简体   繁体   中英

Iterate through list in a list

1st year of CSE in HS. Coding a pizza order program. Teacher wants a separate function for computing cost. I am struggling with getting the program to add on the price of the toppings. Each pizza is $13 and toppings are extra. Goal is to have it charge for a plain pizza (empty list), pizza with toppings, or no pizza at all.

def pizza_cost(pizza):
  global total
  total += 13.00
  for y in pizza:
    if (y == "Pepperoni"):
      total += 1.00

order = input("Would you like to make an order? (y or n)")
while order != "n":
  pizza_order = input("Would you like a pizza? (y or n)")
  pizza = []
  while pizza_order.upper() != "N":
    if pizza_order.upper() == "Y":
      topping_option = input("Would you like to add a topping? (y or n)")
      while topping_option.upper() != "N":
        topping_list = []
        topping = input("What topping would you like? Pepperoni (p), Mushroom (m)")
        if topping.upper() == "P":
          topping_list.append("Pepperoni")
        elif topping.upper() == "M":
          topping_list.append("Mushroom")
        topping_option = input("Would you like to add another topping? (y or n)")
      pizza.append(topping_list)
    pizza_order = input("Would you like another pizza? (y or n)")
  for x in pizza:
    pizza_cost(pizza)
# Example order (Two plain pizzas and pizza with double-pepperoni)
([], [], ["Pepperoni", "Pepperoni"])

The only problem in your code is that you are passing the list of pizza lists pizza , instead of a single pizza x , to the pizza_cost function, at the end of your code:

  for x in pizza:
    pizza_cost(pizza)

If you pass x instead, your whole code will do what you want;) !

  for x in pizza:
    pizza_cost(x)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM