0
why does the program not evaluate to the last "if statement
4 Respostas
+ 5
num = 7
if num < 3:
print("3")
if num <5:
print("5")
if num == 7:
print("7")
This code will be terminated in line 2 with the first if statement. num is 7 and you check it for num less than 3, so it will respond to False.
If you rearrange your code in terms of indentation there is an other result:
num = 7
if num < 3:
print("3")
if num <5:
print("5")
if num == 7:
print("7")
In this case it will print 7. So you maybe have a closer look on indentation.
+ 3
Terry, there may be a misunderstanding. I did not want to say that Python did not allow nested if statements. It's just to say, that in your sample with num =7 the program never can reach the last if statement if num == 7:, because the program checks the first if statement if num == 3 and evaluates this to False. After line 1 in your code everything is indented, so this is all one code block. If first statement is False, the complete block will be skipped.
But you are right, that in my rearranged sample the program has to check each condition. This can be done normally this way:
num = 7
if num < 3:
print("3")
elif num <5:
print("5")
elif num == 7:
print("7")
else:
print('num is greater than 7')
+ 1
Because it requires all the if statements below to be true.