我试图做的是检查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
。在阅读和编写代码时,思考代码中每个阶段“已知”的内容是很有帮助的:我在下面对代码进行了注释,以说明每个阶段“已知”的内容您的
break
语句出现在代码中的某个点,我们知道inputSeconds
是一个数字。但是从逻辑上讲,这不足以停止循环,因为循环的目的是确保inputSeconds
是一个数字,并且它在范围内。所以我们不应该在那一点上。下面是固定的代码,在每个阶段用我们所知道的注释:还要注意
print
语句是如何出现在代码中我们知道错误所在的阶段的:当我们知道用户输入的不是整数时,我们打印“请输入一个有效的整数”,我们打印“请输入一个介于0和86399之间的值”当我们知道用户输入的数字不在范围内时。因此,这种思考代码的方式对于编写正确的代码非常有用,而不仅仅是在循环和break
语句中相关问题 更多 >
编程相关推荐