Python第二个"if语句"否定了第一个

spa*_*row -8 python if-statement

如果我有两个if语句后跟一个else,那么第一个语句基本上被忽略了:

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

print(test) 
Run Code Online (Sandbox Code Playgroud)

返回:

Inconclusive
Run Code Online (Sandbox Code Playgroud)

在我看来,因为第一个if语句是True,所以结果应该是"True".为了使其发生,必须将第二个if语句更改为"elif".有谁知道为什么?

Car*_*ans 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'
Run Code Online (Sandbox Code Playgroud)

而是使用:

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)
Run Code Online (Sandbox Code Playgroud)