Python restaurant program - python

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.

Related

How do I apply the sellProduct method to each choice in the menu?

I don't understand why I can't connect the processSale method to the sellProduct method. I think that the classes and other methods don't need any change because I only followed the criterias that were given to me.
#candy machine
class CashRegister:
def __init__(self, cashOnHand = 500,):
if cashOnHand < 0:
self.cashOnHand = 500
else:
self.cashOnHand = cashOnHand
def currentBalance(self):
return self.cashOnHand
def acceptAmount(self, cashIn):
self.cashOnHand += cashIn
class Dispenser:
def __init__(self, numberOfItems = 50, productCost = 50):
if numberOfItems < 0:
self.numberOfItems = 50
else:
self.numberOfItems = numberOfItems
if productCost < 0:
self.productCost = 50
else:
self.productCost = productCost
def getCount(self):
return self.numberOfItems
def getProductCost(self):
return self.productCost
def makeSale(self):
self.numberOfItems -= 1
class MainProgram:
def showMenu(self):
global userInput
print("**** Welcome to Eros' Candy Shop ****")
print("To select an item enter")
print("""1 for Candy
2 for Chips
3 for Gum
4 for Cookies
0 to View Balance
9 to Exit""")
userInput = int(input("Enter your choice: "))
def sellProduct(self, useDispenser = Dispenser(), useRegister = CashRegister()):
try:
self.useDispenser = useDispenser
self.useRegister = useRegister
if self.useDispenser.getCount != 0:
print(f"It costs {self.useDispenser.getProductCost} cents")
cash = int(input("Please enter your payment: "))
change = cash - self.useDispenser.getProductCost
if change < 0:
print("Insufficient money!")
print(f"You need {self.useDispenser.getProductCost - cash} cents more")
return
else:
print(f"Your change is {change} cents")
self.useRegister.acceptAmount(self.useDispenser.getProductCost)
self.useDispenser.makeSale
return
elif self.useDispenser.getCount == 0:
print("The product you chose is sold out! Try the other itmes")
return
except ValueError:
print("You entered an incorrect value. Please use the numbers on the menu only")
def processSale(self):
Register = CashRegister()
Candy = Dispenser()
Chips = Dispenser()
Gum = Dispenser()
Cookies = Dispenser()
while True:
self.showMenu
if userInput == 1:
self.sellProduct(Candy, Register)
elif userInput == 2:
self.sellProduct(Chips, Register)
elif userInput == 3:
self.sellProduct(Gum, Register)
elif userInput == 4:
self.sellProduct(Cookies, Register)
elif userInput == 0:
print("Current Balance is" + str(Register.currentBalance))
elif userInput == 9:
break
mainProgram = MainProgram()
mainProgram.showMenu()
How do i use sellProduct method on userInput 1-4. I get confused when applying the properties of a class and how to connect them. Can you point out what mistakes I made and what other improvements I can do.
here are some points you can improve :
When you call your methods do not forget the parenthesis :
self.useDispenser.getCount()
self.useDispenser.getProductCost()
Create an infinite loop to continuously ask for input within showMenu and delete the one within processSale (for example):
def showMenu(self):
global userInput
userInput = 0
print("**** Welcome to Eros' Candy Shop ****")
while userInput != 9:
print("To select an item enter")
print(MENU)
userInput = int(input("Enter your choice: "))
if userInput < 9:
self.processSale()
But please update the whole program accordingly.
Hope it helps !

I want to put a input variable before print (menu) but I want it to be printed after the menu

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).

Unable to pass/exit a python function

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!

python checking time to board plane - if not in 45 minutes, then calculates how long to wait

