0

python if statement

Hi guys, Can anyone explain me why the output of this statement is 3 rather than 7? Really appreciated! num = 7 if num > 3: print("3") if num < 5: print("5") if num ==7: print("7")

13th Jan 2018, 12:29 PM
Tianyuan Liu
Tianyuan Liu - avatar
3 Antworten
+ 2
The third if is only executed if the first and second if are also true. The first if is true, the second is not. So only the first print statement is executed.
13th Jan 2018, 12:41 PM
Paul
Paul - avatar
+ 2
It's called a nested if construction. if num < 5 is False, so it doesn't execute the code in the block, where is if num == 7. if condition 1 is True: | block of 1st if | | | if condition 2 is True: | | block of 2nd if | | | | | if condition 3 is True: | | | block of 3rd if | | | | | 1 2 3 | 0 (global scope)
13th Jan 2018, 2:32 PM
Boris Batinkov
Boris Batinkov - avatar
+ 1
it never gets past if num < 5 .. if that returns false it doesn't go into it
13th Jan 2018, 12:40 PM
LordHill
LordHill - avatar