+ 1
num == 7
num = 7 if num > 3: print("3") if num < 5: print("5") if num ==7: print("7") At the end of this code, "if num ==7", I'm not sure I understand why this is false, do you substitute the "num" with 7 from the top here? Could someone please explain? Thank you!
9 ответов
+ 5
Hello Xi Wang, you just need to corrext the indentation in your code: the 'if' statements should be aligned vertically for this code to execute as intended eg:
if num>3:
print("3')
if num<5:
print("5")
if num==7:
print("7")
+ 5
num = 7
if num > 3: #the condition is true and it prints "3"
print("3")
if num < 5: #the condition is false. so it doesn't print "5"
print("5")
if num ==7:
print("7")
# In here, even if the condition is True since the above condition is false (num < 5). Python does not move on and check for the last condition. it terminates the code in the second condition. so it only prints "3"
+ 4
if num > 3 -> true
if num < 5 -> false
-> the rest of the code belongs to this block so it will not be executed.
+ 4
And maybe this code helps you:
https://code.sololearn.com/cT5BRIbkia21/?ref=app
+ 4
num = 7
Is <num> greater than 3? yes
Print 3
Is <num> less than 5? No
Any statement or block of statements following the above condition will not be processed because the evaluation results in false (<num> is 7 and it is not less than 5).
+ 4
Probably anything that happens after false will block another statement depending from the code.
A little advice from a learner.
PS: I'm not sure if this advice is 100% correct.
Edit: Maybe your indentions are wrong. Try checking and editing them again. Then it might work.
+ 3
Buddy here you are using ladder of if-else....
Lets, check step-wise...
num = 7
if num > 3: #since num=7 it is true
print("3")
if num < 5: #since num=7 it is false
print("5")
if num ==7: #this won't get chance
print("7")
+ 3
First evaluate if num is greater than 3 and that's true then evaluate if num is lower than 5 that's false so the next if statements inside this one will not be executed.
+ 3
One word: Indentation. if num == 7 is a part of the block for if num < 5, so it will never execute, no matter the number (because 7 is not less than 5)