A very important statement in Python, for controlling the flow of your program, is the if statement. By now the if statement has probably already been used in some of the chapters that you’ve seen, but it’s time to discuss it more in depth. The if statement depends upon a condition to determine whether or not it should execute a suite, or block, of code. If you have a condition that might be false, like and age variable that’s zero, then that block of code will not execute. And so we do not see the printout of ‘False conditions do not execute’, so these statements won’t print. However, if your condition is true, like and age variable that is 1, any non-zero value is considered true. Then we see that that indented suite of code does get executed and those statements did print.
# The if statement allows for conditional execution age = 0 if age: print('False conditions do not execute') print('So, these statements won\'t print') age = 1 if age: print('True conditions execute the') print('indented suite of code') age = 17 if age >= 18: print('You are old enough to vote') else: print('You are too young to vote')
Now the condition doesn’t have to simply be a true or false type of value. It could be based upon comparison with some other value. For example, if the age is set to 17 and the if condition is age >= 18 then the if block will not execute, because that condition is false; 17 is not greater than or equal to 18. Second part of an if statement can be an else clause that will execute when the condition is false. So in this case, the block of code that’s indented under else executed and we see it printed “You are too young to vote.”
score = 91 print('The grade was:', end=' ') if score < 60: print('F') elif 60 <= score < 70: print('D') elif 70 <= score < 79: print('C') elif 80 <= score <90: print('B') elif 90 <= score <= 100: print('A') else: print('Impossible!')
Else-if it was 80 that was less than or equal to the score, and the score was less than 90, it would print 'B', elif 90 was less than or equal to the score, and the score was less than or equal to 100, it would print 'A'. Now assuming the score can only be a maximum of 100, the else clause would print if none of the other if or elif statements were true, which in this case should be 'Impossible'. It's a good idea to always include a else clause, even if you do not expect it to possibly print out, in which case you might print out some message to let you know that something unusual has occurred.
If you happen to have a multiple if elif group of statements, the first if or elif that matches a true condition will execute and none of the other statements within the if block will. We also saw a couple short forms of if, where you could do a one line if true type of condition to execute one statement, or where you could use if to do an assignment.