python - 为什么我会收到“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 的值未定义,但它们已定义。
解决方案
代码自上而下线性运行(除了函数调用和类初始化之类的跳转)。因为您在底部初始化变量,所以当您到达 if-else 块时,您的代码尚未创建值。如果您将变量放在首位,代码将运行良好。
推荐阅读
- typescript - 如何修复“x”可分配给“y”类型的约束,但“y”可以用约束“x”的不同子类型实例化
- sql - SQL - 将计划表与实际表与计划表中的日期标准合并。对于 Power BI
- angular - 无法以角度访问模型的获取功能
- javascript - 未安装使用条带的 Iban 元素
- javascript - 如何从 jQuery 日期选择器中的值中识别季度?
- javascript - 如何设置两个并排的div独立滚动?
- perl - 500 无法连接到 localhost:443(证书验证失败)
- python - 如何创建两个独立的彩色视频,包括移动和固定对象?
- javascript - 如何使用 JavaScript 过滤或显示 Spring Boot 中两个选定日期之间的数据?
- mongodb - MongoDB连接异常增加