[英]Python Error, Local variable might be referenced before assignment, variable outside the if condition
我是python编程实践的新手,做了我的第一个基本程序
我必须访问并打印if函数中的局部变量,并且如果我尝试访问它,它表明可能引用了局部变量
这是完整的代码
def main():
print("Please place your order by filling the options")
name = input("What is your name ")
while not name.isalpha():
print("invalid name")
age = input("What is your age ")
if not age.isdigit():
print("Please type in correct form")
if age >= "50":
print("you are not allowed!")
sys.exit()
item_1 = "burger"
item_2 = "pizza"
print("what would you like to order?")
print(item_1 + "\n" + item_2)
order = input()
item_1_large = "large burger"
item_1_small = "small burger"
item_2_large = "large pizza"
item_2_small = "small pizza"
if order == item_1:
print("What would you like to choose?")
print(item_1_large + "\n" + item_1_small)
selection_of_category = input()
elif order == item_2:
print("What would you like to choose?")
print(item_2_large + "\n" + item_2_small)
selection_of_category = input()
print("How many ")
number_of_order = input()
burger_price_large = int(10)
burger_price_small = int(5)
pizza_price_large = int(15)
pizza_price_small = int(8)
if order == item_1_large:
result = burger_price_large * int(number_of_order)
elif order == item_1_small:
result = burger_price_small * int(number_of_order)
elif order == item_2_large:
result = pizza_price_large * int(number_of_order)
elif order == item_2_small:
result = pizza_price_small * int(number_of_order)
if order == item_1:
print("Your Burger Order Has Been Placed")
elif order == item_2:
print("Your Pizza Order Has Been Placed")
else:
print("You have made wrong choice")
print("Dear Mr. " + name, "Your Total Bill is $" + str (result))
while True:
main()
if input("Would you like to order something? (Y/N)").strip().upper() != 'Y':
today = date.today()
print("Thank you for your order")
print(today)
break
而且我有以下错误打印(“亲爱的先生” +名称,“您的总帐单为$” + str(结果))UnboundLocalError:赋值之前引用了局部变量'result'
您的问题是仅在if和else-if语句下定义结果。 这意味着,如果if或else-if语句中的每个条件都失败,则不会定义结果,但是您将尝试使用其值。
您有两种解决此问题的方法:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.