When you enter the code to test this in IDLE, after you press the Enter key for the if statement, IDLE
automatically indents the next line for you. All the statements that you enter after that are considered
part of the “then” section of the statement and are controlled by the condition.
When you’re done entering statements, you just press the Enter key on an empty line.
If you’re working with if statements in a Python script, you have to remember to manually indent the
“then” section statements. You indicate the lines outside the “if” section by not indenting them. Listing
6.1 shows an example of doing this.
LISTING 6.1 Using if Statements in Python Scripts
Click here to view code image
1: #!/usr/bin/python
2: x = 50
3: if (x == 50):
4: print("The x variable has been set")
5: print("and the value is 50")
6: print("This statement executes no matter what the value is")
Notice how lines 4 and 5 are indented from the location of the if statement on line 3. The print()
statement on line 6 isn’t indented, though. This means it’s not part of the “then” section.
To test it, run the script0601.py program from the command line:
Click here to view code image
$ python3 script0601.py
The x variable has been set
And the value is 50
This statement executes no matter what the value is
$
Now if you change the code to set the value of x to 25 , you get the following output:
Click here to view code image
$ ./script0601.py
This statement executes no matter what the value is
$
Python skips the print() statements inside the “then” section but picks up with the next print()
statement that’s not indented.
Adding Other Options with the else Statement
In the if statement, you only have one option of whether to run statements. If the condition returns a
False logic value, Python just moves on to the next statement in the script. It would be nice to be
able to execute an alternative set of statements when the condition is False. That’s exactly what the
else statement allows you to do.
The else statement provides another group of commands in the statement:
Click here to view code image
>>> x = 25
>>> if (x == 50):