Ok so I am creating a program so that the user inputs their plane departure time
if the plane departure time is within 45 minutes of current (strftime) then they can procees to board
else, they are told how long until they can make way to gate
e.g. their plane leaves at 8.00 and current time is 7.00 (they cant board yet) so it says they have to wait for 15 minutes
bag = 0
minute = 0
array = []
f_row = ""
f_col = ""
name = ""
x = 0
from time import strftime
def weight():
global bag
print("Bag checking section")
print("")
bag = int(input("Enter weight of your bag: "))
if bag >= 23:
bag += 1
print("You need to pay £4 per extra KG")
print("New total to pay is: £",bag * 4)
elif bag > 0 and bag < 23:
print("Price: free")
else:
print("Try again")
def exchange():
print("Welcome to our exchange system")
print("")
money = float(input("How much money to exchange: £"))
print("1 for DOLLARS")
print("2 for RUPEE")
choice = input("Option: ")
if choice == "1":
print("£",money,"exchanged to $",round((money * 1.35)))
elif choice == "2":
print("£",money,"exchanged to ₹",round((money * 99.40)))
def boarding():
print("Check to see how long until you can board")
print("")
departure = input("Enter time of flight in 24h format: ")
hour = departure[0]+departure[1]
minute = departure[2]+departure[3]
print(hour,minute)
time = minute - 45
print(time)
def seats():
print("")
print("Choose your seats")
print(" ")
name = input("Enter name: ")
f_row = int(input("Enter row to sit in: "))
f_col = int(input("Enter column number: "))
grid = []
print("")
if array[f_row][f_col] != "empty":
print("Seat taken, try again")
elif array[f_row][f_col] == "empty":
array[f_row][f_col] = name
def make():
for x in range(10):
array.append([])
for y in range(7):
array[x].append("empty")
def show():
for row in range(10):
for col in range(7):
symbol = array[row][col]
print(symbol, end = " ")
print()
#main
while True:
print("")
print(strftime("%H:%M%p"))
print("")
print("1 to weigh bag")
print("2 for exchange")
print("3 for time until you can get on plane")
print("4 for choosing seat")
print("5 to exit program")
print("")
choice = input("Option: ")
print("")
if choice == "1":
weight()
elif choice == "4":
make()
show()
seats()
make()
show()
elif choice == "5":
break
elif choice == "2":
exchange()
elif choice == "3":
strftime("%H:%M%p")
print("")
boarding()
else:
print("Try again")
please note I have just started python and will not understand lots of complex code
if possible can it be reallt basic how to do this? thanks

Code in Python that can Calculate Different Product Values, Discounts, etc., for Use by Customers at Shops

