簡體   English   中英

具有多個條件的Python While循環

[英]Python While Loop with multiple conditions

任何人都可以幫助我為什么while循環無法正常工作嗎? 它迫使用戶選擇1、2或3,而不讓他們繼續操作,但是無論您輸入1、2還是3,它總是表明您輸入了另一個數字,因此說“請選擇1、2或3級

level = input("Enter your level by typing 1, 2 or 3\n")
int(level)

levelSelect = 1
while levelSelect == 1:
   if level != int(1) or level != 2 or level != 3:
      level = input("Please choose level 1, 2 or 3\n")
      int(level)
   else:
      print("You have selected level", level)
      levelSelect = 0

int(level)行沒有執行您認為的操作。 它從字符串創建一個整數並返回它。 它沒有在原地運行。 因此,當您進入if語句時,您正在將字符串與始終不相等的整數進行比較。

您可能想要:

level = int(level)

附帶說明,條件也可以使用in運算符編寫:

if level in (1,2,3):
   print("level is ...")
else:
   print("pick again!")
   #other code ...

請參閱mgilson關於將分配級別作為整數的答案,但是您在確定“級別”是否合法時的邏輯也是錯誤的。

更改:

if level != int(1) or level != 2 or level != 3:

對於:

if level not in (1,2,3)

我想這就是您想要的(Inbar Rose的道具)

def get_level():
    while True:
        level = int(input("Enter your level by typing 1, 2 or 3\n"))
            if level in [1, 2, 3]:
                return level

mgilson已在此處指出了核心問題,但是我將提出建議以改進您的代碼。

while True:
    level = input('Enter level: ')
    if level not in ('1','2','3'):
        print('Try again!\n')
    else:
        print('You chose level ', level)
        break

暫無
暫無

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

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