2017-02-22 371 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) 
相关问题