我想在python上添加一个简单的钱添加程序。我试图使它成为函数的第一次迭代changeCalculator()硬币设置为0.0。对于第二次迭代,我想将硬币设置为0.0 +我选择的任何数量。然后,我想要重复该功能,直到用户点击“q”。我的问题是我无法弄清楚如何仅在第一次将硬币设置为0.0,而不是每次迭代都将其设置为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)
答案 0 :(得分:0)
您没有在任何地方存储货币变量。循环的每次迭代都会调用函数,该函数会将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))