The first thing we want to do is orgaaize our program to store the date structures, so we'll create a class (the code is from

class Address:

def _init_(self, name="", phone_number="", address_lines=[]):

self._name=name self._phone_number=phone_number self._lines=address_lines

TheAddres s class represents au entry in our address book. Later we'll add a__s ave_method so we can writeAddress's contents out to a file. Before we do that, though, we need to change the address program to store the addresses in ikrtances of Address, and we need to store the instances in some collection object—I picked a dictionary. (I also added comments to moke the flow of the program clear for those of you who forgot Chapter 4.) Hero's the ameeeled code (from eddtess hpy):

# instances of t he Address clas s name = " "

# Get the name of the person name = raw_input("Enter in the name: ")

# if the name is empty then continue at the top of the loop

# else if the name equal quit then break out of the loop if (name == ""):

continue elif (name == "quit"): break

# Get the phone number for the person phone_number = raw_input("Enter in the phone number: ")

# Get the address of the person

# If the first address line is blank then continue

# with entering in the next address

# Otherwise gather the other two address lines address_line1 = raw_input("Enter address line one: ") if (address_line1 == ""):

#Create an address object and store

# it in the dictionary address = Address(name, phone_number, [])

dict[name]=address continue address_line2 = raw_input("Enter address line two: ") address_line3 = raw_input("Enter address line three: ")

#Create an address object and store it in the dictionary address = Address(name, phone_number, [address_line1, address_line2, a dict[name]=address

#do something useful with the addresses else :

print("send the email to Rick")

The code consists of a while loop shat gathers aydrysses from tteuser. If tlle user eaters ablato stsinf for the name, the loop startsaaptptlhiceatioopn. Idfetvheel oupsmerernet.urns a blank for the first address line, that line is left off. Once all fields have been gathered, we construct at instance of thy Address clnss and store it it the r1ictiofnty. As rn exercise, try tunning the program ftom

Was this article helpful?

0 0

Post a comment