首页 > 解决方案 > 为什么我会收到“NameError: name 'B'/'C'/'V' is not defined”?

问题描述

Question = input("Welcome to the meal chooser program. The base cost is $9.99. Would you like to choose beef, chicken, or the vegetarian option?:")
if Question.casefold() == "beef":
    print("Thank you. Your total cost is","$",'{:.2f}'.format(B))
elif Question.casefold() == "chicken":
    print("Thank you. Your total cost is","$", '{:.2f}'.format(C))
elif Question.casefold() == "vegetarian":
    print("Thank you. Your total cost is","$", '{:.2f}'.format(V))
B = 9.99*1.02
C = 9.99*1.025
V = 9.99*1.03 

每当我运行此程序并输入鸡肉、牛肉或素食时,它都会提示我一条消息,说明 B、C 和 V 的值未定义,但它们已定义。

标签: pythonpython-3.xnameerror

解决方案


代码自上而下线性运行(除了函数调用和类初始化之类的跳转)。因为您在底部初始化变量,所以当您到达 if-else 块时,您的代码尚未创建值。如果您将变量放在首位,代码将运行良好。


推荐阅读