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

(singke) #1
7: # Find out how many club member names need to be entered
8: names_to_enter = int(input("How many Python club member names to enter? "))
9: #
10: for member_number in range (1, names_to_enter + 1): #Loop to enter names
11: print ()
12: print ("Member #" + str(member_number))
13: #
14: first_name = "" # Initialize first_name
15: middle_name = "" # Initialize middle_name
16: last_name = "" # Initialize last_name
17: #
18: while first_name == "": #Loop to keep out blanks
19: first_name = input("First Name: ") #Get first name
20: while middle_name == "": #Loop to keep out blanks
21: middle_name = input("Middle Name: ") #Get middle name
22: while last_name == "": #Loop to keep out blanks
23: last_name = input("Last Name: ") #Get last name
24: #
25: print () # Display a member's full name
26: print ("Member #", member_number, "is", first_name, middle_name, last_
name)
27:
28:
29: pi@raspberrypi ~ $

The first improvement is that the main while loop has been replaced by a for loop, starting on line



  1. Using a for loop eliminates the need to keep track of the number of names that have been entered
    along the way.


Nested within the for loop are three while loops on lines 18, 20, and 22 in Listing 7.21. These
while loops improve the input verification. They ensure that a script user cannot accidentally leave
a name blank.


In Listing 7.22, you can see the new script run and an example of the input verification improvement.
When the script user accidently presses the Enter key instead of entering Raz’s middle name on lines
6 and 7, the script loops back to the input statement and asks again.


LISTING 7.22 Output of script0703.py


Click here to view code image


1: pi@raspberrypi ~ $ python3 py3prog/script0703.py
2: How many Python club member names to enter? 1
3:
4: Member #1
5: First Name: Raz
6: Middle Name:
7: Middle Name:
8: Middle Name: Berry
9: Last Name: Pi
10:
11: Member # 1 is Raz Berry Pi
12: pi@raspberrypi ~ $

Listings 7.21 and 7.22 show a very simple example of a nested loop. Nested loops are often used in
Python scripts for processing data tables, running image algorithms, manipulating games, and so on.

Free download pdf