Search code examples
pythonreceipt

Python - Receipt-like output


Im doing some homework and im breaking my head around this.. either im stupid, or im just way too tired to do this.. I managed to get the output right and prioritized, but when i enter a float number, it will just go crazy.. The overall goal is to be able to enter a float value which will work.. i just can't seem to get my head around a mathematical solution

price = input("Enter Price ")
cash = input("Enter Cash ")
coins = [100, 50, 20, 10, 5, 1, 0.5]
change = cash-price
i = 0
while i<len(coins):
    print int(change/coins[i]),str(" X "),coins[0+i]
    if change>0:
        change = change-((change/coins[i])*coins[i])
    else:
        change = max(change,0)
    i=i+1

Thanks !


Solution

  • I'm too lazy to check the math, but it seems you are forgetting to drop the floating point when subtracting from the change, so a partial coin gets treated like the full current amount and everything zeroes out. I added an int:

    price = input("Enter Price ")
    cash = input("Enter Cash ")
    coins = [100, 50, 20, 10, 5, 1, 0.5]
    change = cash-price
    i = 0
    while i<len(coins):
        print int(change/coins[i]),str(" X "),coins[0+i]
        if change>0:
            change = change-(int(change/coins[i])*coins[i])
        else:
            change = max(change,0)
        i=i+1