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

(singke) #1

Click here to view code image


1: >>> the_number = 1
2: >>> while the_number <= 5:
3: ... print (the_number)
4: ... the_number = the_number + 1
5: ...
6: 1
7: 2
8: 3
9: 4
10: 5
11: >>>

In Listing 7.15, the test statement in line 2 checks the variable the_number. As long as that
variable remains less than or equal to 5 , the subsequent Python statements will be executed. The last
Python statement in the while loop on line 4 increases the variable’s value by 1. Thus, when
the_number is equal to 6 , the while loop’s test statement returns false. At that time, the iterations
through the loop stop.


By the Way: Pretest
while loops are pretested, which means the test statement is run before the statements
in the code block are executed. This is why the variable the_number has to have a
value assigned to it before the while loop’s test condition is executed. These types of
loops are called pretested, or entry control loops.

Iterating Using String Conditions


Character strings can be part of the while loop’s condition test statement. In Listing 7.16, the
while test statement examines the variable the_name and sees if it is not equal to (!=) an empty
string. The while loop continues to ask for names and build that list, as long as the script user does
not just press the Enter key for a name.


LISTING 7.16 Test Condition Using Character Strings


Click here to view code image


1:>>> list_of_names = ""
2:>>> the_name = "Start"
3:>>> while the_name != "":
4:... the_name = input("Enter name: ")
5:... list_of_names = list_of_names + the_name
6:...
7:Enter name: Raz
8:Enter name:
9:>>>

Did You Know: Signaling the End
When the Enter key is pressed in Listing 7.16 and the variable the_name is assigned
Free download pdf