In class we have to create a save/load function utilizing the split() method for a class and dictionary. I managed to get the save function working, but the load function does not seem to want to work for me. I either get it almost working but the saved file does not load, or i get the error
"playerclass" has no "player" attribute. needs to use the init method. Here is the code in its entirety def loaddata(): is mainly the area of concern.
class playerclass:
name = ""
phone = ""
jersey = ""
def __init__(self, name, phone, jersey):
self.name = name
self.phone = phone
self.jersey = jersey
def setname(self, name):
self.name = name
def setphone(self, phone):
self.phone = phone
def setjersey(self, jersey):
self.jersey = jersey
def getname(self):
return self.name
def getphone(self):
return self.phone
def getjersey(self):
return self.jersey
def disroster(self):
print("Player Bio")
print("-----------")
print("Name: ", self.name)
print("Phone #: ", self.phone)
print("Jersey #: ", self.jersey)
def savedata (players):
filename = input("Enter file name: ")
print("Saving....")
outFile = open(filename, "wt")
for x in players.keys():
name = players[x].getname()
phone = str(players[x].getphone())
jersey = str(players[x].getjersey())
outFile.write(name+","+phone+","+jersey+"\n")
print("Save Complete")
outFile.close()
def loaddata ():
players = {}
filename =input("Enter filename to load: ")
inFile = open(filename, "rt")
print("Loading.....")
while True:
inLine = inFile.readline()
if not inLine:
break
inLine = inLine [:-1]
name, phone, jersey = inLine.split(",")
players[name] = playerclass(name, phone, jersey)
print("Load Successfull.")
inFile.close()
return players
def roster(players):
if len(players) == 0:
print("No players on roster: ")
else:
for x in players.keys():
players[x].disroster()
def add_player (players):
newName=input("Enter name of player to add: ")
newPhone = int(input("Enter phone number of player: "))
newJersey = int(input("Enter number of assigned jersey: "))
players[newName]= playerclass(newName, newPhone, newJersey)
return players
def ed_player (players):
oldName = input("Enter players name to edit: ")
if oldName in players:
newName = input("Enter new name for player: ")
newPhone = int(input("Enter new phone number for player: "))
newJersey = int(input("Enter newly assigned jersey number: "))
players[oldName] = playerclass(newName, newPhone, newJersey)
return players
def del_player(players):
delName = input("Enter players name to delete from roster: ")
if delName in players:
del players[delName]
return players
def displayMenu():
print("-------Main Menu-------")
print("1. Display Team Roster.")
print("2. Add Member.")
print("3. Remove Member.")
print("4. Edit Member.")
print("5. Save Data.")
print("6. Load Data.")
print("9. Exit Program.")
return input("Menu Choice: ")
print("Team Management Tools.")
players = {}
menu_choice = displayMenu()
while menu_choice != '9':
if menu_choice == '1':
roster(players)
elif menu_choice == '2':
players = add_player (players)
elif menu_choice == '3':
players = del_player (players)
elif menu_choice == '4':
players = ed_player (players)
elif menu_choice == '5':
savedata (players)
elif menu_choice == '6':
loaddata ()
menu_choice = displayMenu()
print("Updating roster Goodbye:")
Remove players = {} from your loaddata function, and it'll load properly.
If you actually want to reset the contents of the dictionary when loading (which might have been your intent, although I would say that's a questionable design decision), you can do:
def loaddata():
global players
players = {}
...
This is because any variables you write to are assumed to be local variables (as in, local to the function) unless you say otherwise.
I might be overlooking something, but I'm not seeing anything that attempts to read a player attribute from any object, so I'm not sure where the error is coming from. Was it from a different version of this code? Or, if it is the posted version that has that error, can you provide exactly what series of inputs lead to the error?
The rest of this answer isn't directly relevant to your question, just some tips based on things I noticed in your code.
I would remove the:
name = ""
phone = ""
jersey = ""
Because you set them in __init__ and so they're redundant and not doing anything. For looping over lines in files, you can use a for loop, which is more readable than while loops. Example:
for line in infile:
print(line)
And you should look into with. It's another type of block, and they're very useful when working with files because they'll automatically close the file when the block ends, so you don't have to. As an example:
with open("foo", "r") as stream:
for line in stream:
print(line)
# stream got implicitly closed because the block ended
Related
I'm working on an exercise, but I'm stuck on the last part
The section goes here:
Rewrite the function remove_friend so it asks for both the firstname and the lastname and remove all in the list_of_friends for which the first- and last name of the friend object equals the first- and last name entered by the user
In the remove_friends function, I know it's not correct.
In my head, I think I need to compare the delete_first_name and delete_last_name against the first_name and last_name in the new_friends class.
However, I don't know what the syntax would be in order to accomplish this.
Does anyone have hints on how to proceed? I would greatly appreciate if you could give suggestions, and not write the solution.
class Friend:
def __init__(self, first_name, last_name, phone_number):
self.first_name = first_name
self.last_name = last_name
self.phone_number = phone_number
def print_info(self, index):
print(f"\n {self.first_name}, {self.last_name}, {self.phone_number} \n")
list_of_friends = []
def add_friends():
print(" ")
first_name = input("Enter the first name: ")
last_name = input("Enter the last name: ")
phone_number = input("Enter the phone number: ")
new_friend = Friend(first_name.upper(), last_name.upper(), phone_number)
list_of_friends.append(new_friend)
print(f"{new_friend.first_name.title()} {new_friend.last_name.title()} has been added to the list \n")
def view_friends():
if len(list_of_friends):
for counter, new_friend in enumerate(list_of_friends, 0):
print(" ")
new_friend.print_info(counter)
else:
print(" ")
print("List is empty \n")
def remove_friends():
print(" ")
delete_first_name = input("Enter first name to remove: ").upper()
delete_last_name = input("Enter last name to remove: ").upper()
full_name = [delete_first_name, delete_last_name]
if full_name not in list_of_friends:
print(f"{delete_first_name} {delete_last_name} does not exist in the list \n")
else:
list_of_friends.remove(delete_first_name)
list_of_friends.remove(delete_last_name)
print(f"{delete_first_name} {delete_last_name}has been deleted from the list \n")
def print_menu():
menu_string = "\n----Options----\n"
menu_string += "1: Add\n"
menu_string += "2: View\n"
menu_string += "3: Remove\n"
menu_string += "4: Exit\n"
print(menu_string)
user_input = 0
while user_input != 4:
print_menu()
try:
user_input = int(input("Choose one of the above options: "))
if user_input < 1 or user_input > 4:
print("Invalid number. Number must be between 1-4 \n")
elif user_input == 1:
add_friends()
elif user_input == 2:
view_friends()
elif user_input == 3:
remove_friends()
except Exception as err:
print(f"Invalid input: {err}")
print("Exiting \n")
Loop the the list of friends and check first and last name
def remove_friends():
print(" ")
delete_first_name = input("Enter first name to remove: ").upper()
delete_last_name = input("Enter last name to remove: ").upper()
new_list = []
for frnds in list_of_friends:
fnm = frnds.first_name
lnm = frnds.last_name
if(fnm == delete_first_name and lnm == delete_last_name):
# print something meaningfull
continue
else:
new_list.append(frnds)
# new_list will contain the list of friends after removal
The list list_friends has Friend objects and not strings.
you need to access the Friend attributes.
for example like this (function is not complete):
def remove_friends():
first_name=...
last_name = ...
temp_list = list_of_friends[:]
for friend in temp_list :
if first_name == friend.first_name and last_name == friend.last_name:
list_of_friends.remove(friend)
Note that in the beginning I copied the list - do not iterate over a list (or similar) and delete objects from the same list, it is a recipe for bugs.
I have an error that I can not get my head around. The code is as follows:
def saveData():
filename = input("Filename to save: ")
print("Saving Data...")
outFile = open(filename, "wt")
for x in team.keys():
name = team[x].getname()
phone = team[x].getphone()
jersey = team[x].getjersey()
outFile.write
(name+", "+phone+", "+jersey+"\n")
print("Data saved.")
outFile.close()
def loadData():
self = {}
filename = input("Filename to load: ")
inFile = open(filename, "rt")
print("Loading data...")
while True:
inLine = inFile.readline()
if not inLine:
break
inLine = inLine[:-1]
name, phone, jersey = inLine.split(", ")
team[name] = self(name, phone, jersey)
print("Data Loaded Successfully.")
inFile.close()
return self
class teamClass:
name = ""
phone = 0
jersey = 0
def __init__(self, name, phone, jersey):
self.name = name
self.phone = phone
self.jersey = jersey
def setName(self, name):
self.name = name
def setPhone(self, phone):
self.phone = phone
def setJersey(self, jersey):
self.jersey = jersey
def getName(self, name):
return name
def getPhone(self, phone):
return phone
def getJersey(self, jersey):
return jersey
def displayData(team):
print("\n")
print("Welcome to the Team Manager")
print("---------------------------")
print("Name: ", team.name)
print("Phone #: ", team.phone)
print("Jersey #: ", team.jersey)
print("\n")
def displayMenu():
print("--------Main Menu--------")
print("\n1. Display Team")
print("2. Add Member")
print("3. Remove Member")
print("4. Edit Member")
print("9. Exit Program")
print("\n")
return int(input("Selection: "))
def printTeam(team):
if len(team) == 0:
print("No team members in memory.")
else:
for x in team.keys():
team.displayData()
def addTeam(team):
newName = input("Enter the new player name: ")
newPhone = input("Enter the phone #: ")
newJersey = input("Enter the jersey #: ")
team[newName] = teamClass(newName, newPhone, newJersey)
return team
def removeTeam(team):
removeName = input("Enter the member to be removed: ")
if removeName in team:
del team[removeName]
else:
print("Team member not found.")
return team
def editTeam(team):
oldName = input("Enter the player you want to edit: ")
if oldName in team:
newName = input("Enter the new name: ")
newPhone = input("Enter the new phone number: ")
newJersey = input("Enter the jersey #: ")
else:
print("Team member not found")
return team
print("Welcome to the Team Manager")
loadData()
team = {}
menuSelection displayMenu()
while menuSelection != 9:
if menuSelection == 1:
printTeam(team)
elif menuSelection == 2:
team = addTeam(team)
elif menuSelection == 3:
team = removeTeam(team)
elif menuSelection == 4:
team = editTeam(team)
menuSelection = displayMenu()
saveData()
print("Exiting Program...")
I get this error once I add a member and try to display the dictionary:
Traceback (most recent call last):
File "C:/Users/Gameradvocat3/PycharmProjects/Week6/Week6.py", line 121, in <module>
printTeam(team)
File "C:/Users/Gameradvocat3/PycharmProjects/Week6/Week6.py", line 83, in printTeam
team.displayData()
AttributeError: 'dict' object has no attribute 'displayData'
Thank you all! I can not figure this out, this is for my Programming Essentials class. The only reason I am reaching out is because I have combed through the code and the literature from class and I can not figure out why this is not working.
The class teamClass has no function displayData() you are calling printTeam() from your menu-screen with a dictionary of teamClass-objects:
def printTeam(team):
if len(team) == 0:
print("No team members in memory.")
else:
for x in team.keys():
displayData(team[x]) # not team.displayData() - thats a class method call
In case you want to make it a class method you need to indent it and give it a first param of self but then other parts of your code need to be adjusted as the method currently is not fit to be a class-function.
I corrected all errors that hindered you from running this. The fixes are minimal effort on my side and lots of stuff could be made neater - ask on codereview for that. Look / ggogle / search SO for python csv - thats better for reading/writing csv data then what you did manually.
def saveData(team):
filename = input("Filename to save: ")
if not filename: # fix for non.input
filename = "temp.csv"
print("Saving Data...")
with open(filename, "wt") as outFile: # with paradigma for file
for x in team.keys():
name = team[x].name # spelling error
phone = team[x].phone # spelling error
jersey = team[x].jersey # spelling error
outFile.write(name + ", " + phone + ", " + jersey + "\n")
print("Data saved.")
def loadData():
d = {} # do not use self , you could buts bad habit
filename = input("Filename to load: ")
if not filename: # if no name given, dont load, return empty
return {}
with open(filename, "rt") as inFile: # with paradig for open
print("Loading data...") # look into module csv
while True:
inLine = inFile.readline()
if not inLine:
break
inLine = inLine[:-1]
name, phone, jersey = inLine.split(", ")
d[name] = teamClass(name, phone, jersey)
print("Data Loaded Successfully.")
return d
class teamClass:
name = ""
phone = 0
jersey = 0
def __init__(self, name, phone, jersey):
self.name = name
self.phone = phone
self.jersey = jersey
# youre not using getters/setters consistently so I removed them
# def setName(self, name):
# self.name = name
# your getters were wrong, fix like this:
# def getName(self): # fix, getter needs no name
# return self.name # fix missing self.
def displayData(player): # renamed - not a team
print("\n")
print("Welcome to the Team Manager")
print("---------------------------")
print("Name: ", player.name)
print("Phone #: ", player.phone)
print("Jersey #: ", player.jersey)
print("\n")
def displayMenu():
print("--------Main Menu--------")
print("\n1. Display Team")
print("2. Add Member")
print("3. Remove Member")
print("4. Edit Member")
print("9. Exit Program")
print("\n")
try: # catch errors
return int(input("Selection: "))
except:
return -1 # will lead to no action and reprint
def printTeam(team):
if len(team) == 0:
print("No team members in memory.")
else:
for x in team.keys():
displayData(team[x]) # fix -print each player of this team
def addTeam(team):
newName = input("Enter the new player name: ")
newPhone = input("Enter the phone #: ")
newJersey = input("Enter the jersey #: ")
team[newName] = teamClass(newName, newPhone, newJersey)
return team
def removeTeam(team):
removeName = input("Enter the member to be removed: ")
if removeName in team:
team.pop(removeName) # remove with pop
else:
print("Team member not found.")
return team
def editTeam(team):
oldName = input("Enter the player you want to edit: ")
if oldName in team:
newName = input("Enter the new name: ")
newPhone = input("Enter the new phone number: ")
newJersey = input("Enter the jersey #: ")
team.pop(oldName) # remove old
team[newName] = teamClass(newName, newPhone, newJersey) # add new
else:
print("Team member not found")
return team
print("Welcome to the Team Manager")
team = loadData()
menuSelection = displayMenu() # = missing
while menuSelection != 9:
if menuSelection == 1:
printTeam(team)
elif menuSelection == 2:
team = addTeam(team)
elif menuSelection == 3:
team = removeTeam(team)
elif menuSelection == 4:
team = editTeam(team)
menuSelection = displayMenu()
saveData(team) # data missing
print("Exiting Program...")
This code has an error on the load function but I don't understand what is causing it. I'm importing the class definition from another file, the program does save the file as a text in my computer and the program tells me that it loads the data but when I try to call for a display of the data that's when I'm getting the error.
from roster2 import rosterClass
outFile = open("c:\roster.txt", "wt")
outFile.write("The text and data will be save as a file on c:\roster.txt")
outFile.close()
inFile = open("c:\roster.txt", "rt")
contents = inFile.read()
print (contents)
def saveData(roster):
filename = input("Enter file name:")
print("Saving file.....")
outFile = open(filename, "wt")
for x in roster.keys():
name = roster[x].getname()
phone = roster[x].getphone()
jersey = str(roster[x].getjersey())
outFile.write(name+","+phone+","+jersey+"\n")
print("File saved.")
outFile.close()
def loadData():
roster = {}
filename = input("Enter file to load: ")
inFile = open(filename, "rt")
print("Loading data......")
while True:
inLine = inFile.readline()
if not inLine:
break
inLine = inLine[:-1]
name, phone, jersey = inLine.split(",")
roster[name] = name, phone, jersey
print("Roster data loaded succesfully")
inFile.close()
return roster
def displayMenu():
print ("======Main Menu======")
print ("1. Display roster ")
print ("2. Add player:")
print ("3. Remove player: ")
print ("4. Edit player information.")
print ("5. Save data.")
print ("6. Load data.")
print ("9. Exit Program")
print ("")
return int(input("Select a number to continue: "))
def printRoster(roster):
if len(roster) == 0:
print ("no current players in roster")
else:
for x in roster.keys():
roster [x].displayData()
def addRoster (roster):
newName = input("Enter new player's name:")
newPhone = input("Player's phone number: ")
newJersey = int(input("Player's jersey number:"))
roster[newName] = rosterClass (newName, newPhone, newJersey )
return roster
def removeRoster(roster):
removeName = input("enter player's name to be removed:")
if removeName in roster:
del roster[removeName]
else:
print("player not found in list.")
return roster
def editroster(roster):
oldName = input("Enter the name of the player you want to edit:")
if oldName in roster:
newName = input ("Enter the new player's name:")
newPhone = input("Player's new phone number:")
newJersey = int(input("Player's new jersey number:"))
roster[oldName] = rosterClass (newName, newPhone, newJersey)
else:
print ("no player exist in roster")
return roster
print ("Welcome to the Roster Manager")
roster = {}
menuSelection = displayMenu()
while menuSelection !=9:
if menuSelection == 1:
printRoster(roster)
elif menuSelection == 2:
roster = addRoster(roster)
elif menuSelection == 3:
roster = removeRoster(roster)
elif menuSelection == 4:
roster = editRoster(roster)
elif menuSelection == 5:
roster = saveData(roster)
elif menuSelection == 6:
roster = loadData()
menuSelection = displayMenu()
print ("Goodbye......")
I have taken the liberty of attempting to correct the indentation of your code so that it compiles. Of course it won't run on my computer because I don't have the code that your code imports. However, the diagnostic message you supplied complains that, in ' line 62, in printRoster roster [x].displayData() AttributeError: 'tuple' object has no attribute 'displayData''.
The only place in your code that displayData appears is in this line of code:
roster [x].displayData()
It matches the error message! The message says that roster[x] is a tuple which raises my curiosity. How is roster[x] defined?
Two different ways:
roster[name] = name, phone, jersey
roster[newName] = rosterClass (newName, newPhone, newJersey )
I've been programming for nearly fifty years, I can guess which way is correct. What do you think?
I have several lists that each contain objects. All objects have the values "name" and "amount". What I want to do is create a method to update "amount" by first finding the item in the list by user input (enter name to find name) then adding or subtracting a user input value (enter value to add/enter value to subtract).
How would I go about doing this?
This is what I have so far (It's incomplete but it's all I could get done):
Containers = []
Lids = []
Wicks = []
Labels = []
Misc = []
class item(object):
#Constructor
def __init__(self, name, amount):
self.name = name
self.amount = amount
#Accessors
def getName(self):
return self.name
def getAmount(self):
return self.amount
#Mutators
def __str__(self):
return "[Name: " + self.name + \
", Amount: " + self.amount + \
"]"
def addAmount():
found = False
name = input("Enter the name of a container you wish to change: ")
addNewAmount = input("Enter the amount you wish to add: ")
for item in Containers:
if name in item.getName():
found = True
position = Containers.index(name)
print(Containers[position])
if not found:
print("No names match that input.")
def subtractAmount():
update = input("Enter a new amount to subtract: ")
self.amount = amount - update
def addContainer():
name = input("Enter a name for the new container: ")
amount = input("Enter an amount for the new container: ")
return item(name, amount)
def addLid():
name = input("Enter a name for the new lid: ")
amount = input("Enter an amount for the new lid: ")
return item(name, amount)
def addWick():
name = input("Enter a name for the new wick: ")
amount = input("Enter an amount for the new wick: ")
return item(name, amount)
def addLabel():
name = input("Enter a name for the new label: ")
amount = input("Enter an amount for the new label: ")
return item(name, amount)
def addMisc():
name = input("Enter a name for the new misc item: ")
amount = input("Enter an amount for the new misc item: ")
return item(name, amount)
def main():
running = True
while running:
print("Enter a number to start.")
print("1) Add new container 2) Add new lid")
print("3) Add new wick 4) Add new label")
print("5) Add new misc Item 6) Print Inventory")
print("7) Add Amount from item 8) Subtract Amount from item")
print("10) quit")
print("11) print list")
choice = input("> ")
if choice == "1":
Containers.append(addContainer())
elif choice == "2":
Lids.append(addLid())
elif choice == "3":
Wicks.append(addWick())
elif choice == "4":
Labels.append(addLabel())
elif choice == "5":
Misc.append(addMisc())
elif choice == "6":
print("<==========Containers==========>")
for i in Containers:
print(i)
print("<=============Lids=============>")
for i in Lids:
print(i)
print("<=============Wicks============>")
for i in Wicks:
print(i)
print("<============Labels============>")
for i in Labels:
print(i)
print("<==========Misc Items==========>")
for i in Misc:
print(i)
elif choice == "7":
return addAmount()
elif choice == "8":
return subtractAmount()
elif choice == "10":
quit()
elif choice == "11":
print('[%s]' % ', '.join(map(str, Containers)))
else:
print("Invalid entry, please try again.")
if __name__ == "__main__":
main()
There's a couple of issues here. The first is whether you want containers, lids, wicks, etc to all be the same type of object ("item") or whether it would make more sense to have subclasses. Assuming you want them all to be the same ("item") you could adjust your methods according to the code below (I've left out a lot of options for simplicity).
A couple things to note:
"amount" needs to be numerical (int) in order to add or subtract from it correctly
the creation of an item is a function outside the class, and allocates the item to the appropriate list (Containers, Lids)
the "add_amount" function looks through all lists of all items to find a possible match and adjusts the amount accordingly. If a lid and container have the same name, it will modify the first match.
Containers = []
Lids = []
Items = [Containers, Lids]
class item(object):
#Constructor
def __init__(self, name, amount):
self.name = name
self.amount = amount
#Accessors
def getName(self):
return self.name
def getAmount(self):
return self.amount
def __str__(self):
return "[Name: " + self.name + \
", Amount: " + str(self.amount) + \
"]"
def addItem():
global new_item
name = input("Enter a name for the new item: ")
amount = int(input("Enter an amount for the new item: "))
new_item = item(name, amount)
return new_item
def add_amount():
found = False
name = input("Enter the name of the item you wish to change: ")
add_amount = int(input("Enter the amount you wish to add: "))
for itemList in Items:
for item in itemList:
if name == item.getName():
found = True
position = itemList.index(item)
item.amount += add_amount
print(itemList[position])
if not found:
print("No names in match that input.")
def main():
running = True
while running:
print("Enter a number to start.")
print("1) Make a container 2) Make a lid")
print("3) add amount 4) quit")
choice = input("> ")
if choice == "1":
addItem()
print new_item.amount
Containers.append(new_item)
elif choice == "2":
addItem()
print new_item.amount
Lids.append(new_item)
elif choice == "3":
add_amount()
elif choice == "4":
quit()
else:
print("Invalid entry, please try again.")
if __name__ == "__main__":
main()
This might be kind of messy, but should do the work:
def subtractAmount():
containers = [Containers, Lids, Wicks, Labels, Misc]
names = ['Containers', 'Lids', 'Wicks', 'Labels', 'Misc']
print('Select the number of list you want to search for item')
print('\n'.join('{}) {}'.format(str(idx), lst_name) for (idx, lst_name) in enumerate(names, 1)))
selected = input(': ')) - 1
item_name = input('Enter the item name you are looking for: ')
item = None
for value in containers[selected]:
if value.getName().lower() == item_name.lower():
item = value
break
else:
print('No item was found with that name!')
new_amount = input('Enter the new amount for item: ')
item.amount = new_amount
I have this long python code and I'm having trouble finishing or fixing it and I need help.
First I have these codes -
This will just display the menus and i have created several def functions. One is for creating data and saving to the txt file, and the other is to use a hash function to split the name. Contact info as data is created in the txt file. Finally, in a while loop I have to somehow call up the menu codes and this is where I get stuck, or I may need to fix the whole thing. Also when I put a phone number in like 555-5555, it makes an error. How would I input a number like this value?
def menu():
print("Contact List Menu:\n")
print("1. Add a Contact")
print("2. Display Contacts")
print("3. Exit\n")
menu()
choice = int(input("What would you like to do?: "))
def data():
foo = open("foo.txt", "a+")
name = input("enter name: ")
number = int(input("enter the number: "))
foo.write(name + " " + str(number))
foo.close()
def contact():
data = open("foo.txt")
file = {}
for person in data:
(Id, number) = person.split()
file[number] = Id
data.close()
while choice !=3:
if choice == 1:
print(data())
if choice ==2:
print(data())
menu()
choice = int(input("What would you like to do?: "))
It seems that the program never stops and I have to use option 3 from the menu to exit the program.
Phone number like 555-5555 is not valid integer number so keep it as a text.
Inside menu() you call menu() which call menu(), etc. It is recursion. When you choose 3 you leave last menu() and return to previous menu().
EDIT:
btw: you have to add "\n" in write
def menu():
print("Contact List Menu:\n")
print("1. Add a Contact")
print("2. Display Contacts")
print("3. Exit\n")
def data():
foo = open("foo.txt", "a+")
name = input("enter name: ")
number = int(input("enter the number: "))
foo.write(name + " " + str(number) + "\n") # new line
foo.close()
def contact():
data = open("foo.txt")
for person in data:
name, number = person.split()
print(name, number)
data.close()
#----------------
menu()
choice = int(input("What would you like to do?: "))
while choice !=3:
if choice == 1:
data()
if choice == 2:
contact()
menu()
choice = int(input("What would you like to do?: "))