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

(singke) #1
print("and the value is 50")
else:
print("The x variable has been set")
print("And the value is not 50")
print("This ends the test")

You can control the output by adjusting the value you assign to the x variable. When you run the script
as is, you get this output:


Click here to view code image


$ python3 script0603.py
The x variable has been set
And the value is not 50
This ends the test
$

If you change the value of x to 50 , you get this output:


Click here to view code image


$ ./script0603.py
The x variable has been set
And the value is 50
This ends the test
$

Everything in the if/else statement blocks is based on the indentation of the statements, so be very
careful when you construct the statement!


Adding More Options Using the elif Statement


So far you’ve seen how to control a block of statements by using either the if statement or the if
and else combination. That gives you quite a bit of flexibility in controlling how your scripts work.
However, there’s more!


Sometimes you need to compare a value against multiple ranges of conditions. One way to solve that
is to string multiple if statements back-to-back, as shown in Listing 6.4.


LISTING 6.4 The script0604.py File


Click here to view code image


#!/usr/bin/python
x = 45
if (x > 100):
print("The value of x is very large")
if (x > 50):
print("The value of x is medium")
if (x > 25):
print("The value of x is small")
if (x <= 25):
print("The value of x is very small")

When you run the script0604.py script, Python executes only one of the print() statements,
based on the value stored in the x variable:

Free download pdf