簡體   English   中英

while 循環卡在范圍條件

[英]While loop stuck in range condition

我正在嘗試向用戶詢問 integer 輸入。 如果輸入在范圍內,它會遍歷列表以找到其匹配值。 如果輸入不在范圍內,它會要求用戶輸入指定范圍內的輸入。 但是,出於某種原因,該值將繼續被計為 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: "))

因此,無論該數字是否在范圍內,它都會立即將 go 變為 'while not' 條件並停留在那里。 我嘗試使用“在范圍內”,但是,我仍然遇到同樣的問題

優先規則的意思是:

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

被解析為:

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

因此,任何不大於/等於 1920小於/等於 2020 的數字都被接受(這實際上意味着您將接受任何小於/等於 2020 的數字;任何小於 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:也可以,但其他兩個是更難看而且很容易出錯)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM