I'm trying to make a simple phone book where if you put type in
1: you add a contact to a dictionary, if
2 you lookup the dictionary based on the inputted name (key) if
3 you lookup the dictionary based on the inputted number (value)
When I run a key lookup based on value (input 3) it returns the else function 'this is invalid' regardless of whether or not it is true.
Can someone decipher this?
#Input contact name
if button == 1:
name = input('Please enter the contact name:')
if name in contacts:
print("The name you entered already exists in the address book --> %s:%s"\
%(name,contacts[name]))
flag = input("Whether to modify user information (YES/NO):")
if flag== 'YES':
tel = input('Please enter the users contact phone number:')
contacts.update({name:tel}) #Update dictionary
print("Contacts have been updated!")
else:
continue
else:
contacts[name] = input('Please enter the contact phone number:')
print("Contact has been saved!")
#Search by contact name
if button == 2:
name = input('Please enter the contact name:')
if name in contacts:
print("%s : %s "%(name,contacts[name]))
else:
print('The name you entered is no longer in the address book! ')
#Search by contact number
if button == 3:
numba = input('Please enter the contact number:')
lookup = []
for key,value in contacts.items():
if(value == numba):
lookup.append(key)
print('Name(s) matching number is',lookup)
else:
print('This is invalid')
Try this:
if button == 3:
numba = input('Please enter the contact number:')
lookup = []
for key,value in contacts.items():
if(value == numba):
lookup.append(key)
if lookup: # True if len(lookup) != 0
print('Name(s) matching number is', lookup)
else:
print('This is invalid')
Probably a bit of a stretch, but I made it work like this:
numba = input('Please enter the contact number: ')
lookup = []
for key,value in contacts.items():
if(numba == key):
lookup.append(value)
print('Name(s) matching number is', lookup)
if(int(numba) > len(contacts.items())):
print('This is invalid')
Related
import re
contact = {}
def display_contact():
for name, number in sorted((k,v) for k, v in contact.items()):
print(f'Name: {name}, Number: {number}')
#def display_contact():
# print("Name\t\tContact Number")
# for key in contact:
# print("{}\t\t{}".format(key,contact.get(key)))
while True:
choice = int(input(" 1. Add new contact \n 2. Search contact \n 3. Display contact\n 4. Edit contact \n 5. Delete contact \n 6. Save your contact as a file \n 7. Update Saved List \n 8. Exit \n Your choice: "))
if choice == 1:
while True:
name = input("Enter the contact name ")
if re.fullmatch(r'[a-zA-Z]+', name):
break
while True:
try:
phone = int(input("Enter number "))
except ValueError:
print("Sorry you can only enter a phone number")
continue
else:
break
contact[name] = phone
elif choice == 2:
search_name = input("Enter contact name ")
if search_name in contact:
print(search_name, "'s contact number is ", contact[search_name])
else:
print("Name is not found in contact book")
elif choice == 3:
if not contact:
print("Empty Phonebook")
else:
display_contact()
elif choice == 4:
edit_contact = input("Enter the contact to be edited ")
if edit_contact in contact:
phone = input("Enter number")
contact[edit_contact]=phone
print("Contact Updated")
display_contact()
else:
print("Name is not found in contact book")
elif choice == 5:
del_contact = input("Enter the contact to be deleted ")
if del_contact in contact:
confirm = input("Do you want to delete this contact Yes or No? ")
if confirm == 'Yes' or confirm == 'yes':
contact.pop(del_contact)
display_contact
else:
print("Name is not found in phone book")
elif choice == 6:
confirm = input("Do you want to save your contact-book Yes or No?")
if confirm == 'Yes' or confirm == 'yes':
with open('contact_list.txt','w') as file:
file.write(str(contact))
print("Your contact-book is saved!")
else:
print("Your contact book was not saved.")
# else:
elif choice == 7:
confirm = input("Do you want to update your saved contact-book Yes or No?")
if confirm == 'Yes' or confirm == 'yes':
f = open("Saved_Contact_List.txt" , "a")
f.write("Name = " + str(name))
f.write(" Number = " + str(phone))
f.close()
#with open('contact_list.txt','a') as file:
# file.write(str(contact))
print("Your contact-book has been updated!")
else:
print("Your contact book was not updated.")
else:
break
I have tried but only get to save the last input and not all of the contact list. Any ideas on how to save them all. I have been trying different code as I have comment some out to try a different way but it only print the last input. I would like it to save a output file with the first save to save all the contact then if they add or update a contact to save it as a updated saved file like choice 7. But I only get it to save the last input. I still learning how python works and this is over my head.
You're looking for serialization, which is (usually) best left to libraries. The json library easily handles reading and writing dictionaries to a file.
To write a dictionary, take a look at json.dump():
with open("Saved_Contact_List.txt", "w") as f:
json.dump(contact, f)
I was trying to check if the username entered is equal to the second index of item in the list, and I tried to use !=, but it still keeps letting the same username to be registered. What's the problem with the code ?
Registering username :
user_list = [['usr1','Daniel'],['usr2','Raymond'],['usr3','Emanuel']]
name = input("Please enter your name : ")
while True:
if name == '':
name = input("Please enter your name : ")
else:
for user in user_list:
if name != user[1]:
break # break out for loop
else:
print("This username has been registered")
name = input("Please try another username : ")
continue # continue the while loop
break # break out while loop
print("Username registered as",name)
Editted:
The results of != and == seems to be different, the == works.
Login username :
user_list = [['std1','Daniel'],['std2','Raymond'],['std3','Emanuel']]
name = input("Please enter your name : ")
while True:
if name == '':
name = input("Please enter your name : ")
else:
for user in user_list:
if name == user[1]:
break # break out for loop
else:
print("Unregistered username")
name = input("Please try another username : ")
continue # continue the while loop
break # break out while loop
print("Logged in as",name)
You're very close!
What you're trying to do: break out of the loop if there are any names in user_list that match the new name.
What it's currently doing: breaking out of the loop if there are any names in user_list that don't match the new name.
I.e., if you enter Daniel, since Daniel != Raymond, you will break early.
Instead, what you should do is break if the newly entered name is not present in a list of names:
user_list = [['usr1','Daniel'],['usr2','Raymond'],['usr3','Emanuel']]
name = input("Please enter your name : ")
while True:
if name == '':
name = input("Please enter your name : ")
else:
if name in [user[1] for user in user_list]: # existing names list
print("This username has been registered")
name = input("Please try another username : ")
else:
break
print("Username registered as",name)
This code below will sort a lot of things out. In your code, even if we fix the indentation mistake with the else which should be moved into the for loop, the code won't work if we type Raymond. So I have provided an example which checks if the entered usr is in all the names in your user_list.
user_list = [['usr1','Daniel'],['usr2','Raymond'],['usr3','Emanuel']]
name = input("Please enter your name : ")
while True:
if name == '':
name = input("Please enter your name : ")
else:
for user in user_list:
if name not in [lst[-1] for lst in user_list]:
break # break out for loop
else:
print("This username has been registered")
name = input("Please try another username : ")
continue # continue the while loop
break # break out while loop
print("Username registered as",name)
I create a few class about pet, the following code was part of my main() function, First, ask the user to select one thing they want to do. that is if use input '1' they will add some pet instance. At the same time, I want to append part of the pet instance's information to a list. Then if the user chooses to read this information. I want to print it in another if statement branch. that is when the user input '2'. the problem occurs when I input 2 after already generating some pet instance. the list called l_weight always be void. How could I fix it? I already try to use the global list but is not work
def main():
l_weight=[]
print("========menu=========")
print("1. to add a pet")
print("2. print current weight for all pet")
print("3. print all pets and owners")
print("4. to exist system")
a=int(input("you selection(just input the number before each function)"))
while(True):
if a==1:
a=int(input("please select what type of pet would be added: 1-- mammals 2--fish 3--amphibians"))
name = input('please enter the name of pet:')
dob = input('please enter the dob of pet:(year,month,day)')
bw = input('please enter the birth weight:')
name = input('please enter the owner name:')
address = input('please enter the onwer address:')
if a==1:
ls = input('please enter the litter size:')
hs = input('pet has claws(yes or no):')
op=mammals(name,dob,bw,name,address,ls,hs)
print(op)
l_weight.append(op.get_current_weight)
elif a==2:
sc = input('please enter the scale condition:')
sl = input('please enter the scale length:')
op =fish(name,dob,bw,name,address,sc,sl)
print(op)
l_weight.append(op.get_current_weight)
elif a==3:
iv = input('is venomous(yes or no):')
op =amphibians(name,dob,bw,name,address,iv)
print(op)
l_weight.append(op.get_current_weight)
else:
print(' input wrong vaule,please choose a number from 1,2 or 3')
return main()
elif a==2:
for i in l_weight:
print(i)
return main()
The reason l_weight() isn't appending is because in your code, you named the list l_weight and then in the rest of your code it's written as l_weigh
It should be:
def main():
l_weight=[]
print("========menu=========")
print("1. to add a pet")
print("2. print current weight for all pet")
print("3. print all pets and owners")
print("4. to exist system")
a=int(input("you selection(just input the number before each function)"))
while(True):
if a==1:
a=int(input("please select what type of pet would be added: 1-- mammals 2--fish 3--amphibians"))
name = input('please enter the name of pet:')
dob = input('please enter the dob of pet:(year,month,day)')
bw = input('please enter the birth weight:')
name = input('please enter the owner name:')
address = input('please enter the onwer address:')
if a==1:
ls = input('please enter the litter size:')
hs = input('pet has claws(yes or no):')
op=mammals(name,dob,bw,name,address,ls,hs)
print(op)
l_weight.append(op.get_current_weight)
elif a==2:
sc = input('please enter the scale condition:')
sl = input('please enter the scale length:')
op =fish(name,dob,bw,name,address,sc,sl)
print(op)
l_weight.append(op.get_current_weight)
elif a==3:
iv = input('is venomous(yes or no):')
op =amphibians(name,dob,bw,name,address,iv)
print(op)
l_weight.append(op.get_current_weight)
else:
print(' input wrong vaule,please choose a number from 1,2 or 3')
elif a==2:
for i in l_weight:
print(i)
currently I am doing my assignment. The requirement is to test the format of Student ID. I wonder why is my while loop is not working properly..
My validation check is as below:
def isValidStudentIDFormat(stid):
# studentID must have a length of 9
if(len(stid) != 9):
# return the invalid reason
return "Length of Student ID is not 9"
# studentID must starts with a letter S
if(stid[0] != 'S'):
# return the invalid reason
return "First letter is not S"
# studentID must contains 7 numbers between the two letters
for i in range(1,8):
# anything smaller than 0 or bigger than 9 would not be valid.
# so does a character, will also be invalid
if((stid[i] < '0') or (stid[i] > '9')):
# return the invalid reason
return "Not a number between letters"
if((stid[8] < 'A') or (stid[8] > 'Z')):
# return the invalid reason
return "Last letter not a characer"
# return True if the format is right
return True
My function to insert a student record is below:
def insert_student_record():
#printing the message to ask user to insert a new student into the memory
print("Insert a new student \n")
fn = input("Enter first name: ")
#check if user entered space
#strip() returns a copy of the string based on the string argument passed
while not fn.strip():
print("Empty input, please enter again")
fn = input("Enter first name: ")
ln = input("Enter last name: ")
while not ln.strip():
print("Empty input, please enter again")
ln = input("Enter last name: ")
stid = input("Enter student id: ")
while not stid.strip():
print("Empty input, please enter again")
stid = input("Enter student id: ")
result = isValidStudentIDFormat(stid)
while (result != True):
print("Invalid student id format. Please check and enter again.")
stid = input("Enter student id: ")
result == True
#append the student details to each list
#append first name
fName.append(fn)
#append last name
lName.append(ln)
#append student id
sid.append(stid)
#to check if the new student is in the lists
if stid in sid:
if fn in fName:
if ln in lName:
#then print message to tell user the student record is inserted
print("A new student record is inserted.")
However, I'm getting an infinite loop even if I key in the correct format for student ID. Anyone can help ?
You compare result == True when you should assign. Still, you don't check the new student id for validity, which could be done this way:
while (result != True):
print("Invalid student id format. Please check and enter again.")
stid = input("Enter student id: ")
result = isValidStudentIDFormat(stid)
?
def validateStudentIDFormat(stid):
if len(stid) != 9:
raise RuntimeError("Length of Student ID is not 9")
if stid[0] != 'S':
raise RuntimeError("First letter is not S")
for char in stid[1:-1]:
if char.isnumeric():
raise RuntimeError("Not a number between letters")
if not stid[-1].isalpha():
raise RuntimeError("Last letter not a characer")
....
while True:
stid = input("Enter student id: ")
try:
validateStudentIDFormat(stid)
except RuntimeError as ex:
print(ex)
print("Invalid student id format. Please check and enter again.")
else:
break
If I create a dictionary that I need to access in multiple functions what would be the best way to pass it?
What I currently am doing keeps reseting the dictionary to empty. If I print in the addDictionary() I get the result I want. However, when I go to look up a element using the key in lookUpEntry(), I can't find it. When I print I get an empty dictionary. I also have to eventually pickle and unpickle so if anyone has any feedback on that, that would also help.
import pickle
def dictionary():
addressBook = {}
return addressBook
def addPerson():
personLastName = input("Enter the last name of "
"the person you want to add: ").lower()
personFirstName = input("Please enter the first name of "
"the person you want to add: ")
localPart = input("Please enter the local part of the email address")
while not localPart.isalnum():
localPart = input("Please enter a valid input, a-z and numbers 0-9: ")
domain = input("Please enter the domain of the email addres: ")
while not domain.isalnum():
domain = input("Please enter a valid input, a-z and numbers 0-9: ")
topLevelDomain = input("Please enter the top level domain, examples: com, net, org: ")
while not topLevelDomain.isalnum() or len(topLevelDomain) > 3:
topLevelDomain = input("Please enter only letters, a-z and not more then 3 characters: ")
personEmail = localPart + "#" + domain + "." + topLevelDomain
personStreetAddress = input("Please enter house number and street of the person you want to add: ")
personCityState = input("Please enter the city, state abbreviation and zipcode of the person you want to add: ")
personPhone = input("Please enter the phone number of the person you want to add: ")
personPhoneStr = personPhone.strip("-")
while not personPhoneStr.isdigit() and not len(personPhoneStr) == 10:
personPhone = input("Error. That is not a valid phone number. Try again: ")
personPhoneStr = personPhone.strip("-")
return personLastName, personFirstName, personEmail, personStreetAddress, personCityState, personPhone
def addDictionary():
addressBook = dictionary()
personLastName, personFirstName, personEmail, personStreetAddress, personCityState, personPhone = addPerson()
addressBook[personLastName] = personFirstName, personEmail, personStreetAddress, personCityState, personPhone
print(personFirstName,personLastName, "has been added to the address book!")
print(addressBook)
return addressBook
def lookUpEntry():
addressBook = dictionary()
keyName = input("Enter the last name of the person you are trying to find.")
while not keyName in addressBook:
keyName = input("That name is not in the address book. Please try again.").lower()
x = input("Enter '1' if you want to look up a email. Enter '2' if you want to look "
"up a persons address. Enter '3' to look up a persons phone number: ")
if x == "1":
print("The email of", addressBook[keyName[0]], keyName, "is:", addressBook[keyName[1]])
elif x == "2":
print("The address of", addressBook[keyName[0]], keyName, "is:", addressBook[keyName[2]], addressBook[keyName[3]])
elif x == "3":
print("The phone number of", addressBook[keyName[0]], keyName, "is:", addressBook[keyName[4]])
else:
print("Sorry that item is not stored in this address book.")
def main():
addDictionary()
lookUpEntry()
main()
Currently you define dictionary as
def dictionary():
addressBook = {}
return addressBook
Here you create a new dictionary every time it is called. Try replacing this with
# a global dictionary
_addressBook = {}
def dictionary():
return _addressBook