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

(singke) #1

Hour 6. Controlling Your Program


What You’ll Learn in This Hour:
How to use if-then statements
How to group multiple statements
How to add else sections
Stringing together if-then statements
Testing conditions

In all the Python scripts discussed so far, Python processes each individual statement in the script in
the order in which it appears. This works out fine for sequential operations, where you want all the
operations to process in the proper order. However, this isn’t how all programs operate.


Many programs require some sort of logic flow control between the statements in the script. This
means that Python executes certain statements given one set of circumstances but has the ability to
execute other statements given a different set of circumstances. A whole class of statements, called
structured commands, allow Python to skip over or loop through statements based on conditions of
variables or values.


There are quite a few structured commands available in Python, and we look at them individually. In
this hour, we look at the if statement.


Working with the if Statement


The most basic type of structured command is the if statement. The if statement in Python has the
following basic format:


if (condition): statement

If you have ever used if statements in other programming languages, this format may seem somewhat
odd because there’s no “then” keyword in the statement.


Python uses the semicolon to act as the “then” keyword. Python evaluates the condition in the
parentheses and then either executes the statement after the semicolon if the condition returns a True
logic value or skips the statement after the semicolon if the condition returns a False logic value.


Try It Yourself: Using the if statement
Let’s walk through a few examples to show using the if statement:


  1. Open the Python3 IDLE interface on your graphical desktop (see Hour 3, “Setting Up
    a Programming Environment”).

  2. Set a value for a variable:



    x = 50






  3. Test the variable value using an if statement:
    Click here to view code image

Free download pdf