如何为第一次迭代设置变量,但在每次迭代后不断更改?

2024-04-20 05:30:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在python上做一个简单的加钱程序。我试图使它在函数changeCalculator()的第一次迭代中设置为0.0。对于第二次迭代,我希望coin设置为0.0+我选择的任何数量。然后我希望函数重复,直到用户点击“q”。我的问题是,如果每次迭代都不将coin设置为0.0,我就无法第一次将coin设置为0.0

def changeCalculator():
    coin = 0.0                      
    coin = input()
    if coin == 'a':
        money = money + 20.0
        print(money)
        return money
    elif coin == 's':
        money = money + 10.0
        print(money)
        return money
    elif coin == 'd':
        money = money + 5.0
        print(money)
        return money
    elif coin == 'f':
        money = money + 1.0
        print(money)
        return money
    elif coin == 'g':
        money = money + 0.25
        print(money)
        return money
    elif coin == 'h':
        money = money + .10
        print(money)
        return money
    elif coin == 'j':
        money = money + .05
        print(money)
        return money
    elif coin == 'k':
        money = money + .01
        print(money)
        return money
    elif coin == 'q':
        return 'end'




print('This is a simple calculator to add money easily.')
print('a = 20$, s = $10, d = $5, f = $1, g = a quarter,')
print('h = a dime, j = a nickel, k = a penny.')
print('Hit q to quit.')
print('Hit the key and then enter to add money:')

while True:
    changeCalculator()
    `enter code here`if changeCalculator() != 'end':
        continue

cash = changeCalculator()
print(cash)

Tags: to函数程序addreturnifcashend
1条回答
网友
1楼 · 发布于 2024-04-20 05:30:05

您没有将货币变量存储在任何地方。循环的每次迭代都在调用函数,该函数将coin重置为0.0,并返回钱。把它带到功能之外。还可以使用字典映射键及其值

keymap = {'a': 20,
         's': 10,
         'd': 5,
         'f': 1,
         'g': 0.25,
         'h': 0.1,
         'j': 0.05,
         'k': 0.01}

# Prompt user
print(*("press {} to add ${}".format(k,v) for k,v in keymap.items()),
      "press q to quit the program", sep="\n")

money = 0.
choice = input()
while choice != 'q':
    money += keymap[choice]
    choice = input()

print("Your total is ${}.".format(money))

相关问题 更多 >