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

(singke) #1

  1. Type python3 py3prog/script0701.py again and press Enter to run the
    script. This time, answer the question incorrectly, answering anything except
    secret. You should see output similar to that shown in Figure 7.3.


FIGURE 7.3 The script0701.py output with incorrect answers.

Input verification is an important tool. The little script you just created is a small example of what
you can do with a for loop to verify user input. A while loop, as you’ll see next, is another type of
loop to use for input verification in Python scripts.


Using the while Loop for Iteration


In Python, the while loop construct is called a “condition-controlled” loop because the loop’s set of
tasks are performed until a desired condition is met. Once the condition is met, the iterations stop. For
example, you might want a loop’s set tasks to be performed until a certain condition is no longer true.
In such a case, you would use a while loop in Python.


The syntax structure of the while loop in Python is as follows:


Click here to view code image


while condition_test_statement:
set_of_Python_statements

Just like the for loop, the while loop uses indentation to denote the Python statements associated
with it (code block). condition_test_statement examines a condition, and if the condition
is found to be true, Python statements within the loop’s code block are executed. For each iteration,
the condition is checked. If the condition is examined and found to be false, the iterations stop.


Iterating Using Numeric Conditions


You can use a number or mathematical equation in a while loop’s condition test statement. Listing
7.15, for example, shows a mathematical condition used in a while loop.


LISTING 7.15 A while Loop

Free download pdf