I am learning python and I what I need to achieve is to count how many denominations of 1000, 500, 200, 100, 50, 20, 10, 5, 1 , 0.25, 0.01 count base on my input data of 1575.78.This specific code bums me out.
def withdraw_money():
denoms = (1000, 500, 200, 100, 50, 20, 10,5,1,.25,0.01)
while True:
try:
withdraw = 1575.770
break
except Exception as e:
print('Incorrect input: %s' % e)
print("Here is the bill breakdown for the amount input")
for d in denoms:
count = withdraw // d
print('P%i = %i' % (d, count))
withdraw -= count * d
withdraw_money()
My current output is:
Here is the bill breakdown for the amount input
P1000 = 1
P500 = 1
P200 = 0
P100 = 0
P50 = 1
P20 = 1
P10 = 0
P5 = 1
P1 = 0
P0.25 = 3
P0.01 = 2
which is wrong because the P0.01 = 2
is suppose to be P0.01 =3.
However this code is correct when running whole numbers like 1500, or 20 but large number with decimal it get wrong on the 0.01 denomination count.
CodePudding user response:
After debugging the code, I found the error. Using round()
solve the problem.
def withdraw_money():
denoms = (1000, 500, 200, 100, 50, 20, 10,5,1,0.25,0.01)
while True:
try:
withdraw = 1575.77
break
except Exception as e:
print('Incorrect input: %s' % e)
print("Here is the bill breakdown for the amount input")
for i in range(len(denoms)):
if denoms[i] != 0.01: count = withdraw // denoms[i]
else: count = withdraw / denoms[i]
print(f'P{denoms[i]} = {count:0.0f}')
withdraw = round(withdraw % denoms[i],2)
withdraw_money()
CodePudding user response:
You can use f string here like below
def withdraw_money():
denoms = (1000, 500, 200, 100, 50, 20, 10, 5, 1, .25, 0.01)
while True:
try:
withdraw = 1575.770
break
except Exception as e:
print('Incorrect input: %s' % e)
print("Here is the bill breakdown for the amount input")
for d in denoms:
count = withdraw // d
print(f'P{d} = {count:0.0f}')
withdraw -= count * d
withdraw_money()
Output:
Here is the bill breakdown for the amount input
P1000 = 1
P500 = 1
P200 = 0
P100 = 0
P50 = 1
P20 = 1
P10 = 0
P5 = 1
P1 = 0
P0.25 = 3
P0.01 = 1