首页 > 解决方案 > Python 错误,局部变量可能在赋值之前被引用,变量在 if 条件之外

问题描述

我是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

我遇到以下错误 print("Dear Mr." + name, "Your Total Bill is $" + str (result)) UnboundLocalError: local variable 'result' referenced before assignment

标签: pythonlocal-variables

解决方案


您的问题是 result 仅在 if 和 else-if 语句下定义。这意味着如果 if 或 else-if 语句中的每个条件都失败,则不会定义结果,但您将尝试使用它的值。

您有两种解决方案来解决此问题:

  1. 使最后一个 elif 成为一个 else 成为一个包罗万象的东西,并且对所有可能的 order 值都有一个值
  2. 如果所有 if 和 elif 条件均失败,则在最后一个 elif 之后有一个单独的 else 以将结果定义为“N/A”之类的东西。

推荐阅读