if/elif/else statement help with money - python

Updated my new code at the bottom of the page as an answer.
So for my CS 170 class, we have to make a program that has user input for less than $10 and change is returned in the least amount of coins, no bills or 50 cent pieces. For the most part the program does well except when you run into a x.x0
e.g.:
Python 2.7.2 (v2.7.2:8527427914a2, Jun 11 2011, 15:22:34)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "copyright", "credits" or "license()" for more information.
>>> ================================ RESTART ================================
>>>
Amount due:
7.80
Amount in return
2.20.
Quaters in return 8.
Dimes in return 0.
Nickels in return 4.
>>>
the program completely skips over the dimes section and straight to nickels providing 4 as a solution when the least amount should be 8 quarters, 2 dimes and end. Also I'm not really skilled in loops too much, but I know this would be possible and a lot shorter code, and cleaning up the code advice would be nice as well. Thanks for any help!
# optional.py
# Calculating the least amount of change in return for a $10 bill.
## amount due
due = input("Amount due:\n ")
## if amount is more than 10, exit program
if due > 10.00:
print "Please enter a number lower then 10.00."
exit()
## if amount is less than 0, exit program
if due < 0:
print "Please enter a number greater than 0.00."
exit()
## subtract amount from 10
else:
change = 10.00 - due
print "Amount in return\n %0.2f." % change
## if amount is 0, no change
if change == 0:
print "No change in return."
## passes expression if previous not met
pass
elif change >= .25:
## setting q, dividing change by .25
q = change / .25
## maaking q an integer
quaters = int(q)
print "Quaters in return %r." % quaters
## subtracting quaters from chane
change = change - (quaters *.25)
if change < .10:
pass
elif change >= .10 <= .24:
d = change * .1
dimes = int(d)
print "Dimes in return %r." % dimes
change = change - (dimes * .1)
if change < .05:
pass
elif change >=.05 <=.09:
n = change / .05
nickels = int(n)
print "Nickels in return %r." % nickels
change = change - (nickels * .05)
if change == .01:
pennies = change / .01
print "Pennies in return %r." % pennies
elif change >=.01 <=.04:
p = change / .01
print "Pennies in return %0.0f." % p

There are a few changes you could make to clean up this code, and one of them might fix your problem. First, pass does absolutely nothing. It is usually used as a placeholder for a loop or function that will be filled in later. Also, the conditions of your elif statements are mutually exclusive with the if statements they follow, so
if change == 0:
print "No change in return."
## passes expression if previous not met
pass
elif change >= .25:
## setting q, dividing change by .25
q = change / .25
## maaking q an integer
quaters = int(q)
print "Quaters in return %r." % quaters
## subtracting quaters from chane
change = change - (quaters *.25)
can be rewritten as
if change >= .25:
## setting q, dividing change by .25
q = change / .25
## making q an integer
quaters = int(q)
print "Quaters in return %r." % quaters
## subtracting quaters from change
change = change - (quaters *.25)
for each if/elif statement. Also, in the statement
if change >=.01 <=.04:
you are testing whether
change >= .01 and .01 <= .04
To make it do what you want, the statement should be rewritten as
if .01 <= change <= .04
In addition, you are using floating point numbers, which often lead to rounding errors. To avoid these errors, I would suggest either representing your money as an integer number of cents and multiply all of the numbers in your problem by 100 or use something with fixed point numbers like python's decimal module.

This is not doing what you expect:
elif change >= .10 <= .24:
It looks like you intend something like:
elif change >= .10 and change <= .24:
or Python also supports:
elif .10 <= change <= .24:
However, you will next run into floating point rounding problems of various kinds. I suggest you first convert the input number to an integer number of cents, and perform all your calculations in cents. Avoid floating point numbers when dealing with money.

