[英]why do i keep getting this python error cost is not defined?
print("============================================================\n"
" Welcome to Pizza Store \n"
"============================================================\n")
def welcomescreen():
print("1) Menu for the Pizza")
print("2) Order the Pizza")
print("3) Exit the program")
ch = input("Select from one of the above: ")
return ch
def main():
choice = welcomescreen()
while choice != '3':
# based on user choice add appropriate method
if choice == '1':
print("1. Pepperoni 9 AED\n2. Margherita 12 AED\n3. Vegetarian 15 AED\n4. Neapolitan 21 AED")
ask = input("Do you want to go back to the main menu? yes/no : \n").lower()
if ask == "yes":
main()
elif ask == "no":
break
elif choice == '2':
n=int(input("Enter the number of pizzas to be ordered: "))
kind=input("Enter the kind of Pizza: ")
size=input("Enter the size of Pizza\n(Large (50 AED),Medium (40 AED), Small (30 AED) : ")
if(size == "Large"):
cost_size=n*50
elif(size == "Medium"):
cost_size=n*40
elif(size == "Small"):
cost_size = n*30
if(kind == "Pepperoni"):
cost= n*10
pizza = 'Pepperoni'
elif(kind== "Margherita" ):
cost= n*15
pizza = "Margherita"
elif(kind == "Vegetarian" ):
cost= n*20
pizza = "Vegetarian"
elif(kind== "Neapolitan"):
cost= n*18
pizza = "Neapolitan"
d=input("Enter toppings: \n").split(" ")
extra=0
if(len(d)>3):
extra= n*3*(len(d)-3)
#final Bill
print("---------------------Your BILL-----------------------\n")
print("The Pizza kind :", kind)
print("The size :", size)
print("Number of pizzas : x", n)
print("Extra toppings :")
for i in d:
print(i,end=" ")
print("\n")
print("==========Breakdown of bill========== \n")
print("Bill for pizza : ", cost)
print("Bill for size : ",cost_size)
print("Bill for extra toppings: ",extra)
print("Total Bill : ",cost+cost_size+extra)
else:
print("Invalid choice. Try again.")
choice = welcomescreen()
print("Thank you! Have a nice day :)")
main()
我得到的錯誤是:
披薩種類:意大利辣香腸尺寸:大披薩數量:x 1 額外配料:意大利辣香腸
==========賬單明細==========
Exception has occurred: UnboundLocalError
cannot access local variable 'cost' where it is not associated with a value
File "C:\Users\mandoof1\Downloads\Pizza part A.py", line 57, in main
print("Bill for pizza : ", cost)
File "C:\Users\mandoof1\Downloads\Pizza part A.py", line 68, in <module>
main()
應該發生的是根據您的輸入計算成本並給您賬單
只有當kind
是您在 if/elifs 中檢查的三個字符串之一時,才會定義cost
。 具體來說,我認為發生的事情是你輸入了“意大利辣香腸”,但你真的想輸入“意大利辣香腸”(注意大寫)
為了更普遍地處理這個問題,您可能想要:
.lower()
輸入kind
和你要檢查的內容,所以你不必擔心大寫else
子句,這樣如果用戶輸入了意想不到的東西,你就會知道。size
輸入也重復這兩個修復。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.