2010-08-02 43 views
2

我試過谷歌,但我找不到這個簡單問題的答案。 我討厭自己無法弄清楚這一點,但我們現在就去。我的「if」陳述中的「or」有什麼問題?

如何在or中編寫if語句?

例如:

if raw_input=="dog" or "cat" or "small bird": 
    print "You can have this animal in your house" 
else: 
    print "I'm afraid you can't have this animal in your house." 
+0

您的示例代碼爲「或」荷蘭國際集團的字符串,這是不合法的操作。 – marr75 2010-08-02 14:44:33

+2

@marr它實際上是在執行'(raw_input =='dog')或'cat'或'small bird'',所以如果'raw_input =='dog''或'cat'返回'True' – 2010-08-02 14:45:55

+0

Oops ,你是對的,那將永遠執行。它是or'ing字符串,但這將評估爲「貓」每次,因爲貓是一個字符串,不是空的,它會算作真實的。 – marr75 2010-08-03 04:41:11

回答

11

如果你想使用or,你每次都需要重複整個表達式:

if raw_input == "dog" or raw_input == "cat" or raw_input == "small bird": 

但更好的方法來做到這一點特定的比較與in

if raw_input in ("dog", "cat", "small bird"): 
17

你可以把允許動物進入tuple然後使用in搜索匹配

if raw_input() in ("dog", "cat", "small bird"): 
    print "You can have this animal in your house" 
else: 
    print "I'm afraid you can't have this animal in your house." 

你也可以在這裏使用一個set,但我對此表示懷疑會改善這種少數允許動物的表現

desired_animal = raw_input() 
allowed_animals = set(("dog", "cat", "small bird")) 
if desired_animal in allowed_animals: 
    print "You can have this animal in your house" 
else: 
    print "I'm afraid you can't have this animal in your house." 
+1

+1儘管提出了大多數pythonic解決方案,但它們可以變得更加實用。 – marr75 2010-08-02 14:43:20

+5

@marr這是一個非常微不足道的問題,我不認爲我們需要開始重構它,使它更「功能」 – 2010-08-02 14:44:36

+0

@ marr75,請隨時發佈更實用的答案:) – 2010-08-02 14:50:20

1
if (raw_input=="dog") or (raw_input == "cat") or (raw_input == "small bird"): 
    print You can have this animal in your house 
else: 
    print I'm afraid you can't have this animal in your house. 

if raw_input in ("dog", "cat", "small bird"): 
    print You can have this animal in your house 
else: 
    print I'm afraid you can't have this animal in your house. 
+0

不是很「pythonic」,我寫過這樣的代碼,但我不會推薦給一個新的程序員。 – marr75 2010-08-02 14:42:42

+0

假設raw_input應該是調用raw_input()的函數,你不想調用它3次 – 2010-08-02 14:43:21

0

你可以這樣做

if raw_input=="dog" or raw_input=="cat" or raw_input=="small bird": 
0
goodanimals= ("dog" ,"cat","small bird") 
print("You can have this animal in your house" if raw_input().strip().lower() in goodanimals 
     else "I'm afraid you can't have this animal in your house.")