2017-06-12 58 views
1

只是學習如何編寫代碼,並想製作一個小程序來查看我所知道的內容。如果聲明沒有讀取輸入

n = int(input("Pick a number any Number: ")) 
if n > 100: 
    print ("No... Not that Number") 
else: 
    answer = input("Would you like to know your number?") 
    if answer == "Y" or "Yes" or "y" or "yes": 
     print ("Your number is %s" % (n)) 
    elif answer == "N" or "No" or "n" or "no" or "NO": 
     print ("Oh, well that's a shame then.") 
    else: 
     print ("Please type Yes or No") 

input("Press Enter/Return to Exit") 

一切正常,除了第二if語句,它不遵循任何進入input數據。爲什麼會這樣做?

+1

糾正壓痕第一 –

+0

是整個代碼或者這是一個while循環的身體? – Rosh

回答

0

==具有比or更高的優先級。因此,在if條件中,您將檢查answer == 'Y'然後or這個布爾表達式與"Yes"(它是非None字符串),因此它評估爲True。相反,你應該使用in操作,以檢查是否answer是你感興趣的值之一:

if answer in ("Y", "Yes", "y", "yes"): 
    print ("Your number is %s" % (n)) 
elif answer in ("N", "No", "n", "no", "NO"): 
    print ("Oh, well that's a shame then.") 
else: 
    print ("Please type Yes or No") 
+0

即使優先權被改變,它也不起作用; '或'根本不遵循英語語法規則。 –

1

Python是不是人,它不理解

if answer == "Y" or "Yes" 

方式你的意思是。你應該做

if answer == 'Y' or answer == 'Yes' 

甚至更​​好

if answer in ('Yes', 'Y', 'yes', 'y') 

甚至更​​短的

if answer.lower() in ('yes', 'y')