当循环卡在范围条件下时



我正试图向用户请求一个整数输入。如果输入在该范围内,它会遍历列表以找到匹配的值。如果输入不在范围内,它会要求用户输入指定范围内的输入。然而,由于某些原因,该值将继续被计算为false,循环将无限继续。

choice1 = input("Select an option from the menu: ")
if choice1 == '1':
year = int(input("Please enter a year: "))
while not year>=1920 or year<=2020:
year = int(input("Please enter a year within range: "))

因此,无论数字是否在范围内,它都会立即进入"while not"条件并保持不变。我试着用";在范围内;然而,我仍然遇到了同样的问题

优先级规则的意思是:

while not year>=1920 or year<=2020:

解析为:

while (not (year>=1920)) or (year<=2020):

因此,任何不大于/等于1920、小于/等于2020的数字都是可以接受的(这实际上意味着你将接受任何小于/等于20的数字;任何小于1920的数字,如果第一次测试不合格,将小于2020,通过第二次测试(。

如果你想像这样进行测距测试,我建议:

while not (1920 <= year <= 2020):
# Parentheses not *needed*, so you could do:
while not 1920 <= year <= 2020:
# but the relative precedence of not and the chained comparison isn't always obvious
# so the parens make it more maintainer friendly

它不仅读起来更清楚一点("虽然年份不在1920年到2020年之间"(,而且性能也稍好一点(只加载一次year(。最低限度的修复可能只是:

while not year>=1920 or not year<=2020:
# or undistributing the not
while not (year>=1920 and year<=2020):
# or checking for failures rather than checking for successes then inverting:
while year < 1920 or year > 2020:

但只要你使用允许条件链接的Python,我认为while not (1920 <= year <= 2020):是最干净的选项(while year < 1920 or year > 2020:也可以,但其他两个更丑陋,很容易出错(。

最新更新