The previous article discussed how Python deals with conditions. Crucially, it
is important to know that conditions are evaluated to either True
or False.
To reinforce the use of conditions before moving to this first method of flow control, the following sample contains three conditions:
c1 = (5 + 10 > 20) or True c2 = (5 + 10 < 20) and True c3 = False and True print(c1) print(c2) print(c3)
Both conditions return True.
If statements
If statements are so crucial in flow control. In the simplest of senses, an if statement will evaluate a condition and decide where to go from there. In computer science terms, this is referred to as code branching or selection.
An if statement can have just one route or multiple routes. If an if statement is given no second route, it will only change the flow of the program if the actual condition is satisfied.
The following is an example of an if statement with just one route.
if 5 > 3: print ("It is")
In this example, if 5 is greater than 3 (which it is, of course) Python will
print It is. Note the importance of the colon : at the end
of the condition.
Mentioned earlier was the concept of an if statement with multiple routes. When
an if statement has an else it can follow an alternative route,
in fact, an if statement with an else in it has an
infinite number of routes - meaning that all code will enter the if statement one
way or another.
The following sample shows an if statement with an else
in it:
x = float(input("Insert a value")) if 5 > x: print ("It is") else: print ("It is not")
But what about a situation that says something different for when it is not greater than 5, but also not less than 5 but equal to 5? That's where else-if branches come in.
In Python, else if is achieved with the elif keyword. The following
sample expands upon the previous one, adding this branch in to it.
x = float(input("Insert a value")) if 5 > x: print ("5 is greater than your input") elif 5 == x: print ("5 is equal to your input") else: print ("5 is less than your input")
- Change the values used in the conditions and observe how the output changes.
- Modify an
ifstatement so that its condition evaluates toFalse. - Add an
elsebranch to an existingifstatement. - Modify the messages printed by the program so that they describe a different condition.
Rewrite the program so that it checks whether a number is greater than 10.
x = 15 if x > 10: print("The number is greater than 10")
Modify the following program so that the else branch is executed.
age = 20 if age < 18: print("Child") else: print("Adult")
Extension challenge: Ask the user for their age. If the age is less than 16, display "Too young to drive"; otherwise display "Old enough to learn to drive".
