2017-02-22 42 views
-8

如果我有兩個if語句後跟別人那麼第一個基本上忽略:Python的第二個「if語句」否定第一個

x = 3 
if x == 3: 
    test = 'True' 
if x == 5: 
    test = 'False' 
else: 
    test = 'Inconclusive' 

print(test) 

返回:

Inconclusive 

在我看來,因爲第一個if語句是True,所以結果應該是「True」。爲了做到這一點,第二條語句必須改爲「elif」。有誰知道爲什麼?

+2

'else'被連接到前面的'if' ......你在這裏不理解什麼? – miradulo

+0

因爲第二個'if..else'仍然被執行**。你是否想用'if..elif..else'來代替? –

+0

感謝米奇我現在明白了。我最好刪除這個,因爲它會得到很多贊成票:)。我只是認爲它應該看看我沒有意識到他們是獨立的第一個不平等。 – sparrow

回答

4

你有兩個獨立的if語句。第二個這樣的陳述有一個else套房在這裏並不重要; else套件是根據第二個if測試附帶的條件挑選的;無論發生在第一個if聲明並不重要

如果你希望兩個x測試是獨立的,使用一個if聲明和使用elif套件的第二個測試:

if x == 3: 
    test = 'True' 
elif x == 5: 
    test = 'False' 
else: 
    test = 'Inconclusive' 

elif這裏是單if的一部分聲明,現在只有三個塊中的一個被執行。

5

您應該使用if-elif-else來代替。目前,您的代碼執行

x = 3 
if x == 3: # This will be True, so test = "True" 
    test = 'True' 
if x == 5: # This will be also tested because it is a new if statement. It will return False, so it will enter else statement where sets test = "Inconclusive" 
    test = 'False' 
else: 
    test = 'Inconclusive' 

而是使用:

x = 3 
if x == 3: # Will be true, so test = "True" 
    test = 'True' 
elif x == 5: # As first if was already True, this won't run, neither will else statement 
    test = 'False' 
else: 
    test = 'Inconclusive' 

print(test) 
相關問題