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

(singke) #1
>>> if (x == 50): print("The value is 50")

The value is 50


  1. Try another test using another condition:
    Click here to view code image



    if (x < 100): print("The value is less than 100")
    The value is less than 100






  2. Try a test condition that should fail:
    Click here to view code image



    if (x > 100): print("The value is more than 100")







>>>

With the if statement, each time you enter the statement and press the Enter key, the IDLE interface
pauses on the next line to see if you’re going to enter any more statements. You just press the Enter
key again to close out the statement.


In the first example, the condition checks to see if the variable x is equal to 50. (We talk about the
double equal sign in the “Comparison Conditions” section, later in this chapter.) Since it is, Python
executes the print() statement on the line and prints the string.


Likewise, the second example checks whether the value stored in the x variable is less than 100.
Since it is, Python again executes the print() statement to display the string.


However, in the third example, the value stored in the x variable is not greater than 100, so the
condition returns a False logic value, causing Python to skip the print() statement after the
semicolon.


Grouping Multiple Statements


The basic if statement format allows you to process one statement based on the outcome of the
condition. More often than not, though, you want to group multiple statements together, based on the
outcome of the condition. This is another place where the Python if statement format deviates from
other programming languages.


Many programming languages use either braces or a keyword to indicate the group of statements that
the if statement controls. Instead of grouping statements together using either braces or a special
keyword, Python uses indentation.


To group a bunch of statements together, you must place them each on separate lines in the script and
indent them from the location of the if statement. Here’s an example:


Click here to view code image


>>> if (x == 50):
print("The x variable has been set")
print("and the value is 50")

The x variable has been set
and the value is 50
>>>
Free download pdf