Python Programming for Raspberry Pi, Sams Teach Yourself in 24 Hours

(singke) #1

Click here to view code image


$ python3 script0604.py
The value of x is small
$

This works, but it is a somewhat ugly way to solve the problem. Fortunately, there’s an easier
solution.


Python supports the elif statement, which lets you string together multiple if statements and end
with a catch-all else statement. The basic format of the elif statement looks like this:


Click here to view code image


if (condition1):statement1
elif (condition2): statement2
else: statement3

When Python runs this code, it first checks the condition1 result. If that returns a True value,
Python runs statement1 and then exists the if/elif/else statements.


If condition1 evaluates to a False value, Python then checks the condition2 result. If that
returns a True value, Python runs statement2 and then exits the if/elif/else statement.


If condition2 evaluates to a False value, Python runs statement3 and then exits the
if/elif/else statement.


Listing 6.5 shows an example of how to use the elif statement in a program.


LISTING 6.5 Using the elif statement


Click here to view code image


x = 45
if (x > 100):
print("The value of x is very large")
elif (x > 50):
print("The value of x is medium")
elif (x > 25):
print("The value of x is small")
else:
print("The value of x is very small")

When you run the script0605.py code, only one print() statement runs, based on the value
you set the x variable to. By default, you see this output:


Click here to view code image


$ python3 script0605.py
The value of x is small
$

You can see that you have complete control over just what code statements Python runs in the script!


Comparing Values in Python


The operation of the if statement revolves around the comparisons you make. Python provides quite
a variety of comparison operators that allow you to check all types of data. This section walks

Free download pdf