簡體   English   中英

為什么Elif在我的while循環中不起作用?

[英]why wont the elif in my while loop work?

我剛開始學習python並嘗試制作一個基本的while循環,但是當我運行它時,它不會運行elif語句,即,如果userguess ==“ tiger”,它就不會打印“ almost”。將不勝感激。 謝謝

animal = "lion"
userguess = raw_input("guess an animal: ")

while userguess != animal:
  userguess = raw_input("guess an animal: ")
  if userguess == animal:
    print("you got it")
    break
  elif userguess == "tiger":
    print("almost, try again: ")
  else:
    print("try again: ")

這是因為在到達if塊之前,您兩次調用raw_input 因此,用戶必須在進行任何檢查之前輸入兩只動物。

guess an animal: tiger
guess an animal: tiger
almost, try again:
guess an animal:

如果您只希望用戶猜測一次,則將第二個raw_input移至循環末尾。

animal = "lion"
userguess = raw_input("guess an animal: ")

while userguess != animal:
  if userguess == animal:
    print("you got it")
    break
  elif userguess == "tiger":
    print("almost, try again: ")
  else:
    print("try again: ")
  userguess = raw_input("guess an animal: ")

或者,將第二個raw_input調用保留在原處,並將第一個調用替換為虛擬值。

animal = "lion"
userguess = None

while userguess != animal:
  userguess = raw_input("guess an animal: ")
  if userguess == animal:
    print("you got it")
    break
  elif userguess == "tiger":
    print("almost, try again: ")
  else:
    print("try again: ")

您還可以完全刪除初始分配以及while循環的條件。 照原樣,該條件永遠不會觸發,因為當animal是“獅子”時,您總是在到達塊的結尾之前就break了。

animal = "lion"

while True:
  userguess = raw_input("guess an animal: ")
  if userguess == animal:
    print("you got it")
    break
  elif userguess == "tiger":
    print("almost, try again: ")
  else:
    print("try again: ")

第二和第三種方法可能比第一種更好,因為即使當用戶在他們的第一次嘗試中猜到“獅子”時,它們也可以確保將“您得到”打印出來。

暫無
暫無

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

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