Kris Kris - 1 month ago 11
Python Question

How do I suppress printing under certain circumstances in python?

I have written following code in python for a simulation of an 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)


If I type in 50 in the beginning, I get following output:

How much do you want to withdraw? 50
Withdrawal: 50 CHF
100 0
50 1
20 0
10 0


I want to change the display, so that in the output it shows only the bills that are being used, which in this case would be only the
50
bill. All bills which aren't used shouldn't be printed. Is there a way to change the output in that direction?

Answer

The solution is obviously to check if a>0:, if b>0: and so on. But what about throwing in a loop, so you don't have to hardcode the conditions for all the bills?

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])

In this example you also store the number of bills in a dictionary if you need also it for further computations

Comments