Question

i am making a pizza ordering system for a project, the user chooses how many pizzas they want with this:

pizza_number=0
goodpizza_number=False 
while not goodpizza_number:
    try:
        pizza_number= int(input("How many Pizzas do you want? (MAX 5): "))
        if pizza_number ==0 or pizza_number > 5:
            print("Not a correct choice, Try again")
        else:
            goodpizza_number=True 
    except ValueError:
        print("Not a number, Try again")

and then there is a list of pizzas for the user:

PIZZA_LIST=["Tandoori chicken: $8.50", "Prawn: $8.50", "Ham and cheese: $8.50", "Pepperoni: $8.50", "Hawaiian: $8.50","Beef and onion: $8.50","Meat lovers: $8.50", "Satay chicken: $13.50", "Apricot chicken: $13.50", "Supreme cheese:13.50", "Italian beef: $13.50", "Mediterraneo: $13.50"]
for index in range(0, len(PIZZA_LIST)):
    print(index, PIZZA_LIST[index])

and the user is able to choose what pizzas they want with this:

pizza=[] 
for n in range(pizza_number): #covers values from 0 to 9 
    pizza = pizza + [int(input("Choose a pizza: "))] 
print(pizza) 

The first 7 pizzas on the list have to be $8.50 and the last 5 pizzas on the list have to be $13.50. how can i add the user's choices together and get the prices of all the pizzas they chose and add to the total cost?

Was it helpful?

Solution

First, you might want to change how the pizza names and prices are presented. Since you get user input as integer, I would suggest using list of tuples:

pizzas_with_prices = [('Tandoori chicken', 8.5), ('Prawn', 8.5) ..., ('Mediterraneo', 13.5)]

then you can loop over your pizza list (which could be better named as selected_pizzas or so):

total_price = 0
for selected in selected_pizzas:
  total_price += pizzas_with_prices[selected][1]
print total_price

Also, couple of suggestions to improve the code:

For the first code block, you can get rid of the goodpizza_number

number_of_pizzas = 0
while 0 < number_of_pizzas <= 5:
  try:
    number_of_pizzas = int(input("How many Pizzas do you want? (MAX 5): "))
  except ValueError:
    print("Not a number, try again")

On the second block, as suggested, you could use list of tuples and use enumerate

pizzas_with_prices = [('Tandoori chicken', 8.5), ('Prawn', 8.5) ..., ('Mediterraneo', 13.5)]
for index, pizza in enumerate(pizzas_with_prices):
  print("%d %s: $%s" % (index, pizza[0], pizza[1]))

OTHER TIPS

You need to create another pizza name and pizza price in a dict. The user choice of pizza can be put in a list. Once you have the list, iterate over the list to get price from pizza name-price dict and add then to get total price.

total_cost = sum([float(PIZZA_LIST[idx].split('$')[1]) for idx in pizza])

By the way: you can replace

pizza = pizza + [int(input("Choose a pizza: "))] 

with

pizza.append(int(input("Choose a pizza: ")))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top