我遇到一个错误,其中totalp
似乎没有进行计算。用户应该输入他们想要的商品的编号,直到按5停止订单为止,然后计算输入的总价,但是我不知道该怎么做,因为错误是问题的一部分
这是我得到的错误:
UnboundLocalError: local variable 'totalp
在分配前被引用了
print ("""
MENU ITEMS \t \t PRICES
1. Pizza \t \t $7.29 sm $12.39 lg
TOPPINGS
2. Green Peppers \t $1.50
3. Mushrooms \t \t $1.00
4. Pepperoni \t \t $2.00
5. Complete my order
""")
name = input("What is your name? ")
p_number = "How many pizzas would you like to purchase? "
t_number = "How many different toppings would you like to add? "
totalp = 0
totalt = 0
def choose_menu():
print("")
menu = int(input("What would you like to order? "))
if menu == 0:
choose_top()
if menu == 1:
p_size = input("What size of pizza would you like? \n (s for small, l for large): ")
if p_size == "s":
sprice = 7.29
totalp += sprice
print("")
print("You purchased a small pizza.")
elif p_size == "l":
lprice = 12.39
totalp += lprice
print("")
print("You purchased a large pizza.")
else:
print("")
print("Invalid entry, please reenter.")
choose_menu()
choose_top()
choose_menu()
display_receipt()
elif menu == 5:
print("Nothing was purchased.")
else:
print("Invalid entry, please reenter.")
choose_menu()
def choose_top():
print("")
topping_choice = int(input("What toppings would you like to add? "))
if topping_choice == 0:
top = "No toppings were added."
display_receipt()
elif topping_choice == 2:
top = "Green peppers added."
price2 = 1.50
totalt += price2
choose_top()
elif topping_choice == 3:
top = "Mushrooms added."
price3 = 1.00
totalt += price3
choose_top()
elif topping_choice == 4:
top = "Pepperonis added."
price4 = 2.00
totalt += price4
choose_top()
elif topping_choice == 5:
print("Order has been confirmed.")
display_receipt()
else:
print("Invalid entry, please reenter.")
choose_top()
print(top)
if menu == 1:
p_total = p_number * totalp
t_total = t_number * totalt
b_tax_total = p_total + t_total
tax = int(.0825)
sales_tax = b_tax_total * tax
total_price = b_tax_total + sales_tax
def display_receipt():
print("")
print("CUSTOMER RECEIPT:")
print("Customer name:", name)
print("The total number of pizzas ordered:", p_number)
print("The total number of toppings ordered:", t_number)
print("Total price before tax:")
print(format(b_tax_total, '.2f'))
print("Sales tax:")
print(format(sales_tax, '.2f'))
print("The total amount due:")
print(format(total_price, '.2f'))
choose_menu()
答案 0 :(得分:0)
我认为您在复制代码缩进时弄糟了。例如,display_receipt()似乎现在没有主体。请解决。同样,“ if menu == 1”行似乎也不合适。
假设您的缩进效果很好。上面显示的错误是由于以下事实导致的:totalp已在引用它的函数范围之外分配。因此,请使用(并且,如果需要,请阅读)“ global”关键字。基本上,如果您将choose_menu()函数修改为类似
def choose_menu():
global totalp
print("")
# code continues as shown above
您将获得想要的行为。总计可能需要做同样的事情。
值得一提的是,对于琐碎的情况使用全局变量通常不是最好的方法。如果可以的话,请尝试传递该值,或者在这种情况下使用允许引用的类型(例如列表)。