python - 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
解决方案
您的问题是 result 仅在 if 和 else-if 语句下定义。这意味着如果 if 或 else-if 语句中的每个条件都失败,则不会定义结果,但您将尝试使用它的值。
您有两种解决方案来解决此问题:
- 使最后一个 elif 成为一个 else 成为一个包罗万象的东西,并且对所有可能的 order 值都有一个值
- 如果所有 if 和 elif 条件均失败,则在最后一个 elif 之后有一个单独的 else 以将结果定义为“N/A”之类的东西。
推荐阅读
- javascript - fabric.Image.filters.Blend 不是构造函数
- reactjs - React 不会让我以完全合理的方式使用 `useEffect`
- django - 即使尚不支持 SAVEPOINTS 功能,YugabyteDB 是否支持 Django?
- php - PHP Laravel - 通过搜索获取模型数组或返回空数组
- database - 访问更新不更新记录
- macos - Solana 测试验证器 -- dyld:未加载库:/usr/local/opt/openssl@1.1/lib/libssl.1.1.dylib
- xcode - 没有名为 BootSplash 的故事板 react-native-bootstrap
- sparql - 使用 Jena 列出 N-triple 文件中的所有类和实例
- c# - CSV 文件中的 double[] = ToArray()
- c# - 如何防止在浏览器后退按钮上重新提交表单?