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

(singke) #1
9:
10: >>>

The test statement in the while loop returns false before the loop’s statements even iterates one
time. However, the else section still executes, and thus a blank line prints on line 9! You can see
that the else clause operates very differently in a while loop than it does in an if-then-else
statement.


Using while True


An infinite loop can be created using a while loop. An infinite loop is a loop that never ends.
Adding a break statement to this type of a while loop makes it usable. Take a look at Listing 7.19.
The while test statement has been modified on line 3 to while True:, and this causes the loop to
be infinite. This means the while loop will iterate indefinitely. Thus, line 5 tests for an added
sentinel value within the loop. If the Enter key is pressed without a name being typed first, the if
statement returns a true value, and break is executed. Thus, the infinite loop stops.


LISTING 7.19 while True and break


Click here to view code image


1: >>> list_of_names = ""
2: >>> the_name = "Start"
3: >>> while True:
4: ... the_name = input("Enter name: ")
5: ... if the_name == "":
6: ... break
7: ... list_of_names += the_name
8: ... else:
9: ... print (list_of_names)
10: ...
11: Enter name: Raz
12: Enter name: Berry
13: Enter name: Pi
14: Enter name:
15:>>>

Another item to notice in Listing 7.19 is that the else clause is not executed. This is because when
you issue a break in a loop, any Python statements in the else clause are skipped. You simply
“jump” right out of the while loop. To get the list of names printed out, you remove the else clause
and move the print statement to an if statement before the break, as shown in Listing 7.20.


LISTING 7.20 An else Clause Fix


Click here to view code image


>>> list_of_names = ""
>>> the_name = "Start"
>>> while True:
... the_name = input("Enter name: ")
... if the_name == "":
Free download pdf