I am currently trying to create a code that will help people in shops who need to:
Calculate the item with the best value (out of up to 10 items)
Calculate the sale price
Calculate the discount
Create a shopping cart or a shopping list
Print a receipt (just by simply showing the items, the quantity and the the cost of each products, then showing the total cost at the bottom)
I have only worked on the top four points above, but I have not a single idea on how to create and print a receipt. Here's my code so far:
#This part greets the user, and lets the user know that the application has started
print("Hello there!")
#This starts off the loop, but this variable may be changed later on
cont = "yes"
#This is the actual loop
while cont == "yes" or cont == "Yes" or cont == "YES":
print("Choose an option below:")
#This shows the options
print("1) Calculate the value of different product sizes")
print("2) Calculate the sale price")
print("3) Calculate the discount")
print("4) Create a shopping list")
print("5) Exit")
#This part lets the user choose what they would like to do
option = float(input("Choose an option (1/2/3/4/5): "))
#This is what happens if the user chooses Option 4
if option == 4:
#This is the "Shopping list" part of the application below
import os,sys,time
sl = []
try:
f = open("Your_shopping_list.txt","r")
for line in f:
sl.append(line.strip())
f.close()
except:
pass
def mainScreen():
print("Your list contains",len(sl),"items.")
print("Please choose from the following options:")
print("1) Add to the list")
print("2) Delete from the list")
print("3) View the list")
print("4) Quit the program")
choice = input("Enter your choice here (1/2/3/4): ")
if len(choice) > 0:
if choice == "1":
addScreen()
elif choice == "2":
deleteScreen()
elif choice == "3":
viewScreen()
elif choice == "4":
sys.exit()
else:
mainScreen()
else:
mainScreen()
def addScreen():
print("Please enter the name of the item that you want to add.")
print("Press ENTER to return to the main menu.")
item = input("Item: ")
if len(item) > 0:
sl.append(item)
print("Item added.")
saveList()
time.sleep(1)
addScreen()
else:
mainScreen()
def viewScreen():
for item in sl:
print(item)
print("Press ENTER to return to the main menu")
input()
mainScreen()
def deleteScreen():
global sl
count = 0
for item in sl:
print(count, " - ", item)
count = count + 1
print("Press ENTER to return to the main menu.")
print("Which item do you want to remove?")
choice = input("Enter your choice here: ")
if len(choice) > 0:
try:
del sl[int(choice)]
print("Item deleted...")
saveList()
time.sleep(1)
except:
print("Invalid number")
time.sleep(1)
deleteScreen()
else:
mainScreen()
def saveList():
f = open("Your_shopping_list.txt", "w")
for item in sl:
f.write(item)
f.close()
mainScreen()
#This is what happens if the user chooses Option 1
#This is the part that calculates the value of up to 10 products
if option == 1:
#This notifies the user that there can only be up to 10 product sizes entered
print("Please note: This code can only take up to 10 product sizes.")
#This asks the user how many products there are
products = int(input("How many products are there? "))
#This is just in case the user still types that there are over 10 products
if products > 10:
print("This code can only take up to 10 product sizes.")
print("Please enter only up to 10 product sizes below.")
if products <= 1:
#This tells the user that they must enter at least 2 product sizes to compare them
print("You must enter at least two product sizes to compare.")
if products >= 1:
#This asks for information because the user may just be looking for the $/g.
cost1 = float(input("Cost of first product($): "))
mass1 = float(input("Mass of first product(g): "))
ans1 = cost1/mass1
a = ans1
#This part substitutes undefined variables with a blank
#This is in case the number of sizes being compared doesn't reach 2 to 10
ans2 = ""
ans3 = ""
ans4 = ""
ans5 = ""
ans6 = ""
ans7 = ""
ans8 = ""
ans9 = ""
ans10 = ""
#This is for when there are two or more product sizes
if products >= 2:
cost2 = float(input("Cost of second product($): "))
mass2 = float(input("Mass of second product(g): "))
ans2 = cost2/mass2
if a > ans2:
a = ans2
#This is for when there are three or more product sizes
if products >= 3:
cost3 = float(input("Cost of third product($): "))
mass3 = float(input("Mass of third product(g): "))
ans3 = cost3/mass3
if a > ans3:
a = ans3
ans4 = ""
ans5 = ""
ans6 = ""
ans7 = ""
ans8 = ""
ans9 = ""
ans10 = ""
#This is for when there are four or more product sizes
if products >= 4:
cost4 = float(input("Cost of fourth product($): "))
mass4 = float(input("Mass of fourth product(g): "))
ans4 = cost4/mass4
if a > ans4:
a = ans4
ans5 = ""
ans6 = ""
ans7 = ""
ans8 = ""
ans9 = ""
ans10 = ""
#This is for when there are five or more product sizes
if products >= 5:
cost5 = float(input("Cost of fifth product($): "))
mass5 = float(input("Mass of fifth product(g): "))
ans5 = cost5/mass5
if a > ans5:
a = ans5
ans6 = ""
ans7 = ""
ans8 = ""
ans9 = ""
ans10 = ""
#This is for when there are six or more product sizes
if products >= 6:
cost6 = float(input("Cost of sixth product($): "))
mass6 = float(input("Mass of sixth product(g): "))
ans6 = cost6/mass6
if a > ans6:
a = ans6
ans7 = ""
ans8 = ""
ans9 = ""
ans10 = ""
#This is for when there are seven or more product sizes
if products >= 7:
cost7 = float(input("Cost of seventh product($): "))
mass7 = float(input("Mass of seventh product(g): "))
ans7 = cost7/mass7
if a > ans7:
a = ans7
ans8 = ""
ans9 = ""
ans10 = ""
#This is for when there are eight or more product sizes
if products >= 8:
cost8 = float(input("Cost of eighth product($): "))
mass8 = float(input("Mass of eighth product(g): "))
ans8 = cost8/mass8
if a > ans8:
a = ans8
ans9 = ""
ans10 = ""
#This is for when there are nine or more product sizes
if products >= 9:
cost9 = float(input("Cost of ninth product($): "))
mass9 = float(input("Mass of ninth product(g): "))
ans9 = cost9/mass9
if a > ans9:
a = ans9
ans10 = ""
#This is for when there are ten or more product sizes
if products >= 10:
cost10 = float(input("Cost of tenth product($): "))
mass10 = float(input("Mass of tenth product(g): "))
ans10 = cost10/mass10
if a > ans10:
a = ans10
#There's nothing for 10+ sizes for there is no loop for it'll make the code too long
#This tells the user the which product size(s) is/are the ones with the best value
#This tells the user the final result
if products >= 1:
print("The product(s) with the best value is/are the below product number(s):")
if ans1 == a:
print(1)
if ans2 == a:
print(2)
if ans3 == a:
print(3)
if ans4 == a:
print(4)
if ans5 == a:
print(5)
if ans6 == a:
print(6)
if ans7 == a:
print(7)
if ans8 == a:
print(8)
if ans9 == a:
print(9)
if ans10 == a:
print(10)
#This tells the user the cost per gram of the product(s) with the best value is/are
print("The cost per gram is $", a, "/ g")
#This tells the user to pick the size with best quality if multiple are above
#Sometimes, items with the best value may not have the best quality.
print("If there are multiple options above, choose the one with best quality.")
#This is what happens if the user chooses Option 2
#This calculates the price after a discount
if option == 2:
#This asks for the ticket (original) price of a specific product
p = float(input('The ticket (original) price($): '))
#This asks for the discount (in percentage) of a specific product
d = float(input('The discount(%): '))
#This then puts the information together and calculates the discount...
s = (d*0.01)
ps = (p*s)
answer = (p - ps)
answer2 = str(round(answer, 2))
print('The discount is $', ps)
#... and also the final discounted price.
#Finally, it tells the user the result
print('The final price is $', answer2)
#This is what happens if the user chooses Option 3
#This calculates the discount (in percentage)
if option == 3:
#This collects information about what the ticket (original) price was
o = float(input('The ticket (original) price($): '))
#This asks what the price of the product after the discount is
#Then it takes all the information, puts them together and calculates the discount(%)
d = float(input('Price after the discount($): '))
p = 100/(o/d)
p = str(round(p, 2))
#Finally, it tells the user the result
print('The percentage discount is', p,'%')
#This is the final option, which is for the user to quit using this application
if option == 5:
#This asks the user one last time in case they accidentally pressed 5.
exit = input("Are you sure you want to exit? (Yes/No): ")
#There are three versions of "Yes" to make the application more user-friendly
if exit == "yes":
#"Thank you and goodbye" thanks the user for using this application
#Then, it says goodbye and ends the application
print("Thank you and goodbye!")
cont = 'no'
if exit == "Yes":
print("Thank you and goodbye!")
cont = 'no'
if exit == "YES":
print("Thank you and goodbye!")
cont = 'no'
#But if exit doesn't equal "Yes" or "yes" or "YES", then cont still equals "yes".
#And if cont = "yes", then the loop restarts.
#This is if the user doesn't choose any of the above and enters an invalid input
elif option != 1:
if option != 2:
if option != 3:
if option != 4:
if option != 5:
print('Invalid input')
#This asks if the user would like to continue or quit
cont = input('Continue? (Yes/No): ')
#To make the application more user-friendly, there are again three versions of "No"
if cont == 'No':
#"Thank you and goodbye" thanks the user for using this application
#Then, it says goodbye and ends the application
print("Thank you and goodbye!")
if cont == 'no':
print("Thank you and goodbye!")
if cont == 'NO':
print("Thank you and goodbye!")
Here are some improvements:
1.Use a class instead to store different related things
class Ingredient():
def __init__(self, name):
self.name = name
self.cost = float(input(f"Cost of {self.name}($): "))
self.mass = float(input(f"Mass of {self.name}(g): "))
self.ans = cost6 / mass6
2.Then you don't need ten answer variables. You can use a list
wrong:
ans2 = ""
ans3 = ""
...
option1 = input()
option2 = input()
...
right:
ingredients = []
for i in range(0, products):
ing = Ingredient("Product " + str(i + 1))
ingredients.append(ing)
3.Use lists to compare different options
elif option != 1:
if option != 2:
if option != 3:
if option != 4:
if option != 5:
can be replaced by
if option not in [1, 2, 3, 4, 5]:
and
if exit == "yes":
print("Thank you and goodbye!")
...
could be
if exit in ["yes", "YES", "Yes"]:
print("Thank you and goodbye!")
cont = 'no'
same for cont == No
Then showing a receipt will be easy
totalCost = 0
for item in ingredients:
print(item.name, str(item.cost), str(item.mass))
totalCost += item.cost
print(totalCost + "$")
Here is a solution (I hope this answers your question):
print ('How many items are you planning to buy?')
times = int(input('>> '))
def question(times):
grocery_list = {}
print ('Enter grocery item and price.')
for i in range(times):
key = input('Item %d Name: ' % int(i+1))
value = input('Item %d Price: $' % int(i+1))
grocery_list[key] = value
print(grocery_list)
totalPrice = sum([float(grocery_list[item]) for item in grocery_list])
print('Total: ${:.2f}'.format(totalPrice))
question(times)
print('< >')
Maybe consider using this as a solution, as it is an improved version of user13329487 's code:
def inputGroceries():
groceries = list()
while True:
try:
i = len(groceries)
name = input('Item #{} name: '.format(i))
if name == '':
break
price = float(input('Item #{} price: $'.format(i)))
quantity = int(input('Item #{} quantity: '.format(i)))
except ValueError:
print('Error: invalid input..')
continue
groceries.append((name, price, quantity))
return groceries
print("Enter items, price and quantity (end list by entering empty name):")
groceries = inputGroceries()
for item in groceries:
print('{} x {} (${:.2f} PP)'.format(item[2], item[0], item[1]))
totalPrice = sum([item[1] * item[2] for item in groceries])
print(30*'-')
print('Total: ${:>22.2f}'.format(totalPrice))

Categories

Resources