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

(singke) #1
an empty string or null value, it causes the while loop to terminate. A data value used
in this way is called a sentinel value. A sentinel value is any predetermined value that
is used to indicate the end of the data. Thus, sentinel values can be used for terminating
while loops.

A nice tweak on the while loop in Listing 7.16 is to replace the very long code in line 5 with a more
efficient statement that uses an operator shortcut. You learned about operator shortcuts, also called
augmented assignment operators, in Hour 5, “Using Arithmetic in Your Programs.” With an operator
shortcut, line 5 would now look like this:


list_of_names += the_name

Another nice tweak you can make is to include an optional else clause in the while loop. If you
included these two changes, Listing 7.16 would become Listing 7.17.


LISTING 7.17 An else Clause in a while Loop


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 += the_name
6: ... else:
7: ... print (list_of_names)
8: ...
9: Enter name: Raz
10: Enter name: Berry
11: Enter name: Pi
12: Enter name:
13: RazBerryPi
14: >>>

In Listing 7.17, the list_of_names variable is printed after the while loop terminates.
However, you should know that an else clause is executed whenever the while loop’s test
statement returns false, which could be the very first time it is tested! Listing 7.18 shows a few
changes made to the Python statements to demonstrate this potential problem.


LISTING 7.18 And else Clause Problem Due to a Pretest


Click here to view code image


1: >>> list_of_names = ""
2: >>> the_name = "Start"
3: >>> while the_name != "Start":
4: ... the_name = input("Enter name: ")
5: ... list_of_names += the_name
6: ... else:
7: ... print (list_of_names)
8: ...
Free download pdf