I am creating a basic phonebook program that can perform operations (add new, update, delete, lookup and exit). I have the first option as add entry and the second as delete entry. Every time the user completes an action, the option to select an action again should come up. When the user selects for the second time, it brings back to the first item instead of the selection; For example; 1 is to add new contact, 2 is to delete new contact. User selects 1, adds new contact is asked to select another option, chooses 2 but the code for option 1 runs again to add new instead of delete.
print("Please select an option from the main menu :\n")
def print_menu():
print("1 : Add New Entry")
print("2 : Delete Entry")
print("3 : Update Entry")
print("4 : Lookup Number")
print("5 : QUIT")
print()
print_menu()
while 1 == 1:
try:
menuOption = int(input())
break
except:
print("Invalid! Please choose an option between 1 and 5.")
while menuOption not in(1,2,3,4,5):
print("Invalid! Please choose an option between 1 and 5.")
try:
menuOption = int(input())
break
except:
print("Invalid! Please choose an option between 1 and 5.")
###the above works perfect to set menu and restrict entry
phonebook = {}
#while menuOption != 5:
#menuOption = int(input("Enter your selection (1-5): "))
while 1 == 1 :
if menuOption == 1: #
print("\nNEW CONTACT")
while True:
name = input("Contact Name : ")
if name.replace(' ','').isalpha():
break
print('Please enter a valid name.')
while True:
try:
number = int(input("Contact Number : "))
if number:
break
except:
print("Please enter a valid number.")
if number in phonebook:
print("Contact already exists. Duplicates are not allowed.\n")
else:
phonebook[number] = name
print("Success! New contact has been added.\n")
print("PLEASE SELECT AN OPTION BETWEEN 1 AND 5 \n")
try:
option = int(input())
except:
print("Please enter a numeric value between 1 and 5 \n")
elif menuOption == 2: ##delete
print("\nDELETE CONTACT")
name = input("Contact Name : ")
if name in phonebook:
del phonebook[name]
print(name, "has been removed from your contacts.")
else:
print("Contact not found.")
print("PLEASE SELECT AN OPTION BETWEEN 1 AND 5 \n")
try:
option = int(input())
except:
print("Please enter a numeric value between 1 and 5 \n")
Welcome to the stack, rainyday! On looking at/running your code, the message to remind the user to enter between one and five came up a bit more than I expected, along with random other errors that you probably just haven't coded for yet. I would suggest that defining more functions (for the menu options) and structuring your code a bit more would make your code easier to read and follow.
Below (which is not complete or error-free btw), I re-structured your code so that when main() is called, the Phone Book menu options shows and the user can choose another option. Instead of using long "else-if"/elif s between the various functions, the various menu routines are neatly organised in one while statement in the main() function and the choices are organised into 5 different functions: add()/delete() etc. (I put dummy code into the update/lookup/exit fns). I hope you find this helpful. I did find that if I entered a string when a digit was expected as input that it threw an error message. I inserted comments to assist.
Hope this helps
phonebook= []
def main():
print("\n\tPhone Book") #title
# main menu
print("\n\tMain Menu")
print("\t1. Add a contact")
print("\t2. Delete a contact")
print("\t3. Update a contact")
print("\t4. Look up")
print("\t5. Quit")
menuOption = int(input("\nPlease select one of the five options "))
while menuOption not in(1,2,3,4,5) :
## insert try/except error handling needed here to handle NaN ##
print("\nPlease insert a numeric option between 1 and 5")
menuOption =int(input())
while menuOption <=5:
mOpt =menuOption
if menuOption == 1:
Add(mOpt)
elif menuOption == 2:
Delete(mOpt)
elif menuOption == 3:
Update(mOpt)
elif menuOption == 4:
LookUp(mOpt)
elif menuOption == 5:
ExitPhone(mOpt)
else:
print("Invalid input! Please insert a value between 1 and 5")
# add contact
def Add(mOpt):
##Option 1
add = ""
contact = True
print("\n\tADD CONTACT")
while contact == True:
if mOpt == 1:
print("\nNEW CONTACT")
while True:
name = input("Contact Name : ")
if name.replace(' ','').isalpha():
break
print('Please enter a valid name.')
while True:
try:
number = int(input("Contact Number : "))
if number:
break
except:
print("Please enter a valid number.")
if number in phonebook:
print("Contact already exists. Duplicates are not allowed.\n")
else:
#item = name + number this won't be found in the delete function
phonebook.append(name)
phonebook.append(number)
#print(phonebook)
print("Success! New contact has been added.\n")
add = input("Would you like to add another? Y (yes) or N (no)")
add = add.lower()
if add=="yes" or add=="y":
contact = True
else:
contact = False
main()
# delete
def Delete(mOpt):
redel = ""
delcontact = True
print("\n\tDELETE CONTACT")
while delcontact == True:
if mOpt == 2:
print("Enter Contact Name:")
name = input("Contact Name : ")
if name in phonebook:
## insert code here to find associated number
## and concatenate it if you have created an 'item'
phonebook.remove(name) #removes name, leaves the number
print(name, "has been removed from your contacts.")
#print(phonebook)
else:
print("Contact not found.")
redel = input("Would you like to delete another? Y (yes) or N (no)")
redel = redel.lower()
if redel =="yes" or redel =="y":
delcontact = False
else:
delcontact = True
main()
def Update(mOpt):
if mOpt == 3:
print("\nUpdate function")
main()
def LookUp(mOpt):
if mOpt == 4:
print("\nLookUp function")
main()
def ExitPhone(mOpt):
if mOpt == 5:
print ("Exit?")
main()
main()
Your code checks the menuOption's value, but inputs option. Just change
option = int(input())
into
menuOption = int(input())
Related
I successfully defined a parameter and passed it to a function but when I return to main menu that parameter's value is completely reset and I cannot use it anywhere. The value of the parameter stays only within the second function. Like, the parameter cannot communicate with the whole program as far as I understand.
def main_menu(subtotal):
while True:
print("1) Appetizers")
print("2) Option 2")
print("3) Option 3")
print("4) Option 4")
print("5) Option 5")
print(" ")
print("Current overall subtotal: $" + str(round(subtotal,2)))
while True:
try:
choice = int(input("What is your choice? "))
break
except ValueError:
print("Please enter whole numbers only.")
while choice > 5 or choice < 1:
print("Please choose an option from 1 to 5")
try:
choice = int(input("what is your choice? "))
except ValueError:
print("Please enter whole numbers only.")
if choice == 1:
appetizers(subtotal)
"""
elif choice == 2:
option_2(subtotal)
elif choice == 3:
option_3(subtotal)
elif choice == 4:
option_4(subtotal)
elif choice == 5:
end(subtotal)
return subtotal
"""
def appetizers(subtotal):
while True:
print("1) Option 1")
print("2) Option 2")
print("3) Option 3")
print("4) Return to Main Menu")
print(" ")
print("Current overall subtotal: $" + str(round(subtotal,2)))
product_amount = 1
while True:
try:
choice = int(input("What is your choice? "))
break
except ValueError:
print("Please enter whole numbers only.")
while choice > 4 or choice < 1:
print("Please choose an option from 1 to 4")
try:
choice = int(input("what is your choice? "))
except ValueError:
print("Please enter whole numbers only.")
if choice == 4:
return subtotal
else:
while True:
try:
product_amount = int(input("How many would you like? "))
break
except ValueError:
print("Please enter whole numbers only.")
while product_amount > 100000 or product_amount < 1:
print("Please choose an option from 1 to 100,000")
product_amount = int(input("How many would you like? "))
if choice == 1:
subtotal = subtotal + (product_amount * 4.99)
elif choice == 2:
subtotal = subtotal + (product_amount * 2.99)
elif choice == 3:
subtotal = subtotal + (product_amount * 8.99)
For this project's sake, I don't want to use global variables. I only want to use the subtotal variable as a parameter throughout the program and continuously alter its value throughout the program and make calculations with it. I want to do this by passing it through other functions.
Since you've written the operations into functions and you're passing in the current subtotal, you just need to be updating the subtotal by saving the return value from appetizers() in main_menu(), like here:
# ...
if choice == 1:
subtotal = appetizers(subtotal)
I am a beginner in Python so kindly do not use complex or advanced code.
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. Print \n 7. Exit \n Enter "))
#I have already tried
if choice == 1:
while True:
try:
name = str(input("Enter the contact name "))
if name != str:
except ValueError:
continue
else:
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:
sort_contact = input("Enter yes to print your contact")
if sort_contact in contact:
confirm = input("Do you want to print your contact Yes or No? ")
if confirm == 'Yes' or confirm == 'yes':
strs = [display_contact]
print(sorted(strs))
else:
print("Phone book is printed.")
else:
break
I tried but keep getting errors and I can't fiugre out how to make it only take string or letter as input and not numbers.
if choice == 1:
while True:
try:
name = str(input("Enter the contact name "))
if name != str:
except ValueError:
continue
else:
break
it is not working my code still accepts the ans in integer and string.
I am a beginner so I might have made a lot of mistakes. Your patience would be appreciated.
You can use a regex with re.fullmatch:
import re
while True:
name = input("Enter the contact name ")
if re.fullmatch(r'[a-zA-Z]+', name):
break
Or use the case-insensitive flag: re.fullmatch(r'[a-z]+', name, flags=re.I):
As you noted that you are a beginner, I'm adding this piece of code
as a "custom-made" validation, just so you can check how you would do something like this by your own .
Note: #mozway gave a MUCH BETTER solution, that is super clean, and I recommend it over this one.
def valid_input(input: str):
# Check if any char is a number
for char in input:
if char.isdigit():
print('Numbers are not allowed!')
return False
return True
while True:
name = input("Enter data:")
if valid_input(name):
break
I found this answer from another website:
extracted_letters = " ".join(re.findall("[a-zA-Z]+", numlettersstring))
First, import re to use the re function.
Then let's say that numlettersstring is the string you want only the letters from.
This piece of code will extract the letters from numlettersstring and output it in the extracted_letters variable.
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':
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 add to if else function, one to save the contact list and one to just update it with the new contact. But When I run it I still get the old contact that where already saved. Any ideas on how to fix it to only append the new contacts to the already saved txt file.
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':
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.")
I just changed the "w" in choice 7 to "a" to append the new contact but I still get all the old one in the new save. Any ideas.
I am trying to create a phone book and I have everything except I need to run the entire code over and over instead an individual if statement. I am not sure how to continue any advice?
I have used a while loop.
#Intro
print("Address book to store friends contact")
print("-" * 50)
print("-" * 50)
#Display of options
print("Select an option: ")
print("1-Add/Update contact")
print("2- Display all contacts")
print("3- Search")
print("4- Delete contact")
print("5- Quit")
#Selection
option = input("Select which one you would like to choose. Ex. Select an
option. Type here: ")
#Map
contacts = {}
#Main program
for i in range(0,1):
if option == "Add/Update contact":
person_added = input("Who would you like to be updated or added")
next_question = input("What is there contact information")
#The code below will add the person to the list or update them
contacts [person_added] = next_question
elif option == "Display all contacts":
print(contacts)
elif option == "Search":
search_question = input("Who are you looking for: ")
for search in contacts.items():
if search == search_question:
print("I found" + search)
else:
print("Contact not found")
elif option == "Delete contact":
person_deleted = input("Who would you like to be deleted ")
del(contacts[person_deleted])
else:
print("Thank You! Goodbye")
for an assignment, I made a menu and must have it work in a way to execute multiple functions. However, the problem is that when I use the menu and put in an answer that doesn't exist, I cannot get it to work correctly. So when I re-enter an option number for "Incorrect option, try again: ", I do not get the number re-evaluated to execute. Since my code is far from finished, right now I want to be able to choose "4" as an input and get "Incorrect option, try again" as an output and input "1" into this to get the output "Choose the level of difficulty".
def main_menu():
print(10*"=","GAME",10*"=",'\n')
print("1. Choose level of difficulty ")
print("2. Start Game")
print("3. Exit the Game",'\n')
print("Current Difficulty: /5")
print("Highest Score Reached:",'\n')
option=input("Enter an option: ")
return option
def user_input():
while True:
try:
if option==1:
difficulty()
break
elif option==2:
start()
break
elif option==3:
exit()
break
except:
option=input("Incorrect option, try again: ")
def difficulty():
d=int(input("Choose level of difficulty: "))
if 1<=d<=5:
start()
else:
int(input("Incorrect option, try again: "))
#difficulty()
return d
Here a is modified version of your code which I believe does what you are looking for.
def main_menu():
print(10 * "=", "GAME", 10 * "=", '\n')
print("Current Difficulty: /5")
print("Highest Score Reached:", '\n')
while True:
print("1. Choose level of difficulty")
print("2. Start Game")
print("3. Exit the Game", '\n')
try:
option = int(input("Enter an option: "))
if option == 1:
difficulty()
elif option == 2:
start()
elif option == 3:
return
else:
print("Incorrect option, try again!")
except ValueError:
print("Invalid option.")
def difficulty():
try:
d = int(input("Choose level of difficulty: "))
if 1 <= d <= 5:
print(d)
start()
else:
print("Incorrect option, try again.")
except ValueError:
print("Invalid value.")
def start():
print("Starting game...")
if __name__ == "__main__":
main_menu()
Let me know if anything is misunderstood or mistaken.