2014-02-14 97 views
1

我希望有人能幫助我。當我運行下面的函數時,無論輸入什麼內容,都會打印規則。我看不出我做錯了什麼。爲什麼我的python if語句不工作?

def check_rules(): 
    while True: 
     request = input("\nWould you like to know the rules? (y/n) ") 
     if request == "y" or "Y": 
      print(""" 
1. Each player takes it in turn to roll a dice. 
2. The player then turns over a card with the same 
    number as the number rolled to see how many ladybirds 
    there are (0-3). 
3. The player keeps the card. 
4. If a player rolls a number that is not on an unclaimed 
    card, play continues to the next player. 
5. Play continues until there are no more cards. 
6. The player with the most number of ladybirds wins.""") 
      break 
     elif request == "n" or "N": 
      break 
     else: 
      print("\nI'm sorry, I didn't understand that.") 

回答

4

你如果格式不正確的語句:

def check_rules(): 
    while True: 
     request = input("\nWould you like to know the rules? (y/n) ") 
     if request in ["y","Y"]: 
      print(""" 
1. Each player takes it in turn to roll a dice. 
2. The player then turns over a card with the same 
    number as the number rolled to see how many ladybirds 
    there are (0-3). 
3. The player keeps the card. 
4. If a player rolls a number that is not on an unclaimed 
    card, play continues to the next player. 
5. Play continues until there are no more cards. 
6. The player with the most number of ladybirds wins.""") 
      break 
     elif request in ["n","N"]: 
      break 
     else: 
      print("\nI'm sorry, I didn't understand that.") 

布爾表達式不能像if something == x or y,你必須說明他們像if something == x or something == y

+0

謝謝。我確實知道這一點。我不敢相信我犯了這樣一個愚蠢的錯誤。再次感謝。 – user3311991

+1

在這種情況下,'如果request.lower()=='y':'可能是最合適的。 – SethMMorton

0

if聲明並不確定請求是否等於yY。如果確定可能爲false的布爾值request == "y"。如果它是假的,則它確定布爾值"Y"。由於非空字符串的計算結果爲True request == "y""Y"始終爲真。

相關問題