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")
Related
Can anyone help I am a beginner? I want the variable choice to be displayed after the menu is but I need the variable to be on top so the name inserted can be shown beside add player name.
choice = input("Input your menu choice: ")
choice = False
if choice == "1":
name = input("What is your name? ")
print(" Menu ")
print("------------------------------------------")
print(f"[1] Add player name: {name} ")
print("[2] Play guess the capital city")
print("[3] End game")
print("------------------------------------------")
choice True
I tried to use a Boolean but it didn't so any help would be great.
How about defining a string first like this?
import random
name = 'Anonomous'
playing = True
while playing == True:
print(" Menu ")
print("------------------------------------------")
print(f"[1] Add player name: {name} ")
print("[2] Play guess the capital city")
print("[3] End game")
print("------------------------------------------")
choice = input("Input your menu choice: ")
if choice == "1":
name = input("What is your name? ")
if choice == "2":
winner = False
capital_city = random.choice(['London', 'Paris', 'Rome'])
while not winner:
guess = input("What capital city am I thinking of? ").title()
if guess == capital_city:
print(f'You won!!! I was thinking of {guess}..')
winner = True
else:
print(f'No, it was not {guess}, guess again..')
if choice == "3":
playing = False
This part:
choice = input("Input your menu choice: ")
choice = False
will make choice always equal False, also you should avoid changing types of variables like above: from str to bool. Assuming that you want working and well-structured console game:
name = 'Unnamed' # Set default value of name.
# Create game loop using infinite while.
while True:
# Display the menu: use string multiplication and a little of math.
print(' ' * 18 + 'Menu' + ' ' * 18)
print('-' * 40)
print(f"[1] Add player name: {name} ")
print("[2] Play guess the capital city")
print("[3] End game")
print('-' * 40)
# Get choice from user.
choice = input("\nInput your menu choice: ")
# Perform proper action for a choice selected.
if choice == '1':
name = input("What is your name? ")
elif choice == '2':
# Load your game ...
...
# If player wants to end game, it is equivalent to exiting
# loop using 'break' statement.
elif choice == '3':
break
else:
# Define what happens if player inputted unsupported choice.
...
# It is a common way to clear screen in python console
# applications/games, if fourty lines of empty lines is not
# sufficient increase amount of them.
print('\n' * 40)
# Here you can save for instance player score or nickname and
# later read it at the beginning of file (before the game loop).
Just starting out with python functions (fun_movies in functions.py) and I can't seem to get out (via "no" or False) once in the loop:
main_menu.py
from functions import *
def menu():
print("Press 1 for movies.")
print("Press 2 to exit.")
menu()
option = int(input("Input a number: "))
while option != 0:
#try:
if option == 1:
fun_movies()
elif option == 2:
print("Goodbye! ")
break
else:
print ("Wrong input")
functions.py
global movies
movies = {}
def fun_movies():
name = input("Insert movie name: ")
genre = input("Input genre: ")
movies [name] = [genre]
a = True
while a:
query = input("Do you want to input another movie? (yes/no) ")
if query == "yes":
name = input("Insert movie name: ")
genre = input("Input genre: ")
movies_if = {}
movies_if [name] = [genre]
movies.update(movies_if)
elif query == "no":
break
else:
print ("Wrong input!")
return movies
Code works fine when not called via import. When called via import (in main_menu.py), it keeps asking for infinite movies even when I input a "no". I can't find a way to exit the loop. Initially I had a "pass" but that didn't work.
Thanks in advance!
global movies
movies = {}
def fun_movies():
name = input("Insert movie name: ")
genre = input("Input genre: ")
movies [name] = [genre]
a = True
while a:
query = input("Do you want to input another movie? (yes/no) ")
if query == "yes":
name = input("Insert movie name: ")
genre = input("Input genre: ")
movies_if = {}
movies_if [name] = [genre]
movies.update(movies_if)
elif query == "no":
a = False
else:
print ("Wrong input!")
return movies
A few things:
Firstly, you don't need a==True as this statement returns True when a is True and False when a is False, so we can just use a as the condition.
Secondly, only use the input at the start of the loop as you want to ask once per iteration
Thirdly, place your return outside the loop so you only return when a==False and you don't want to input another movie.
edit:
main file>
from functions import *
def menu():
print("Press 1 for movies.")
print("Press 2 to exit.")
menu()
option = int(input("Input a number: "))
while option != 0:
if option == 1:
fun_movies()
elif option == 2:
print("Goodbye! ")
break
else:
print ("Wrong input")
option = int(input("Input a number"))
global movies
movies = {}
def fun_movies():
name = input("Insert movie name: ")
genre = input("Input genre: ")
movies[name]= genre
a = True
while a:
query = input("Do you want to input another movie? (yes/no) ")
if query == "yes":
name = input("Insert movie name: ")
genre = input("Input genre: ")
movies_if = {}
movies_if [name] = genre
movies.update(movies_if)
elif query == "no":
break
else:
print ("Wrong input!")
# continue
return movies
print(fun_movies())
Hope It works for you!
Goal:
After the user inputs whether they want to add another new item or not I want the code to start over at the newItem input line so that I don't have to just keep the if-train going and end up adding a cap to it.
Listed below is the code I've written so far.
shopping_cart_menu = []
shopping_cart_prices = []
print("Welcome to the shopping cart program. Please select an option from the menu below.")
print("*******************")
print("01: Add a new Item")
print("02: Display Cart contents")
print("03: Remove Item")
print("04: Compute Total")
print("05: Quit")
print("*******************")
menuAnswer = input(" ")
if menuAnswer == "01":
newItem = input("What item would you like to add? ")
shopping_cart_menu.append({newItem})
followUp = input("Would you like to add another item? Y/N: ")
if answer = "Y"
Here is how you can use a while loop:
menuAnswer = input(" ")
if menuAnswer == "01":
while True:
newItem = input("What item would you like to add? ")
shopping_cart_menu.append({newItem})
followUp = input("Would you like to add another item? Y/N: ")
if answer != "Y":
break
Using a while loop will allow you to loop the if statements. The line "followup = followup.upper()" will capitalise the input too.
shopping_cart_menu = []
shopping_cart_prices = []
print("Welcome to the shopping cart program. Please select an option from the menu below.")
print("*******************")
print("01: Add a new Item")
print("02: Display Cart contents")
print("03: Remove Item")
print("04: Compute Total")
print("05: Quit")
print("*******************")
menuAnswer = input(" ")
if menuAnswer == "01":
followup = "Y"
while followup == "Y":
newItem = input("What item would you like to add? ")
shopping_cart_menu.append({newItem})
followup = input("Would you like to add another item? Y/N: ")
followup = followup.upper()
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())
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?: "))