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

While true loop to check for numbers within range, and also ValueError check?

我想做的是检查 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检查工作正常,但范围检查被忽略;该代码将继续并计算其中抛出的任何数字。感谢您花时间看我的代码♡

您可能知道,break 关键字退出当前循环。这意味着您应该只在代码中循环达到您想要的效果的地方编写它。

在此循环中,您希望从用户那里获取一个介于 0 和 86399 之间的数字,因此您不应该 break 直到您确定拥有该范围内的数字。在阅读和编写代码时,思考代码中每个阶段的 "known" 是什么是有帮助的:我在下面的代码中注释了每个阶段的 "known" 是什么。

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 是一个数字 并且 在范围内。所以我们不应该在那个时候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.
    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 语句是如何在我们知道错误的代码阶段出现的:我们打印 "Please enter a valid integer" 当我们知道用户输入的不是整数,当我们知道用户输入的数字不在范围内时,我们打印 "Please enter a value between 0 and 86399" 。因此,这种思考代码的方式对于编写正确的代码很有用,而不仅仅是在涉及循环和 break 语句时。