python - 如何获取或初始化我想要的变量?
问题描述
我正在尝试编写一个简单的程序,但是我遇到了一个问题,即程序最终没有输出给定的变量“tax”。
def main():
# define and initialize constants and variables
menu1 = 6
menu2 = 2.5
menu3 = 1.25
menu4 = 3.75
choose = total = 0
tax = total*0.06
# display welcome
print("Welcome to Yum Yum Snack Bar!")
try:
while choose != 5:
print("\nPlease choose from the following menu:")
print("1) Personal Pizza $6.00")
print("2) Pretzel $2.50")
print("3) Chips $1.25")
print("4) Hot Dog $3.75")
print("5) Exit ")
choose = int(input("\nEnter your choice here: "))
if choose == 1:
total += menu1
elif choose == 2:
total += menu2
elif choose == 3:
total += menu3
elif choose == 4:
total += menu4
elif choose == 5:
continue
else:
print("Invalid choice. Must choose 1 – 5. Try again.")
print("Current total: $",total)
except:
print("Invalid choice. Must choose 1 – 5. Try again.")
main()
print("Current total: $",total)
print("Sales tax: $",tax)
print("Total Bill: $",total+tax)
print("Have a nice day!")
main()
解决方案
当你初始化时tax
,你给了它一个值,0
因为total*0.06
那时等于零。
python 逐行运行,所以变量“ tax
”没有改变整个代码的值,你只改变了“ total
”。
所以要得到税,你应该重新计算。
print("Current total: $",total)
tax=0.06*total
print("Sales tax: $",tax)
print("Total Bill: $",total+tax)
print("Have a nice day!")
推荐阅读
- json - Firebase 云消息服务器帐户密钥过期
- sql-server - 如何在 rdlc 和 vb,net 中的报告上显示参数值
- android-studio - 右键单击 res 文件夹时找不到“在资源管理器中显示”
- android - 在数据库中获取空白条目
- c# - 异常没有被 catch 捕获
- eclipse - 如何在 Eclipse 中安装插件开发的源代码?
- sql - 如何编写 SQL 查询以获得以下场景输出
- angular - 在 HTTP 响应后调用时,角度数据表显示错误“无法读取未定义的属性 aDatasort”
- ruby-on-rails - 如何将枚举与复选框导轨一起使用
- java - 我正在尝试从 Drawable 加载图像,但它没有在 imageview 中显示任何图像