Python counting through a number with >=

python

Solution

For currency calculations it's best to avoid `float` type if you can, because of accumulating rounding errors. You can do it in a way similar to this:

amount= input("Bitte gib einen Euro Betrag ein: ")
coins = []
cents = [2000, 1000, 500, 200, 100, 50, 20, 10, 5, 2, 1]
amount = int(float(amount) * 100)
for cent in cents:
    while amount >= cent:
        amount -= cent
        coins.append(cent)

print [coin / 100.0 for coin in coins]

I've also changed the variable name from `sum` to `amount` - `sum` will shadow the `sum` built-in function.

Result:

Bitte gebe einen Euro Betrag ein: 17.79
[10.0, 5.0, 2.0, 0.5, 0.2, 0.05, 0.02, 0.02]

Alternatively, you can implement this without inner `while` loop, like this:

for cent in cents:
    n = int(math.floor(amount / cent))
    amount -= n * cent
    coins += [cent] * n

It's possible to exit loop earlier (`if not amount: break`) and avoid unnecessary operations (`if not n: continue`), but I omitted these guards for readability.

Another possible alternative is to use the `decimal` data type.

Problem

I'm learning Python(2.7) at the moment, and an exercise says to write a program which counts how many coins you need to pay a specific sum. My solution is this: ``` sum = input("Bitte gebe einen Euro Betrag ein: ") coins = [] euro = [20,10,5,2,1,0.5,0.2,0.1,0.05,0.02,0.01] for i in euro: while sum >= i: sum -= i coins.append(i) print coins ``` This is nearly working, but when I input e.g. 17,79 it gives me the coins for 17,78. ``` Bitte gebe einen Euro Betrag ein: 17.79 [10, 5, 2, 0.5, 0.2, 0.05, 0.02, 0.01] ``` Why? Has this something to do with round?

Original source