0

why does the program not evaluate to the last "if statement

https://code.sololearn.com/c77wN54Nor8f/?ref=app

16th Sep 2019, 2:44 PM
Terry
Terry - avatar
4 ответов
+ 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.
16th Sep 2019, 3:41 PM
Lothar
Lothar - avatar
+ 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')
17th Sep 2019, 2:41 PM
Lothar
Lothar - avatar
+ 1
Because it requires all the if statements below to be true.
16th Sep 2019, 2:45 PM
Airree
Airree - avatar
0
Lothar in this case, are you saying Python doesn't allow for *nested IFs* because considering your example, each IF has to be run by the program to get the desired output
17th Sep 2019, 8:40 AM
Terry
Terry - avatar