而true循环检查范围内的数字,以及ValueError检查?

2024-09-30 01:36:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图做的是检查inputSeconds是否在0-83699范围内,同时检查用户是否使用整数(使用ValueError检查)

我已经尝试了很多相同代码的不同迭代,移动东西。。。我对Python还是一个新手,而且我在这方面已经坚持了很长时间,非常感谢您的帮助。♡

下面是我正在努力解决的代码部分:

while True:
    try:
        inputSeconds = int(input("♡ Seconds: "))
        break
    except ValueError:
        print("Please enter a valid integer.")
    else:
        if 0 <= inputSeconds <= 86399:
            break
        else:
            print("Please enter a value between 0 and 86399.")

ValueError检查工作正常,但忽略范围检查;代码将继续计算抛出的任何数字。感谢您抽出时间查看我的代码♡


Tags: 代码true检查用户整数elseintprintenter
1条回答
网友
1楼 · 发布于 2024-09-30 01:36:59

您可能知道,break关键字从当前循环中退出。这意味着您应该只在代码中循环达到您所希望的程度时编写它

在这个循环中,您希望从用户那里获得一个介于0和86399之间的数字,因此在您确定有一个数字在该范围内之前,您不应该break。在阅读和编写代码时,思考代码中每个阶段“已知”的内容是很有帮助的:我在下面对代码进行了注释,以说明每个阶段“已知”的内容

while True:
    try:
        # at this line, we know nothing
        inputSeconds = int(input("♡ Seconds: "))
        # at this line, we know that int worked, so inputSeconds is a number.
        break
    except ValueError:
        # at this line, we know that int didn't work, so we don't have a number.
        print("Please enter a valid integer.")
    else:
        # this line will never be reached, because of the break at the end of
        # the try block.
        if 0 <= inputSeconds <= 86399:
            break
        else:
            print("Please enter a value between 0 and 86399.")

# at this line, the loop stopped because of the break statement in the try block,
# so we know what we knew before that break statement: inputSeconds is a number.

您的break语句出现在代码中的某个点,我们知道inputSeconds是一个数字。但是从逻辑上讲,这不足以停止循环,因为循环的目的是确保inputSeconds是一个数字,并且它在范围内。所以我们不应该在那一点上。下面是固定的代码,在每个阶段用我们所知道的注释:

while True:
    try:
        # at this line, we know nothing
        inputSeconds = int(input("♡ Seconds: "))
        # at this line, we know that int worked, so inputSeconds is a number.
    except ValueError:
        # at this line, we know that int didn't work, so we don't have a number.
        print("Please enter a valid integer.")
    else:
        # this line is reached when the try block finishes, so we know the same
        # thing we knew at the end of the try block: inputSeconds is a number.
        if 0 <= inputSeconds <= 86399:
            # now we know that inputSeconds is a number and it is within range.
            break
        else:
            # now we know that inputSeconds is a number and it is not within range.
            print("Please enter a value between 0 and 86399.")

# at this line, the loop stopped because of the break statement in the else block,
# so we know what we knew before that break statement: inputSeconds is a number
# and it is within range.

还要注意print语句是如何出现在代码中我们知道错误所在的阶段的:当我们知道用户输入的不是整数时,我们打印“请输入一个有效的整数”,我们打印“请输入一个介于0和86399之间的值”当我们知道用户输入的数字不在范围内时。因此,这种思考代码的方式对于编写正确的代码非常有用,而不仅仅是在循环和break语句中

相关问题 更多 >

    热门问题