+ 1

Nested if statement question

I am working through the python 3 modules and came across the coding question of: What is the output of this code? num = 7 if num > 3: print("3") if num < 5: print("5") if num ==7: print("7") Now my logic says the output would be : 3 7 but the module says the answer is just: 3 does someone mind explaining why it wouldn't return both values since i assume 7 == 7

14th Oct 2018, 4:19 AM
Fowler Myles
Fowler Myles - avatar
6 Respuestas
+ 2
Indentation is very important in python. An if statement looks like this: if condition: do_something() Everything on the same indentation level as do_something() will only be executed/evaluated if 'condition' is True. If you change your code like this: num = 7 if num > 3: print("3") if num < 5: #not indented print("5") if num ==7: #not indented print("7") ...it will check if num is < 5 or == 7 no matter if num is > 3 or not, because those statements are not indented anymore. So they are independent from the previous code. I hope this makes sense
14th Oct 2018, 5:10 AM
Anna
Anna - avatar
+ 4
in the second if statement (num<5) (7<5) is false so the out put is only 3
14th Oct 2018, 4:58 AM
estifanos
estifanos - avatar
+ 1
That's an explanation right there! thank you so much
14th Oct 2018, 11:04 AM
Fowler Myles
Fowler Myles - avatar
0
I see due to a lack of elif it ends the execution immediately after the false statement
14th Oct 2018, 5:01 AM
Fowler Myles
Fowler Myles - avatar
0
You're welcome 😀
14th Oct 2018, 11:44 AM
Anna
Anna - avatar
0
Due to indentation yo got 3 if you place all if statements in order then it will print 3 and 7
23rd Oct 2024, 3:54 PM
Yasaswani Barri
Yasaswani Barri - avatar