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

(singke) #1
print("The value is 50")
else:
print("The value is not 50")

The value is not 50
>>>

When you use the else statement with the if statement, you must be careful how you place the
else statement. If you try to keep it indented, you get an error message from Python:


Click here to view code image


>>> if (x == 50):
print("The value is 50")
else:

SyntaxError: invalid syntax
>>>

The same applies when you’re using the if and else statements in Python scripts. When you’re
creating your script code file, make sure you line up the else statement properly in the text. Listing
6.2 demonstrates this.


LISTING 6.2 Using the else statement in a Python script


Click here to view code image


#!/usr/bin/python
x = 25
if (x == 50):
print("The value is 50")
else:
print("The value is not 50")

The code shown in Listing 6.2 has the else statement at the same indentation level as the if
statement. When you run the script0602.py script, only one of the print() statements will
execute, like this:


$ python3 script0602.py
The value is not 50
$

The same applies when you have multiple statements in either the “if” or “else” sections, and when
you have additional code after the if and else statements block. Listing 6.3 demonstrates a more
complicated if/else statement.


LISTING 6.3 Multiple Statements in the if and else Sections


Click here to view code image


#!/usr/bin/python
x = 25
if (x == 50):
print("The x variable has been set")
Free download pdf