So I got it worked out in a better format with cleaner print code. Thanks for the help guys!
If anyone wants to know the difference between the 2 codes, it's getting it out of floating point like the others suggested and converting what is needed to integers, multiplying the integers by the specific amount, say a quarter, and then subtracting int * coin/bill from the change. Worked out well. I tried experimenting with a for statement, but that didn't turn out too well since I don't know a lot about it yet either. Until next time...
Again thanks guys!
Here's the finished code for anyone wondering about it:
import sys
due = input("Please enter the amount due on the item(s):\n ")
# if over $10, exit
if due > 10:
print "Please enter an amount lower then 10."
sys.exit(1)
## if under/equal 0, exit
if due <= 0:
print "Please enter an amount greater than 0."
sys.exit(2)
## 10 - due = change, converts change into cents by * by 100 (100 pennies per dollar)
else :
change = 1000 - (due * 100)
## if change is 0, done
if change == 0:
print "No change in return!"
## if not 0 makes change2 for amount in return
else:
change2 = change / 100
print "Amount in return:\n $%.2f." % change2
## if change > 500, subract 500 and you get 1 $5 bill
if 500.0 <= change:
bill_5 = change / 500
b5 = int(bill_5)
change = change - 500
## if change is over 100, change divided by 100 and subtracted from change for quaters
if 100.0 <= change:
dollars = change / 100
dollar = int(dollars)
change = change - (dollar * 100)
if 25 <= change < 100:
quaters = change / 25
quater = int(quaters)
change = change - (quater * 25)
if 10 <= change <= 24:
dimes = change / 10
dime = int(dimes)
change = change - (dime * 10)
if 5 <= change < 10:
nickels = change / 5
nickel = int(nickels)
change = change - (nickel * 5)
if 0 < change < 5:
pennies = change / 1
penny = int(pennies)
change = change - (penny * 1)
print "Change in return:\n $5:%i\n $1:%i\n Quaters:%i\n Dimes:%i\n Nickels:%i\n Pennies:%i " % (
b5, dollar, quater, dime, nickel, penny )
if 0 >= change:
print "Done!"

Related

Figuring out money change in python

