Correcting Errors Challenge (Burger, Fries, and Drink)
Here is some code that I made error proof so that the user can see the total cost of their meal!
For this week's hacks, we were challenged to identify and correct errors on a code segment that allows a user to order items from a menu. Below is the code with errors:
menu = {"burger": 3.99,
"fries": 1.99,
"drink": 0.99}
total = 0
#shows the user the menu and prompts them to select an item
print("Menu")
for k,v in menu.items():
print(k + " $" + str(v)) #why does v have "str" in front of it?
#ideally the code should prompt the user multiple times
item = input("Please select an item from the menu")
#code should add the price of the menu items selected by the user
print(total)
The problem with the above code is that it prompts the user to order something only one time. Also, as you can see, even if a user orders something, the total cost still remains at 0. Below is the code that has all of these errors corrected:
menu = {"burger": 3.99,
"fries": 1.99,
"drink": 0.99}
total = 0
# welcomes the user shows them the menu and prompts them to select an item
print("Hello! Welcome to our Python restaurant! What would you like?")
print("Menu")
for k,v in menu.items():
print(k + " $" + str(v)) # shows the name of the item on the menu followed by its price
#ideally the code should prompt the user multiple times
order = True
while order: # this makes it so that the user will be prompted multiple times to order something
item = input("Please select an item from the menu")
if item in menu.keys(): # If the user orders an item on the menu, the cost of that item will be added to the total cost
total+= menu[item]
print("$", round(total,3))
else: # if a user tries to order something that is not on the menu, the code will immediately exit
order = False
print("Have a nice day!")
As you can see, an item that a user orders will now have its price be added to the total cost. Also, the user can now order from the menu as many times as they want until they hit the escape key.