Why do I get "NameError: name 'B'/'C'/'V' is not defined"?

Why do I get "NameError: name 'B'/'C'/'V' is not defined"?

Question = input("Welcome to the meal chooser program. The base cost is .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 的值未定义,但它们是。

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