I have an assignment where I have to prompt the user for cost of a product and amount paid, I have to output change in pennies, dimes, quarters, $1, $5, $20, $50, and $100, for example: The cost of the item is $19.99 and the client pays with a $50 bill. The change to be provided is 1 $20 bill, one $10 bill, and one penny.
I am confused how to get an output like that though, any help would be greatly appreciated, heres what I have so far
cost = float(input('Cost: '))
amount_paid = float(input('Amount paid: '))
penny = 0.01
dime = 0.10
quarter = 0.25
dollar_1 = 1.00
dollar_5 = 5.00
dollar_10 = 10.00
dollar_20 = 20.00
dollar_50 = 50.00
dollar_100 = 100.00
change = cost - amount_paid
if amount_paid < cost:
print('Error')
I dont know what to do next
A common misstep here is to use floats. You should instead convert everything to the smallest whole unit (a cent) and use integer math. Floating point math is...fuzzy.
currencies = {"penny": 1,
"nickel": 5,
"dime": 10,
"quarter": 25,
"dollar": 1_00,
"five": 5_00,
"ten": 10_00,
"twenty": 20_00,
"fifty": 50_00,
"hundred": 100_00}
# never seen that numeric notation before? It's safe to embed underscores
# in numerical literals! It's often used for large numbers in place of
# commas, but it makes sense here in place of a period.
Then you should only need to define a dictionary for the result, and use divmod to find how many of the denomination can fit in the amount left due.
change_due = {}
for denomination, amt in reversed(currencies.items()):
if amt < amt_due:
d, m = divmod(amt_due, amt)
change_due[denomination] = d
amt_due = m
welcome to stackoverflow! I wrote the code for you and this is how it works. Basically it sees each currency and uses integer division // to see how many integers can fit in. It then subtracts that amount from the remaining change and the process continues. Please ask if you don't understand something, or if you think there is an error.
Code:
cost = float(input('Cost: '))
amount_paid = float(input('Amount paid: '))
penny = 0.01
dime = 0.10
quarter = 0.25
dollar_1 = 1.00
dollar_5 = 5.00
dollar_10 = 10.00
dollar_20 = 20.00
dollar_50 = 50.00
dollar_100 = 100.00
changeTypes = {dollar_100:0,dollar_50:0,dollar_20:0,dollar_10:0,dollar_5:0,dollar_1:0,quarter:0,dime:0,penny:0}
change = amount_paid-cost
if amount_paid < cost:
print('Error: InsufficientFunds')
for changeType in changeTypes:
numAmount = max(0,change//changeType)
change-=numAmount*changeType
changeTypes[changeType] = int(numAmount)
print(changeTypes)
P.S you should make this a function, it shouldn't be too hard.
You could do this good with dictionaries, but without using still there are many ways to go about this, options are endless, heres one idea
def get_bills(change, value):
if change//value > 0:
bills = change//value
change -= bills * value
return bills, change
else:
return 0, change
cost = float(input('Cost: '))
paid = float(input('Amount Paid: '))
while paid < cost:
paid = float(input('Amount Paid: '))
change = paid - cost
hundreds, change, = get_bills(change, 100)
fifties, change, = get_bills(change, 50)
twenties, change = get_bills(change, 20)
tens, change = get_bills(change, 10)
fives, change = get_bills(change, 5)
ones, change = get_bills(change, 1)
quarters, change = get_bills(change, .25)
dimes, change = get_bills(change, .1)
nickels, change = get_bills(change, .05)
pennies = round(change * 100)
print(f"Hundreds: {hundreds}, Fifties: {fifties}, Twenties: {twenties}," +
f" Tens: {tens}, Fives: {fives}, Ones: {ones}, Quarters: {quarters}," +
f" Dimes: {dimes}, Nickels: {nickels}, Pennies: " +
f"{pennies}")
bill = float(input())
paid = float(input())
Available = {100.0:0,50.0:0,20.0:0,10.0:0,5.0:0,1.0:0,0.25:0,0.10:0,0.01:0}
due = paid-bill
for change in sorted(Available,reverse = True):
amt= max(0,due//change)
due-=amt*change
Available[change] = int(amt)
print(Available)
I know this is a late response but maybe it can help someone.
Below is a code for doing exactly what you want. The program iterates through the notes available from largest to smallest and calculates how many times the current note may be used to deduct from the remaining change to be given.
Finally returning a list containing the notes used to reach the sum required.
# Available notes for change
notes = [500, 200, 100, 50, 20, 10]
def change_notes(change, notes):
notes_out = []
for note in notes:
print(f"current note is {note}")
sleep(1)
while change > 0 and note <= change:
if change - note >= 0:
change -= note
notes_out.append(note)
print(f"change is {change}")
sleep(1)
if change == 0:
break
return notes_out

Change calculator only works if one type of coin needed

I'm currently trying to learn python and have been going through beginner projects on /r/learnpython. My idea for the change calculator project was to create a dictionary with keys 'quarter', 'dime', 'nickel', and 'penny', each with values initialized to 0. My code, shown below, appears to only work when the change I input only requires one type of coin, i.e. 0.75 --> 3 quarters, 0.1 --> 1 dime, etc.
change_map = {
'quarter' : 0,
'dime' : 0,
'nickel' : 0,
'penny' : 0
}
def calculator(change):
while change > 0:
if change >= 0.25:
change -= 0.25
change_map['quarter'] += 1
elif change < 0.25 and change >= 0.10:
change -= 0.10
change_map['dime'] += 1
elif change < 0.10 and change >= 0.05:
change -= 0.05
change_map['nickel'] += 1
elif change < 0.05 and change >= 0.01:
change -= 0.01
change_map['penny'] += 1
print "You need the following: "
print change_map
change = raw_input("Please enter amount of change: ")
change = float(change)
calculator(change)
Floating point arithmetic error
Your error is due to float arithmetic error. Here is what happens when you input a value such as 0.26.
change = 0.26
change -= 0.25
change -= 0.01
print (change) # 8.673617379884035e-18
Since the last value of change is above 0 but below 0.01, you enter an infinite loop.
How to fix it
One way to fix this is to rely on exact arithmetic by using int instead of float to represent discrete values such as currencies. This means making your base unit the cent instead of the dollar.
change_map = {
'quarter' : 0,
'dime' : 0,
'nickel' : 0,
'penny' : 0
}
def calculator(change):
while change > 0:
if change >= 25:
change -= 25
change_map['quarter'] += 1
elif change >= 10:
change -= 10
change_map['dime'] += 1
elif change >= 5:
change -= 5
change_map['nickel'] += 1
else:
change -= 1
change_map['penny'] += 1
print ("You need the following: ")
print (change_map)
change = raw_input("Please enter amount of change: ")
# Here we convert the decimal value input by the user to cents
change = int(float(change) * 100)
calculator(change)
Example:
Please enter amount of change: 0.26
You need the following:
{'quarter': 1, 'dime': 0, 'nickel': 0, 'penny': 1}
Improvements
On a side note, you can improve your solution by using a dict of values and names for coins. In particular, this allows you to extend your program by updating the dict instead of having to add a new if-statement.
Here is an example that adds in the possibility to return a dollar as change.
value_map = {
100: 'dollar',
25: 'quarter',
10: 'dime',
5: 'nickel',
1: 'penny'
}
def calculator(change):
change_map = {}
for value in sorted(value_map, reverse=True):
coin = value_map[value]
change_map[coin], change = divmod(change, value)
print ("You need the following: ")
print (change_map)
change = raw_input("Please enter amount of change: ")
change = int(float(change) * 100)
calculator(change)
I debugged your code and noticed that there was an infinite loop. Probably, that because of float arithmetics. You can declare an epsilon value like
eps = 1e-2
And change the while loop respectively
while change > eps

in python, i have an int and want to substract it from a list

In python: how do I divide an int received by a user from a list while every time it runs in the for loop I need to divide the value I received from the round before in the next round?
This is my code:
a = input('price: ')
b = input('cash paid: ')
coin_bills = [100, 50, 20, 10, 5, 1, 0.5]
if b >= a:
for i in coin_bills:
hef = b - a
print (hef / i), '*', i
else:
print 'pay up!'
Example: a=370 b=500 ---> b-a=130
Now in the loop I will receive (when i=100) 1, and (when i=50) I will receive 2 but I want in the second round (when i=50) to divide 30 (130[=b-a]- 100[=answer of round 1*i]) by 50.
What do I need to change in the code?
Thanks!
You just need to subtract the amount of change you give back at each step from the total amount of change you're returning. It's much easier to see if you change your variable names to something meaningful:
price= int(raw_input('price: ')) # Use int(raw_input()) for safety.
paid= int(raw_input('cash paid: '))
coin_bills=[100,50,20,10,5,1,0.5]
if paid >= price:
change = paid - price
for i in coin_bills:
# Use // to force integer division - not needed in Py2, but good practice
# This means you can't give change in a size less than the smallest coin!
print (change // i),'*',i
change -= (change // i) * i # Subtract what you returned from the total change.
else:
print 'pay up!'
You could also clear up the output a bit by only printing the coins/bills that you actually return. Then the inner loop might look something like this:
for i in coin_bills:
coins_or_bills_returned = change // i
if coins_or_bills_returned: # Only print if there's something worth saying.
print coins_or_bills_returned,'*',i
change -= coins_or_bills_returned * i
OK, I'm assuming that you're trying to calculate change for a transaction using a number of types of bills.
The problem is that you need to keep a running tally of how much change you have left to pay out. I used num_curr_bill to calculate how many of the current bill type you're paying out, and your hef I changed to remaining_change (so it would mean something to me) for the remaining change to pay.
a= input('price: ')
b= input('cash paid: ')
coin_bills=[100,50,20,10,5,1,0.5]
if b>=a:
# Calculate total change to pay out, ONCE (so not in the loop)
remaining_change = b-a
for i in coin_bills:
# Find the number of the current bill to pay out
num_curr_bill = remaining_change/i
# Subtract how much you paid out with the current bill from the remaining change
remaining_change -= num_curr_bill * i
# Print the result for the current bill.
print num_curr_bill,'*',i
else:
print 'pay up!'
So, for a price of 120 and cash paid 175, the output is:
price: 120
cash paid: 175
0 * 100
1 * 50
0 * 20
0 * 10
1 * 5
0 * 1
0.0 * 0.5
One bill for 50 and one for 5 add up to 55, the correct change.
Edit: I'd go more sparingly on the comments in my own code, but I added them here for explanation so that you could more clearly see what my thought process was.
Edit 2: I would consider removing the 0.5 in coin_bills and replacing 1 with 1.0, since any fractional amounts will wind up being fractions of 0.5 anyway.

Python-Modulus-Stuck with a coin-for-given-dollar-amount scenario

Specs: Ubuntu 13.04, Python 3.3.1
General Background: total beginner to Python;
Question-specific background: I'm exhausted trying to solve this problem, and I'm aware that, besides its instructional value for learning Python, this problem is boring and does not in any way make this world a better place :-( So I'd be even more grateful if you could share some guidance on this exhausting problem. But really don't want to waste your time if you are not interested in this kind of problems.
What I intended to do: "Calculate the number of basic American coins given a value less than 1 dollar. A penny is worth 1 cent, a nickel is worth 5 cents, a dime is worth 10 cents,
and a quarter is worth 25 cents. It takes 100 cents to make 1 dollar. So given an amount less than 1 dollar (if using floats, convert to integers for this exercise), calculate the number of each type of coin necessary to achieve the amount, maximizing the number of larger denomination coins. For example, given $0.76, or 76 cents, the correct output would be "3 quarters and 1 penny." Output such as "76 pennies" and "2 quarters, 2 dimes, 1 nickel, and 1 penny" are not acceptable."
What I was able to come up with:
penny = 1
nickel = 5
dime = 10
quarter = 25
i = input("Please enter an amount no more than 1 dollar(in cents): ")
i = int(i)
if i > 100:
print ("Please enter an amount equal or less than 100. ")
elif i >= quarter:
quarter_n = i % quarter
i = i - quarter * quarter_n
if i >= dime:
dime_n = i % dime
i = i - dime * dime_n
if i >= nickel:
nickel_n = i % nickel
i = i - nickel * nickel_n
if i >= penny:
penny_n = i % penny
print (quarter_n,"quarters,",dime_n,"dimes",nickel_n,"nickels",penny_n,"pennies")
else:
if i >= penny:
penny_n = i % penny
print (quarter_n,"quarters,",dime_n,"dimes",penny_n,"pennies")
else:
if i >= nickel:
nickel_n = i % nickel
i = i - nickel * nickel_n
if i >= penny:
penny_n = i % penny
print (quarter_n,"quarters,",nickel_n,"nickels",penny_n,"pennies")
else:
if i >= penny:
penny_n = i % penny
print (quarter_n,"quarters,",penny_n,"pennies")
else:
if i >= dime:
dime_n = i % dime
i = i - dime * dime_n
if i >= nickel:
nickel_n = i % nickel
i = i - nickel * nickel_n
if i >= penny:
penny_n = i % penny
print (dime_n,"dimes",nickel_n,"nickels",penny_n,"pennies")
else:
if i >= penny:
penny_n = i % penny
print (dime_n,"dimes",penny_n,"pennies")
else:
if i >= nickel:
nickel_n = i % nickel
i = i - nickel * nickel_n
if i >= penny:
penny_n = i % penny
print (nickel_n,"nickels",penny_n,"pennies")
else:
if i >= penny:
penny_n = i % penny
print (penny_n,"pennies")
This solution, though the best I could come up with, does not work as expected when fed with actual input numbers. And I'm unable to figure out why. Besides, I know that even from sheer size of the code that something is wrong. I searched for similar questions but the closest I got was one that dealt with very difficult math which I couldn't understand.
My question: I know I can't ask for a complete solution because that's down to me to figure it out. I'll appreciate either a) general pointer on the correct line of thinking b) critiques to my current code/line of thinking so that I might be able to improve it.
Thank you for taking the time, even just reading this!
I think your solution may actually be working if you do a "find and replace" for all the mod operators %, switching in integer division //.
Say you have 76 cents and want to find the number of quarters. Using 76 % 25 results in 1 whereas 76 // 25 is 3.
With regard to the code, you should probably be thinking in terms of iterating over the possible coin values rather than a huge if, elif mess.
Try something like this. The only part that may need some explaining is using divmod but its really just a tuple of the integer division, modulo result. You can use that to get the number of coins and the new amount, respectively.
def coins_given(amount):
coins = [(25, 'quarter'), (10, 'dime'), (5, 'nickel'), (1, 'penny')]
answer = {}
for coin_value, coin_name in coins:
if amount >= coin_value:
number_coin, amount = divmod(amount, coin_value)
answer[coin_name] = number_coin
return answer
print coins_given(76)
# {'quarter': 3, 'penny': 1}
i think your algorithm is too complicated,
you don't need all the elifs and the elses
just check with and if and then modidy the remaining amount until you get to zero
something like this
penny = 1
nickel = 5
dime = 10
quarter = 25
q = 0
d = 0
n = 0
p = 0
i = input("Please enter an amount no more than 1 dollar(in cents): ")
i = int(i)
if i>=25:
q = i/quarter
i %= quarter
if i>=10:
d = i/dime
i%=dime
if i>=5:
n = i/nickel
i %= nickel
if i>0:
p = i/penny
i = 0
print "The coins are %i quarters, %i dimes, %i nickels and %i pennys." %(q , d, n, p)
>>>
Please enter an amount no more than 1 dollar(in cents): 99
The coins are 3 quarters, 2 dimes, 0 nickels and 4 pennys.
>>>
Please enter an amount no more than 1 dollar(in cents): 76
The coins are 3 quarters, 0 dimes, 0 nickels and 1 pennys.
dime=10
nickel=5
penny=1
quarter=25
def change(cents):
changeIs = ""
qs = cents/quarter
cents %= quarter
if qs > 0 :
changeIs += str(qs) + " quarter(s)"
ds = cents/dime
cents %= dime
if ds > 0 :
changeIs += " " + str(ds) + " dime(s)"
ns = cents/nickel
cents %= nickel
if ns > 0 :
changeIs += " " + str(ns) + " nickel(s)"
if cents > 0 :
changeIs += " " + str(cents) + " cent(s)"
return changeIs
if __name__ == '__main__':
cents=int(raw_input("Enter the change: "))
print change(cents)

Rounding up with pennies in Python?

I am making a change program in python. The user must input a dollar amount and then the program will calculate the change in twenties, tens, fives, ones, quarters, dimes, nickels, and pennies. I was instructed to use the round function for the pennies because If I input an amount of $58.79, the program tells me to give 3 pennies back when it should be 4. Is there a way to round up these pennies?
I know the value of a penny is .01, but python reads this as .100000000001 which I believe is the problem.
Any help is appreciated, here is the section I need rounded:
# get the amount to change from the user
change = input("Please enter the amount to change: $")
print "To make change for $",change,"give the customer back:"
# calculate number of twenties
twenties = int(change/ 20)
print twenties, "twenties"
change = change - twenties *20
# calculate tens
tens = int(change / 10)
print tens, "tens"
change = change - tens *10
#calculate fives
fives = int(change / 5)
print fives, "fives"
change = change - fives *5
#calculate ones
ones = int(change / 1)
print ones, "ones"
change = change - ones * 1
#calculate quarters
quarters = int(change / .25)
print quarters, "quarters"
change = change - quarters * .25
#calculate dimes
dimes = int(change / .10)
print dimes, "dimes"
change = change - dimes * .10
#calculate nickels
nickels = int(change / .05)
print nickels, "nickels"
change = change - nickels * .05
#calculate pennies
pennies = int(change / .01)
print pennies, "pennies"
Multiply the user's inputed dollar value by 100, convert to int, and work in units of pennies.
Integer arithmetic is dead simple (and exact). Floating point arithmetic is tricky and forces you to use more brain cells :) . Save brain cells and work entirely in ints.
The problem is that 0.01 cannot be accurately represented as a binary floating point value (which is how normal floats are stored – this is true for any language, not just Python). So if you need exact values for dollars and cents, you can use the decimal module. That way you can be sure that your values will be rounded exactly.
Or (since Decimals might be overkill here), first multiply every dollar value by 100 (this is not the same as dividing by 0.01 for the above reasons!), convert to int, do your calculations, and divide by 100.
The problems you are having are a result of imprecise floating-point arithmetic. There is no way to precisely represent 0.01 in IEEE floating point. That is one reason not to use floats when working with currency.
You should use decimals or even integers, because you know there are at most 2 digits after the decimal point. In that case, just work with the amount in pennies.
On the problem itself, I think the easiest way to do it is convert your amount in dollars to the amount in pennies, then iterate through a predefined list of values containing listing the equivalent amount of pennies (in descending order) for each denomination:
def change(amount):
# this can be removed if you pass the amount in pennies
# rather than dollars
amount = int(round(amount*100))
values = [2000, 1000, 500, 100, 25, 10, 5, 1]
denom = ['twenties', 'tens', 'fives', 'ones', 'quarters', 'dimes', 'nickels', 'pennies']
for i in range(len(values)):
num = amount / values[i]
amount -= num * values[i]
print str(num) + " " + denom[i]
Now calling change(58.79) will print
2 twenties
1 tens
1 fives
3 ones
3 quarters
0 dimes
0 nickels
4 pennies
As seen on codepad.org
use the decimal package
http://docs.python.org/library/decimal.html
it is meant exactly for this kind of use case
>>> from math import ceil
>>> a = 58.79
>>> ceil(a % 0.05 * 100)
4.0
>>>
[edit]
Now that I think of it, might aswell just go with
>>> a = 58.79
>>> a*100 % 5
4.0

Categories

Resources