The phonebook cannot store more than one person with the same last name. For example if i have an entry with the last name x and i try to create a new entry with a last name x,it will replace the previous x with the info of the last x input. This is the code.blablablablablabla(i cant say more but it doesnt let me post)
# Used to store the entries in the telephone book
entries = []
new_entries = {}
# Create flag to decide when the program ix exited
exit_program = False
while exit_program == False:
print( "Welcome to the EG-244 Telephone Book" )
print( "------------------------------------\n" )
print( "Please select from one of the following options:" )
print( "\t1. Add a new entry" )
print( "\t2. List entries" )
print( "\t3. Search for an entry" )
print( "\t4. Delete an entry" )
print( "\t5. Add a personal note" )
print( "\t6. Remove a personal note" )
print( "\t7. Quit" )
menu_input = input()
menu_num = int(menu_input)
if menu_num == 1:
print("\nCan i have your Last name, First name,Age and phone number please")
last_name=input("Last name:")
name=input("Name:")
age=input("Age:")
phone=input("Phone number:")
new_entries[last_name] = {'Last Name':last_name, 'First Name':name, 'Age':age, 'Telephone':phone,'Personal Notes':{'1.':'', '2.':''}}
entries.append(new_entries.copy())
entries=sorted(new_entries.keys(), key=lambda x:x.lower())
continue
elif menu_num == 2:
if len(new_entries) == 0:
print("No entries have been submitted yet")
continue
else:
for i in entries:
values=new_entries[i]
print("Last Name:" + i)
print("First Name:"+values['First Name'])
print("Age:"+values['Age'])
print("Phone Number:"+values['Telephone'])
print('Personal Note 1.:'+values['Personal Notes']['1.'])
print('Personal Note 2.:'+values['Personal Notes']['2.'])
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print("Currently there are" + str(len(entries)) + "entries")
continue
elif menu_num == 3:
print("\nInsert the last name:")
last_name=input()
if last_name in new_entries:
print (last_name, new_entries[last_name])
continue
else:
print("\nThe person is not in the phone book")
continue
elif menu_num == 4:
print("\nInsert the Last name of the entry to be deleted:")
last_name=input()
if last_name in new_entries:
del new_entries[last_name]
print("Entry has been deleted")
continue
else:
print("The entry does not exist")
continue
elif menu_num ==5:
print("Can I have your last and first name please:")
last_name=input("Last name:")
name=input("First name:")
note=input("Personal Note:")
note_1=input("Another personal Note:")
name in [x for v in new_entries.values() for x in v]
if last_name in new_entries:
new_entries[last_name]['Personal Notes']['1.']=note
new_entries[last_name]['Personal Notes']['2.']=note_1
print (last_name, new_entries[last_name])
continue
else:
print("This entry does not exist")
continue
if menu_num == 6:
print("Can I have your last and first name please:")
last_name=input("Last name:")
name=input("First name:")
delete=input("Delete note 1 or 2?")
delete=int(delete)
name in [x for v in new_entries.values() for x in v]
if last_name in new_entries:
for notes in new_entries.values():
if delete == 1:
new_entries[last_name]['Personal Notes']['1.']=''
print("1st Note deleted")
elif delete == 2:
new_entries[last_name]['Personal Notes']['2.']=''
print("2nd Note deleted")
continue
else:
print("This entry does not exist")
elif menu_num == 7:
exit_program = True
else:
print( "Error: You entered an invalid choice. Please try again." )
print( "Thank you for using the EG-244 Telephone Book" )
I think that
new_entries[last_name] = {'Last Name':last_name, 'First Name':name, 'Age':age, 'Telephone':phone,'Personal Notes':{'1.':'', '2.':''}}
should be a list containing a dictionary rather than just a dictionary.
new_entries[last_name] = [{'Last Name':last_name, 'First Name':name, 'Age':age, 'Telephone':phone,'Personal Notes':{'1.':'', '2.':''}}]
That way you could append another item to that list stored under the same last_name key.
You'll then have to update the rest of your code to handle this new data structure.
Related
i'm doing a small script that received name from user and then search for name, if found prints his/her name otherwise print "not found".
def std_record():
print("1. Enter data.")
print("2. Search student")
user_input = int(input("Enter Choice: "))
if user_input == 1:
name = input("Whats your name: ")
elif user_input == 2:
search = input("Enter keyword: ")
if search in name:
print("data found: " + name +".")
else:
print("not found")
while True:
std_record()
UnboundLocalError: local variable 'name' referenced before assignment
you need to initialize strings before using them, either as an empty string or none
so name = ""
or name = None
Try initializing the name variable:
name = None
def std_record():
print("1. Enter data.")
print("2. Search student")
user_input = int(input("Enter Choice: "))
if user_input == 1:
name = input("Whats your name: ")
elif user_input == 2:
search = input("Enter keyword: ")
if name:
print("data found: " + name +".")
else:
print("not found")
while True:
std_record()
I am trying to create a list using a loop, but I want the group to have the same index. Using append, it merges them together. What am I doing wrong?
L=[]
l=[]
def information():
i=0
while i <= 3:
if i==0:
first_name = str(input('First Name : '))
l.append(first_name)
i += 1
elif i==1:
last_name = str(input('Second Name : '))
l.append(last_name)
i += 2
elif i > 2:
wish = str(input('If you wish to continue Press Y/y or Press N/n:'))
if wish == 'y' or wish == 'Y':
L.append(l)
start()
elif wish != 'y' or wish != 'Y':
break
def start():
information()
start()
print('l', l)
print('L ', L)
My desired output is:
[['sachin', 'tendulkar'],['sachin', 'tendulkar'],['sachin', 'tendulkar']]
and I am getting this instead:
['sachin', 'tendulkar','sachin', 'tendulkar']
A little different than what you had going but this might work
Names = []
def information():
wish = str(input("Do you wish to add a name? Press Y/y for yes or Press N/n for no: "))
while ((wish == 'y') or (wish == 'Y')):
fname = str(input('First Name: '))
lname = str(input('Last Name: '))
Names.append([fname, lname])
wish = str(input("Do you wish to add a name? Press Y/y for yes or Press N/n for no: "))
information()
print (Names)
I have been trying to resolve my script with no results. I can't get
the load data to display. It is saving in members.txt and can read
it manually if opened. If someone can give any other advice on the
script as a whole it would be greatly appreciated.
I have reasearced greatly changed script around still have no luck.
import os if 'file' in vars():
wk_dir = os.path.dirname(os.path.realpath('file')) else:
print('We are running the script interactively')
class playerCLass(object):
name = ""
phone = ""
number = 0
def __init__(self, name, phone, number):
self.name = name
self.phone = phone
self.number = number
def setname(self, name):
self.name = name
def setphone(self, phone):
self.phone = phone
def setnumber(self, number):
self.number = number
def getname(self):
return self.name
def getphone(self):
return self.phone
def getnumber(self):
return self.number
def display_data(self):
print("")
print("Member information: ")
print("Name:", self.name)
print("Phone number:", self.phone)
print("Jersey number:", self.number)
def displayMenu():
print("===========Menu Selections===========")
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.")
print("")
return int(input("<<Selection>> "))
def printPlayer(players):
print("Current members: ")
if len(players) == 0:
print("No current members in memory.")
else:
x = 1
while x < len(players):
print(x)
x = x + 1
def addPlayer(players):
newName = input("Type in member's name to be added to the roster:")
newPhone = input("Type in the member's phone number:")
newNumber = int(input("Type in the member's jersey number:"))
players[newName] = playerCLass(newName, newPhone, newNumber)
return players
def removePlayer(players):
name = input("Enter member's name to be removed:")
if name in players:
del players[name]
else:
print("member's name not found in list: ")
return players
def editPlayer(players):
oldName = input("Enter the name you want to edit: ")
if oldName in players:
newName = input("Enter a new name: ")
newPhone = input("Enter new phone number: ")
newNumber = int(input("Enter new jersey number: "))
players[oldName] = playerCLass(newName, newPhone, newNumber)
else:
print("No such name in memory: ")
return players
def saveData():
filename = input("Filename to save: ")
print("Saving data...")
outFile = open(filename, "wt")
for x in players.keys():
name = players[int(x)].getname()
phone = players[int(x)].getphone()
number = str(players[x].getnumber())
outFile.write(name + "," + phone + "," + number + "\n")
print("Data saved.")
outFile.close()
def loadData():
players = {}
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, number = inLine.split(",")
players[name] = (name, phone, number)
print("Data Loaded Successfully.")
inFile.close()
return players
print("Welcome to the Team Manager")
players = {}
menuSelection = displayMenu()
print()
while menuSelection != 9:
if menuSelection == 1:
printPlayer(players)
elif menuSelection == 2:
players = addPlayer(players)
elif menuSelection == 3:
players = removePlayer(players)
elif menuSelection == 4:
players = editPlayer(players)
elif menuSelection == 5:
saveData()
elif menuSelection == 6:
loadData()
menuSelection = displayMenu()
print("Exiting Program...")
If your issue is specifically not getting printPlayer to work you can do
def printPlayer(players):
print("Current members: ")
if len(players) == 0:
print("No current members in memory.")
#Iterate through dictionary of player name and player object and call
#display data on each of them
else:
for name, player in players.items():
print(player.display_data())
If you then run the code and input according to the statements you wrote, you should get something like this.
Welcome to the Team Manager
===========Menu Selections===========
1. Display Team Roster.
2. Add Member.
3. Remove Member.
4. Edit Member.
5. Save Data.
6. Load Data.
9. Exit Program.
<<Selection>> 1
Current members:
No current members in memory.
===========Menu Selections===========
1. Display Team Roster.
2. Add Member.
3. Remove Member.
4. Edit Member.
5. Save Data.
6. Load Data.
9. Exit Program.
<<Selection>> 2
Type in member's name to be added to the roster:Joe
Type in the member's phone number:123
Type in the member's jersey number:456
===========Menu Selections===========
1. Display Team Roster.
2. Add Member.
3. Remove Member.
4. Edit Member.
5. Save Data.
6. Load Data.
9. Exit Program.
<<Selection>> 1
Current members:
Member information:
Name: Joe
Phone number: 123
Jersey number: 456
None
===========Menu Selections===========
1. Display Team Roster.
2. Add Member.
3. Remove Member.
4. Edit Member.
5. Save Data.
6. Load Data.
9. Exit Program.
<<Selection>>
Function is not being called inside another function:
ch = False
while not ch:
print("""
1. Make a User
2. Login in and Play
3. Quit
""")
a = input("What would you like to do: ")
if a == '1':
un_maker()
elif a == '2':
player1Login()
elif a == '3':
input('\nEnter to exit...\n')
quit()
Where when a is 2, it should move on to player1Login(), it does but it does not go to the next function inside the player1Login().
The code for player1Login() and the function it's supposed to run:
def player1Login():
""" Login for player 1 """
user1 = input("Please enter your usernames[Caps sensitive]: ") # Asking the
user to input there username
pass1 = input("Please also enter your password[Caps sensitive]: ") # Asking the user to input there password
verfi1(user1, pass1)
def verfi1(user1, pass1):
""" Verfications of the user """
with open("data.csv", "r") as f:
reader = csv.reader(f) # makes 'reader' the csv reader of file 'f'
for row in reader: # Looking at rows/records inside the file
if user1 in row: # Looks for username inside the row
if pass1 in row[1]:
print("Player 1 Confirmed")
player2Login()
elif pass1 != row[1] or reader == '':
print("""You have entered the wrong Username/Password for Player 1
This could be due to:
1. Inputed the wrong username/password
2. Inputed the wrong case in username/password
3. Inputed username/password that does not exit
""")
break
else:
#print("Reader")
next(reader)
Basically, the code should output when a is 2, player1Login() then move onto verfi1() function however it does not, it just goes back to the menu.
Answer Found:
def menu():
ch = False
optin = 0
while not ch :
print("""
1. Make a User
2. Login in and Play
3. Quit
""")
optin = input("What would you like to do: ")
if optin == '1':
un_maker()
elif optin == '2':
player1Login()
elif optin == '3':
input('\nEnter to exit...\n')
quit()
def player1Login():
""" Login for player 1 """
user1 = input("Please enter your usernames[Caps sensitive]: ")
pass1 = input("Please also enter your password[Caps sensitive]: ")
boop(user1, pass1)
def boop(user1, pass1):
with open('data.csv', 'r') as f:
reader = csv.reader(f)
for row in reader:
if pass1 in row[1] and user1 in row[0]:
print("Username and Password found, Player 1 Confirmed")
player2Login(user1)
elif pass1 not in row[1] and user1 not in row[0] and row[0] == '' :
print("Player Not found / Password incorrect")
menu()
You skip lines with next and therefore jump over each other user in you data.csv file. This can lead to that if user1 in row is never true even though user1 is in your file but happens to be on a skipped line.
Your code:
for row in reader: # Looking at rows/records inside the file
if user1 in row: # Looks for username inside the row
if pass1 in row[1]:
print("Player 1 Confirmed")
player2Login()
elif pass1 != row[1] or reader == '':
print("""You have entered the wrong Username/Password for Player 1
This could be due to:
1. Inputed the wrong username/password
2. Inputed the wrong case in username/password
3. Inputed username/password that does not exit
""")
break
else:
next(reader) # this skips the next
Remove the elseclause because for row in reader already goes over all lines.
menu_item = MainMenu = ["Display Team Roster", "Add Member", "Remove Member", "Edit Member", "Exit Program"]
while menu_item != 9:
print("Welcome to the Team Manager!")
print("1. Display Team Roster.")
print("2. Add Member.")
print("3. Remove Member.")
print("4. Edit Member")
print("9. Exit Program.")
menu_item = int(input("Selection:"))
elifmenu_item == 1
print(current)
current = 0
while len(MainMenu) > 0:
current < len(MainMenu)
print(current, ".", MainMenu[current])
current = current + 1
elifmenu_item == 2
name = input("Enter new member's name:")
MainMenu.append(name)
elifmenu_item == 3
del_name = input("Enter member name to be removed:")
del_name in MainMenu
item_number = MainMenu.index(del_name)
del MainMenu[1]
elifmenu_item == 4
old_name = input("Enter the name of the member you want to edit:")
old_name in MainMenu
item_number = MainMenu.index(old_name)
new_name = input("Enter the new name of the member:")
MainMenu[1] = new_name
else:
print("Goodbye")
Write a modularized program that will utilize a main menu to control the program’s functions and a list to store the members of your team. The following functions that your program needs to include:
•Print the current member list.
•Add a new member.
•Remove a member.
•Modify an existing member.
•Exit the program
elif is not a function, it is language element just like while, if.
It has to be used together with if (just like else), example:
if a == '1':
print('1')
elif a == '2':
print('2')
else:
print('other')
In your case you have elifmenu_item == 1 which is wrong, you should have a space after elif and you should start with an if, only subsequent cases use elif.