Q:

Python: change calculator

I am trying to calculate the number of quarters, dimes and nickles needed to sum to an amount of change with the least coins possible. Here is my code: 
x = raw_input("Please enter an amount of change")
x = float(x)
q = .25
d = .1
n = .05
numberQ = x/q
numberQ = int(numberQ)
money2 = x - (numberQ * q)
numberD = money2/d
numberD = int(numberD)
money3 = money2 - (numberD * d)
numberN = money3/n
numberN = int(numberN)
print numberQ
print numberD
print numberN

The output is off. For example, if I enter 1.95 it will return 7 quarters, 1 dime and 1 nickel when it should be 7 quarters 2 dimes and 0 nickels.

A:

The problem is in the second step. If you start with 1.95, step one returns 7 quarters with a remainder of $0.20. So money2 is now 0.20. Now we divide by the value of a dime. Because of floating point error our result is likely not an even 2 but more like 1.9999999. Python 2.7's int() method rounds towards zero so this gets rounded to 1 dime. The remainder is $0.10 and this gets divided by the value of a nickle which leads to the same problem but this time it rounds down to one nickle. 
To fix this, I recommend using an integer number of pennies instead of a floating point value representing dollars. 
So, 1.95 becomes 195 and the values of a quarter, a dime, and a nickle are 25, 10, and 5, respectively.
Edit Try this:
x = raw_input("Please enter an amount of change (in pennies)")
x = int(x)
q = 25
d = 10
n = 5
numberQ = (x - (x % q))/q
money2 = x % q
numberD = (money2 - (money2 % d))/d
money3 = money2 % d
numberN = (money3 - (money3 % n))/n
pennies = money3 % n
print numberQ
print numberD
print numberN
print pennies

The % gives the remainder of an integer division. If we subtract the remainder from the amount we started with and divide that by the coin value we know the result will be a whole integer. The remainder becomes the new amount of money.

