+ 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
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
+ 4
in the second if statement (num<5)
(7<5) is false so the out put is only 3
+ 1
That's an explanation right there! thank you so much
0
I see due to a lack of elif it ends the execution immediately after the false statement
0
You're welcome 😀
0
Due to indentation yo got 3 if you place all if statements in order then it will print 3 and 7