我在python中编写了以下代码,用于模拟ATM:
withd = int(input("How much do you want to withdraw? "))
# Withdrawal shown to customer
print("Withdrawal: ", withd, " CHF")
# 100 bills
a = withd // 100
a_rest = withd % 100
# 50 bills
b = a_rest // 50
b_rest = a_rest % 50
# 20 bills
c = b_rest // 20
c_rest = b_rest % 20
# 10 bills
d = c_rest // 10
print("100", a)
print("50", b)
print("20", c)
print("10", d)
如果我在开头输入50,我会得到以下输出:
How much do you want to withdraw? 50
Withdrawal: 50 CHF
100 0
50 1
20 0
10 0
我想更改显示,以便在输出中只显示正在使用的帐单,在这种情况下只会是50
帐单。不应打印所有未使用的帐单。有没有办法改变那个方向的输出?
答案 0 :(得分:0)
解决方案显然是要检查if a>0:
,if b>0:
等等。
但是如何投入循环,所以你不必硬编码所有账单的条件?
withd = int(input("How much do you want to withdraw? "))
# Withdrawal shown to customer
print("Withdrawal: ", withd, " CHF")
bills = [100, 50, 20, 10]
res = {}
rest = withd
for bill in bills:
res[bill] = rest // bill
rest = rest % bill
if res[bill] > 0:
print(bill, res[bill])
在此示例中,如果您还需要进行进一步计算,还可以将字典数存储在字典中