Part 4.2If statements
The previous article discussed how Python deals with conditions. Crucially, it
is important to know that conditions are evaluated to either
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
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
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
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")