首页 > 解决方案 > 如何获取或初始化我想要的变量?

问题描述

我正在尝试编写一个简单的程序,但是我遇到了一个问题,即程序最终没有输出给定的变量“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()

标签: python

解决方案


当你初始化时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!")

推荐阅读