I'm a newbie and taking an online python class through an online workbook. I can't seem to figure out how to get the output to display like the example shown:
Problem instructions:
Write a function number_of_pennies() that returns the total number of pennies given a number of dollars and (optionally) a number of pennies. Ex: 5 dollars and 6 pennies returns 506.
Here is what I have:
def number_of_pennies(dollars = (),pennies=())
return number_of_pennies
print(number_of_pennies(5, 6)) # Should print 506
print(number_of_pennies(4)) # Should print 400
Thanks to your help I just changed it to this:
def number_of_pennies(dollars = 0,pennies=0):
number_of_pennies= (dollars * 100) + pennies
return number_of_pennies
print(number_of_pennies(5, 6)) # Should print 506
print(number_of_pennies(4)) # Should print 400
Default arguments are used when the caller doesn't supply a value. So, what should be the default? In your case, if the user doesn't supply dollars, zero dollars seems like a reasonable choice. Same with pennies. Since number_of_pennies(4) should be 400 you know that they want dollars to be the first parameter. The remainder is just the math.
number_of_pennies is just the name of the function which would be an odd thing to return. In fact, when you try it you get something like <function number_of_pennies at 0x7ff4e962d488> which means that the function returned its own function object. Instead return the data you calculate... that's much more useful!
>>> def number_of_pennies(dollars=0, pennies=0):
... return dollars * 100 + pennies
...
>>> print(number_of_pennies(5,6))
506
>>> print(number_of_pennies(4))
400
def number_of_pennies(dollars = 0, pennies = 0):
return dollars * 100 + pennies
print(number_of_pennies(int(input()), int(input()))) # Both dollars and pennies
print(number_of_pennies(int(input()))) # Dollars only
def number_of_pennies(n,x=0):
return n*100+x
I did the same workbork. This is what I came up with:
def number_of_pennies(dollars=0, pennies=0):
dollars = dollars * 100
pennies = pennies
total = dollars + pennies
return total
print(number_of_pennies(int(input()), int(input()))) # Both dollars and pennies
print(number_of_pennies(int(input()))) # Dollars only
Related
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
i am tasked to make a program that will take a monetary amount and find the minimum number of coins needed to get that amount. here is my code.
import math
n1 = eval(input("Enter a monetary amount: "))
n1 = n1 * 100
dollars = 0
quarters = 0
dimes = 0
nickels = 0
pennies = 0
dollars = n1 / 100
n1 %= 100
quarters = n1 / 25
n1 %= 25
dimes = n1 / 10
n1 %= 10
nickels = n1 / 5
n1 %= 5
pennies = n1
print (int(dollars), int(quarters), int(dimes), int(nickels), int(pennies))
whenever I enter a number that needs nickels, it doesn't count them. for example, the output for 1.05 would be
1 0 0 0 0
the output for 1.15 is
1 0 1 0 4
any hints would be appreciated, thanks.
edited a typo that i had, code is still not working as intended though.
You're running into a floating point issues:
>>>> 1.15*100
114.99999999999999
As you can see, here you clearly do not have 115 cents. You have just under that. So you use one dollar, one dime, and 4.99999 pennies (int rounds it down to four).
The easiest way to fix it is to have the user give you an integer number of cents so that you can work in cents the entire time, or to use the built-in round function to get rid of floating point errors.
You can refer to Is floating point math broken? for a more comprehensive explanation on what is going on but basically when you type 1.05 into your code (or through an eval) it does not store the exact value you might expect:
>>> (1.05).as_integer_ratio()
(4728779608739021, 4503599627370496)
If you want the computer to store the exact decimal representation of the number you can simply use decimal.Decimal for the intermediate step:
n1 = decimal.Decimal(input("Enter a monetary amount: "))
n1 = int(n1 * 100) #now you won't get rounding issues
alternately you can parse the number entered yourself to remove the decimal and skip the math required to compensate all togther:
def dollar_to_cent(s):
n,_,end = s.partition(".")
if not all(i=="0" for i in end[2:]):
raise ValueError("can only have up to two digits after decimal.")
return int("{}{:0<2}".format(n,end[:2]))
>>> dollar_to_cent("1")
100
>>> dollar_to_cent("2.")
200
>>> dollar_to_cent("2.3")
230
>>> dollar_to_cent("2.05")
205
>>> dollar_to_cent("2.050000")
205
>>> dollar_to_cent("2.001")
Traceback (most recent call last):
...
ValueError: can only have up to two digits after decimal.
Looks like a typo: nickels vs nickles
Edit: now that you've fixed the typo, it looks like it's definitely a rounding issue. Since you're converting from dollars to a whole number of cents, try turning it into an integer before doing any operations.
Change your n1 = n1 * 100 line to n1 = int(round(n1 * 100)). I tried this out on my computer and it seemed to work.
It is best to work with cents all the way for these kind of problems. Try to make 105 cents (integer) instead of 1.05 times 100. You can avoid rounding all together. Further, since you care about "remainder", use modulo operator instead of division.
I'd solve it like this:
cents = 115
remainder = cents%25
nickels = (cents - remainder)/25
cents = remainder
remainder = cents%10
dimes = (cents - remainder)/10
...
and so on.
However, probably not the question you asked but in general cases this problem is NP-hard, and further depending on the coin denominations some change is not makeable.
I'm using Python, and I am trying to convert a certain amount of money in cents to its equivalent in quarters, nickels, dimes and pennies.
This is what I have so far, but I see the problem is that I don't know how to take the remainder from the quarters and break it down into dimes, nickels and pennies. I'm new to this and just having a hard time. I'm not asking for someone to solve the problem, just point out what I did wrong (and maybe what I need to do to fix it).
# Convert some money to an appropriate collection of cents
penny = 1
nickel = 5
dime = 10
quarter = 25
quarters = 0
dimes = 0
nickels = 0
pennys = 0
cents = int(input("Please enter an amount of money you have in cents: "))
if cents >= 25:
quarters = cents / quarter
cents % quarter
if cents >= 10:
dimes = cents/dime
cents % dime
if cents >= 5:
nickels = cents /nickel
cents % nickel
if cents > 0:
pennys = cents / penny
cents = 0
print ("The coins are: quarters", quarters,\
",dimes", dimes, ",nickels", nickels, ", and pennys.", pennys)
Using divmod, it's just three lines:
quarters, cents = divmod(cents, 25)
dimes, cents = divmod(cents, 10)
nickels, pennies = divmod(cents, 5)
There are two operations that you need here: integer division and modulo.
Integer division A / B asks a simple question: How many times will B fit into A cleanly (without having to break B into decimal pieces)? 2 fits into 8 cleanly 4 times. 2 fits into 9 cleanly 4 times as well.
Modulo A % B asks the same question but gives the flip-side of the answer: Given that A goes into B cleanly some number of times, what's left over? 2 goes into 8 cleanly 4 times with nothing left over, so 2 % 8 is 0. 2 goes into 9 cleanly 4 times but 1 is left over, so 2 % 9 is 1.
I'll give you another example, and let you make the transition from that to your problem. Let's say I'm given a number of seconds, and I need to convert it to days, hours, minutes and seconds.
total_seconds = 345169
# Specify conversion between seconds and minutes, hours and days
seconds_per_minute = 60
seconds_per_hour = 3600 # (60 * 60)
seconds_per_day = 86400 # (3600 * 24)
# First, we pull out the day-sized chunks of seconds from the total
# number of seconds
days = total_seconds / seconds_per_day
# days = total_seconds // seconds_per_day # Python3
# Then we use the modulo (or remainder) operation to get the number of
# seconds left over after removing the day-sized chunks
seconds_left_over = total_seconds % seconds_per_day
# Next we pull out the hour-sized chunks of seconds from the number of
# seconds left over from removing the day-sized chunks
hours = seconds_left_over / seconds_per_hour
# hours = seconds // seconds_per_hour # Python3
# Use modulo to find out how many seconds are left after pulling out
# hours
seconds_left_over = seconds_left_over % seconds_per_hour
# Pull out the minute-sized chunks
minutes = seconds_left_over / seconds_per_minute
# minutes = seconds_left_over // seconds_per_minute # Python3
# Find out how many seconds are left
seconds_left_over = seconds_left_over % seconds_per_minute
# Because we've removed all the days, hours and minutes, all we have
# left over are seconds
seconds = seconds_left_over
Was struggling with this yesterday evening. True, you need division and modulo. Not the most Pythonic way, but it works for any amount, when you restrict the amount of dollars you can input into the vending machine to $5.00. This question has been asked around and has been continually ignored. Maybe because it is homeworksque... Anyway....
def vending_machine_change():
cost = float(input("Enter cost of item: "))
change= 5.00-cost
dollars = int(change)
quarters_change= float("%.2f" % ((change-dollars)))
quarters =int(quarters_change/0.25)
dime_change= float("%.2f" % (quarters_change%0.25))
dimes=int(dime_change/0.10)
nickel_change = float("%.2f" % (dime_change%0.10))
nickels= int(nickel_change/0.05)
pennys = int(nickel_change*100)
print("Change amount: " + str((dollars)) + ' Dollars, ' + str((quarters)) + ' Quarters, '+ str((dimes)) + ' Dimes, '+ str((nickels)) + ' Nickels, '+ str((pennys)) + ' Pennies' )
pass
Hi Can you please refer to below sample code and let me know what is the exact difference between round and int functions
OUTPUT:
12 dollars and 0 cents
12 dollars and 1.0 cents
# code is to convert xx.yy to xx dollars and yy cents **
val = 12.01
dollars = int(val) #Integer value to know how many Dollars
cents = int(100 * (val - dollars)) #Integer value to know how many cents
print str(dollars) + " dollars and " + str(cents) + " cents"
If i write the same code with round function, I am getting right answer
val = 12.01
dollars = int(val) #Integer value to know how many Dollars
cents = round(100 * (val - dollars)) #Integer value to know how many cents
print str(dollars) + " dollars and " + str(cents) + " cents"
Not sure why it is shown as 0 cents when i use int.
You are using float values, they do not map cleanly to decimal values.
If you try something like:
floatcents = 100 * (val - dollars)
cents = int(floatcents)
print floatcents
print cents
You may well end up with floatcents being something like 0.999999999789 and that, truncated to an integer value, becomes 0 instead of 1.
You may be better off using int((100*val) - (100*dollars)) or simply use an integral value of cents instead of having a float value of dollars.
an integer is a whole number
and a float is a number with decimal points
that's the layman's terms of it
int() gets rid of any decimal points. You should instead use:
cents = float(100 * (val - dollars)) #Integer value to know how many cents
explanation:
The following code treats everything as an integer, so (val - dollars) will give you 0 instead of 0.1 therefore multiplying by 100 will still give you 0.
int(100 * (val - dollars))
Assuming val is the result of some calculation and might be for example
val=12.996
You should actually round the dollar result as well:
dollar = round(val*100)/100
cents = round(val*100)-dollar*100
-> $13 + 0 cents , not $12 + 100 cents...
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