2017-01-29 115 views
0

如何使if語句具有兩個值,即同義詞即「display」和「screen」,然後是and和另一個字符串,如「broken」。這個想法是,只有在出現「顯示」,「破碎」或「屏幕」和「破碎」時纔會輸出。不知道如何在if語句中編寫或和語句

我曾嘗試:

def issuesection(): 
    issue = input("Type in your issue in a sentence and we will try out best to help you with a solution: ") 
    if "display" or "screen" in issue and "broken" in issue: 
     print('WORKED') 
    else: 
     print("FAIL") 

回答

1

的問題是,Python看到:

"display" or "screen" in issue 

爲:

("display") or ("screen" in issue) 

所以它計算的"display"truthness每個非空字符串都是認爲是True

所以你應該把它改寫爲:

if "display" in issue or "screen" in issue and "broken" in issue:

此外,由於你想要的and綁定到兩個in檢查,你也應該括號爲and的左操作數:

if ("display" in issue or "screen" in issue) and "broken" in issue:

現在它說:「如果顯示或屏幕出現問題,條件成立; 損壞以及」。如果沒有方括號,則會顯示: 「如果顯示有問題,則條件成立; 屏幕和損壞問題」。

+0

這是最緊湊的方式嗎? –

+0

可能是的,儘管代碼最小化是一個非常困難的問題。 –

+0

你也可以做任何(x [in [「display」,「screen」]中的x),這個例子比較長,但是你可以在其他位置創建列表和/或添加更多的東西所以更具可擴展性 – Copperfield