Unable to pass/exit a python function - python

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!

Related

Python restaurant program

I'm a beginner in python & this is my 3rd program.
I'm learning functions. The user should be able to choose a number first from the menu (1. appetizers, 2.mains 3. drinks, 4.view orders, 5.exit) each one has sub-choices (example appetizers include salad, chips...etc). User should be able to return back after choosing an item.
I'm stuck in View Order option, the user needs to be able to see each of the items in their order + prices next to each item & Lastly I want to be able to show total bill.
How can i view all orders from user?
How can i calculate total? should i use loop?
def menu():
print("--MCQUAN MENU--")
print("1. Appetizers")
print("2. Mains")
print("3. Drinks")
print("4. Desserts")
print("5. View order")
print("6. Exit")
print()
def user_option():
choice = int(input("Choose from the menu & enter a number 1-6: "))
if choice == 1:
print()
print("APP - heres the apps")
print("Salad - $5")
print("Chips & salsa - $6")
print("Soup - $10")
elif choice == 2:
print("MAINS - here the mains")
print("Pasta - $13")
print("Burger - $12")
print("Pizza - $10")
elif choice == 3:
print("DRINKS - heres drinks")
print("Water - $0")
print("Tea - $3")
print("Sprite - $2")
elif choice == 4:
print("DESSERTS - heres desserts")
print("Cake - $6")
print("Ice cream - $5 ")
print("Pie - $7")
elif choice == 5:
print("VIEW ORDER -- heres ur order so far")
elif choice == 6:
print("Exiting")
else:
print("Invalid")
choice = int(input("Enter number 1-6"))
def app():
cost = 0
total = 0
user_food = input("Choose which u want ")
if user_food == "salad":
cheese = input("Cheese? (+$0.50) yes/no ")
dressing = input("Dressing? (+$1) yes/no ")
elif user_food == "chips & salsa":
spicy = input("Spicy? yes/no ")
cilantro = input("Cilantro? yes/no ")
elif user_food == "soup":
soup = input("Chicken noodle or mushroom? ")
else:
print("Alright!")
user_option()
user_food = input("Choose which u want ")
def main():
user_food = input("Choose which u want ")
if user_food == "pasta":
cheese_2 = input("Cheese? yes/no ")
chilli_f = input("Chilli flakes? yes/no ")
elif user_food == "burger":
onions = input("Onions? yes/no ")
pickles = input("Pickles? yes/no ")
elif user_food == "Pizza":
pizza = input("Cheese or pepperoni? ")
else:
print("Alright!")
user_option()
user_food = input("Choose which u want ")
def drinks():
user_food = input("Choose which u want ")
if user_food == "water":
size = input("Small, medium or large? ")
user_option()
user_food = input("Choose which u want ")
def desserts():
user_food = input("Choose which you want")
if user_food == "cake":
w_c = input("Whipped cream? yes/no ")
cherry = input("Cherry? yes/no ")
elif user_food == "ice cream":
w_c = input("Whipped cream? yes/no")
cherry = input("Cherry? yes/no ")
elif user_food == "pie":
w_c = input("Whipped cream? yes/no")
cherry = input("Cherry? yes/no ")
else:
print("Alright")
user_option()
user_food = input("Choose which u want ")
#main
menu()
print("Welcome to McQuans!")
print()
user_option()
app()
main()
drinks()
desserts()`
Ideally you do not want to keep your data in prints.
We can use data structures like lists or dicts
Here's what I suggest:
We use a list for the client order, since we can keep adding to it and we'll be adding things sequentially.
We use dicts (python dictionaries) for the menus, so we can keep track of all the items per menu and the price of each item.
client_order = []
app_menu = {
"Salad": 5,
"Chips & salsa": 6,
"Soup": 10
}
Please check out this Dict tutorial if you are not familiar with them.
Alright, let's start with this. Once you've got it I'll help you out some more if you need.

How to have input in Python only take in string and not number or anything else only letters

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.

i need multiple input to run main function phonebook python

I am having trouble writing a program to repeat input part. for instance
input 1 ___run add_contact()
again ask for input
input 4____run disp_contact()
...
...
I've never written a long code! :\
I'm totally begginer! and learning a bit of Python in my spare time
my mentor said you should define several functions and put them in a main function which get input.
so If anyone can tell me why I get stuck like this I would appreciate it.
contact={}
print(''' phone book
1. add contact
2.delete contact
3.search contact
4.display all
5.Quit''')
def add_contact():
name=input('enter the name: ')
number=input('enter the number: ')
contact[name]=number
print(name, 'added to phone book!')
def del_contact():
name=input('enter the name: ')
while name not in contact:
print("not found! try again" )
name=input('enter again: ')
else:
print(name,' deleted')
del contact[name]
name=False
def search_contact():
name=input('enter the name: ')
while name not in contact:
print('not found!')
name=input('enter again: ')
else:
print(name, 'number is :', contact[name])
def disp_contact():
if len(contact)>0:
print('phone book contacts are: ')
for i in contact:
print(i, end=' ')
else:
print('phone book is empty!')
def main_def(num):
if num==1:
add_contact()
elif num==2:
del_contact()
elif num==3:
search_contact()
elif num==4:
disp_contact()
elif num==5:
print('bye bye')
x=int(input(' enter a number: '))
main_def(x)
You may wrap the main_def in a while True, and use exit(O) to quit properly when 5 is given
def main_def(num):
if num == 1:
add_contact()
elif num == 2:
del_contact()
elif num == 3:
search_contact()
elif num == 4:
disp_contact()
elif num == 5:
exit(0)
while True:
x = int(input(' enter a number: '))
main_def(x)
Note
For del_contact and search_contact, you don't need the else just put after like this
def del_contact():
name = input('enter the name: ')
while name not in contact:
print("not found! try again")
name = input('enter again: ')
print(name, ' deleted')
del contact[name]

How to switch functions in a while loop python

I am trying to make a program that adds, delete and can view dishes a user enters. It seems very simple however, I run into issues with my while loop. When I type in add I am able to add items to my list, however, when I type view the addDish function keeps on looping. I thought I fixed it with my if statement but there's something missing ... !
dish_list = []
user_input = ''
def addDish(dish_list):
user_input = input("Please type the dish you want: ")
dish_list.append(user_input)
#def deleteDish(dish_list):
def viewDish(dish_list):
for i in range(len(dish_list)):
print(dish_list[i])
user_input = input("Please enter a command: ")
while True:
if user_input == '':
user_input = input("Please enter a command: ")
elif user_input == 'add':
addDish(dish_list, user_input)
elif user_input == 'view':
viewDish(dish_list)
Instead of having a while loop, you should call a function that asks for user input once previous input has been handled.
dish_list = []
def addDish(dish_list):
user_input = input("Please type the dish you want: ")
dish_list.append(user_input)
#def deleteDish(dish_list):
def viewDish(dish_list):
for i in range(len(dish_list)):
print(dish_list[i])
def get_input():
user_input = input("Please enter a command: ")
if user_input == 'add':
addDish(dish_list, user_input)
elif user_input == 'view':
viewDish(dish_list)
getInput()
getInput()
A bit cleaner:
dish_list = []
def add_dish(dish_list):
user_input = input("Please type the dish you want: ")
dish_list.append(user_input)
def view_dish(dish_list):
# for dish in dish_list:
# print(dish)
print('\n'.join(dish_list))
while True:
user_input = input("Please enter a command: ")
if user_input == 'add':
add_dish(dish_list)
elif user_input == 'view':
view_dish(dish_list)
else:
print("Unknown command %s" % user_input)
Your variable user_input never gets set back to empty, so you can never enter a new command since it just takes the last entry you input to user_input, which would be the dish type read in the addDish function. Also, your call to addDish has an extra parameter. I also recommend throwing everything in a main method.
def addDish(dish_list):
user_input = input("Please type the dish you want: ")
dish_list.append(user_input)
def viewDish(dish_list):
for i in range(len(dish_list)):
print(dish_list[i])
def main():
dish_list = []
while True:
user_input = ''
if user_input == '':
user_input = input("Please enter a command: ")
elif user_input == 'add':
addDish(dish_list)
elif user_input == 'view':
viewDish(dish_list)
main()
Here's a fixed version of the above code snippet:
def addDish(dish_list):
user_input = raw_input("Please type the dish you want: ")
dish_list.append(user_input)
#def deleteDish(dish_list):
def viewDish(dish_list):
for dish in dish_list:
print(dish)
dish_list = []
while True:
user_input = raw_input("Please enter a command: ")
if user_input == 'add':
addDish(dish_list)
elif user_input == 'view':
viewDish(dish_list)
elif user_input == 'exit':
print('Over!')
break
else:
print('Wrong entry. Retry...')
Execution output:
$python so.py
Please enter a command: add
Please type the dish you want: Bread
Please enter a command: add
Please type the dish you want: Burger
Please enter a command: view
Bread
Burger
Please enter a command: foo
Wrong entry. Retry...
Please enter a command: exit
Over!
$

Limit the amount of inputs in a Python list

I want to set a limit to which the user can input names. This is where I got to and got stuck. How would I set a limit of 10 to the names the user can input into the list and restrict them from entering anymore?
names = []
print ('1 = Add Name ')
print ('2 = Display List ')
print ('3 = Quit ')
while True:
option = input('What would you like to do: ')
if option == '1':
name= input('Enter name: ')
names.append(name)
you can do :
if option == '1':
names = [input('Enter name:') for _ in range(10)]
I hope that following script can help you:
# libraries
import sys
# list variable to store name
names = []
# limits to save name
limit = 10
# function to display menu
def menu():
print("Enter 1 to add Name")
print("Enter 2 to show list")
print("Enter 3 to quit")
choice = int(raw_input("Enter your choice : "))
return choice
# running for infinite times till user quits
while(True):
choice = menu()
if(choice == 1):
name = raw_input("Enter name to add in list : ")
if(len(names) > 10):
print("You cannot enter more names")
else:
names.append(name)
print(name + " - Name saved successfully.")
if(choice == 2):
print("List of names : ")
print(names)
if(choice == 3):
sys.exit()

Categories

Resources