2016-06-23 32 views
-3

我如何克服python中的條件問題?問題在於它應該根據某些條件顯示某些文本,但是如果輸入爲否,則無論如何都表示是有條件的。Python的原始代碼

def main(y_b,c_y): 
    ans=input('R u Phil?') 
    if ans=='Yes' or 'yes': 
      years=y_b-c_y 
      print('U r',abs(years),'jahre alt') 
    elif ans=='No' or 'no': 
      print("How old r u?") 
    else: 
      print('Sorry') 

main(2012,2016) 
+0

也請閱讀格式下次幫助,SO使用減價不是原始HTML – jonrsharpe

+0

'ans =='是'或'yes''是錯誤的,你知道爲什麼。但我認爲,最好將輸入轉換爲小寫,並與「是」進行比較。 – qvpham

回答

3

or是包容。所以yes測試將始終通過,因爲當ans != 'Yes'其他條件yes具有truthy值。

>>> bool('yes') 
True 

而是應該將測試用:

if ans in ('Yes', 'yeah', 'yes'): 
    # code 
elif ans in ('No', 'Nah', 'no'): 
    # code 
else: 
    # more code 
+0

在這種情況下,他應該使用'in [...']''使用'string.lower()==「yes」'可能會更清晰一些 –

2

當你編寫if語句並且你有多個條件時,你必須寫兩個條件並比較它們。這是錯誤的:

if ans == 'Yes' or 'yes': 

,這是確定的:

if ans == 'Yes' or ans == 'yes': 
1

這不是從其他語言不同:

def main(y_b,c_y): 
    ans = input('R u Phil?') 
    if ans == 'Yes' or ans == 'yes': 
      years = y_b-c_y 
      print('U r', abs(years), 'jahre alt') 
    elif ans == 'No' or ans == 'no': 
      print("How old r u?") 
    else: 
      print('Sorry') 

main(2012,2016) 

但是您可能希望使用一個簡單的測試:

if ans.lower() == 'yes':