I am trying to write a code in Python to where it outputs exact change using the fewest coins and one coin type per line. The coin types are Dollars, Quarters, Dimes, Nickels, and Pennies. I also have to use singular and plural coin names as appropriate, like 1 Penny vs. 2 Pennies. When I input 45 and ran the code, I got an error saying (Your program produced no output). Here is my code:
total_change = int(input())
if total_change <= 0:
print('No change')
if total_change >= 100:
dollar = total_change//100
dollar_change = total_change % 100
if dollar == 1:
print(dollar + ' Dollar')
elif dollar > 1:
print(dollar + ' Dollars')
elif dollar_change >= 25:
quarter = dollar_change//25
quarter_change = dollar_change % 25
if quarter == 1:
print(quarter + ' Quarter')
elif quarter > 1:
print(quarter + ' Quarters')
elif quarter_change >= 10:
dime = quarter_change // 10
dime_change = quarter_change % 10
if dime == 1:
print(dime + ' Dime')
elif dime > 1:
print(dime + ' Dimes')
elif dime_change >= 5:
nickel = dime_change // 5
nickel_change = dime_change % 5
if nickel == 1:
print(nickel + ' Nickel')
elif nickel > 1:
print(nickel + ' Nickels')
elif nickel_change >= 1:
penny = nickel_change // 1
if penny == 1:
print(penny + ' Penny')
else:
print(penny + ' Pennies')
total = int(input())
if total == 0:
print("No change")
else:
denominations = [(100, "Dollar", "Dollars"), (25, "Quarter", "Quarters"), (10, "Dime", "Dimes"), (5, "Nickel", "Nickels"), (1, "Penny", "Pennies")]
for d in denominations:
coins = total // d[0]
total %= d[0]
if coins > 1:
print(f"{coins} {d[2]}")
elif coins == 1:
print(f"1 {d[1]}")
In this answer, I created a list full of tuples of all the coins and their values in cents. I then created a for loop which runs through all the tuples in the list, dividing the total removing the remainder for the number of coins
like this:
*coins = total // d[0] #returns the number of coins of the current iteration
Then, in order for the loop to continue to the next iteration and do the calculations correctly, I set the total in cents equal to the remainder of the total divided by the current iteration.
like this:
total %= d[0] #can also be written as total = total % d[0]
Then, I take the number of coins and check if the value is greater than one. If the conditional is met, it prints the number of coins followed by the corresponding "plural version" of the word.
like this:
if coins > 1:
print(f"{coins} {d[2]}")
#d[2] refers to the third item in the tuple of the current iteration
Finally, I use an else-if conditional to return 1 plus the "singular version" of the word
like this:
elif coins == 1:
print(f"1 {d[1]}")
#d[1] refers to the second item in the tuple of the current iteration
Your code has numerous problems that needed to be resolved, including the lack of a condition for input values 0 < total_change < 100, problems with indentation (the elif blocks should be aligned), unnecessary variables (you do not need variables like nickel_change and dime_change - total_change is all that matters), and you tried to print dollar + ' Dollar' even though dollar was a numeric variable.
I wanted to improve on the issues in your code and make it, well, functional, but without entirely rewriting your work. So, the basic framework of the code I'm going to provide is the same.
I used the method of recursion. I have the following function with all of your (cleaned) code:
def printCurrency(total_change):
dollar = total_change//100
dollar_change = total_change % 100
if dollar == 1:
print(str(dollar) + ' Dollar')
printCurrency(total_change-1*100)
elif dollar > 1:
print(str(dollar) + ' Dollars')
printCurrency(total_change-dollar*100)
elif dollar_change >= 25:
quarter = dollar_change//25
quarter_change = dollar_change % 25
if quarter == 1:
print(str(quarter) + ' Quarter')
printCurrency(total_change-1*25)
elif quarter > 1:
print(str(quarter) + ' Quarters')
printCurrency(total_change-quarter*25)
elif dollar_change >= 10:
dime = dollar_change // 10
dime_change = dollar_change % 10
if dime == 1:
print(str(dime) + ' Dime')
printCurrency(total_change-1*10)
elif dime > 1:
print(str(dime) + ' Dimes')
printCurrency(total_change-dime*10)
elif dollar_change >= 5:
nickel = dollar_change // 5
nickel_change = dollar_change % 5
if nickel == 1:
print(str(nickel) + ' Nickel')
printCurrency(total_change-1*5)
elif nickel > 1:
print(str(nickel) + ' Nickels')
printCurrency(total_change-nickel*5)
elif dollar_change >= 1:
penny = dollar_change // 1
if penny == 1:
print(str(penny) + ' Penny')
printCurrency(total_change-1*1)
else:
print(str(penny) + ' Pennies')
printCurrency(total_change-penny*1)
Notice how every time a line is printed, the function is ran again but after subtracting out the change we've already processed.
A few examples:
>>> printCurrency(45)
1 Quarter
2 Dimes
>>> printCurrency(101)
1 Dollar
1 Penny
>>> printCurrency(349)
3 Dollars
1 Quarter
2 Dimes
4 Pennies
And to tie this into your original framework with an input...
total_change = int(input())
if total_change <= 0:
print('No change')
if total_change >= 0:
printCurrency(total_change)
Let me know if you have any questions about the changes I've made to your code!
This is more of an answer that zybooks is looking for considering what it has taught up to this point. All that I have done here is decrement total_change each time I go down the list of coins. If there were no coins for that set then print a statement on the previous line.
total_change = int(input())
if total_change <= 0:
print('No change')
else:
dollar = total_change // 100
if dollar == 1:
print(dollar, 'Dollar')
total_change = total_change - (dollar * 100)
elif dollar <= 0:
print(end='')
else:
print(dollar, 'Dollars')
total_change = total_change - (dollar * 100)
quarter = total_change // 25
if quarter == 1:
print(quarter, 'Quarter')
total_change = total_change - (quarter * 25)
elif quarter <= 0:
print(end='')
else:
print(quarter, 'Quarters')
total_change = total_change - (quarter * 25)
dime = total_change // 10
if dime == 1:
print(dime, 'Dime')
total_change = total_change - (dime * 10)
elif dime <= 0:
print(end='')
else:
print(dime, 'Dimes')
total_change = total_change - (dime * 10)
nickel = total_change // 5
if nickel == 1:
print(nickel, 'Nickel')
total_change = total_change - (nickel * 5)
elif nickel <= 0:
print(end='')
else:
print(nickel, 'Nickels')
total_change = total_change - (nickel * 5)
penny = total_change // 1
if penny == 1:
print(penny, 'Penny')
total_change = total_change - (penny * 1)
elif penny <= 0:
print(end='')
else:
print(penny, 'Pennies')
total_change = total_change - (penny * 1)
Related
I'm trying to make an ATM-like program in Python. The idea is that the user inputs any amount of money and the minimum amount of bills (100, 50, 25, 10, 5) will be printed.
So for example:
Input: 258
expected output: "2 $100 Bills, 1 $50 Bill, 1 $5 Bill, 3 $1 Bills".
The program works for number that are multiples of 5, but I can't seem to get the $10 and $1 Dollar bills to behave the same way. Here is the code:
print("Hi! Welcome to Python Bank. \nHow much would you like to withdraw?")
amnt = int(input("Please input amount: "))
if amnt >= 100:
if amnt // 100 >= 2:
print(amnt // 100, "$100 Bills")
else:
print("1 $100 Bill")
if (amnt // 50) % 2 != 0:
print("1 $50 Bill")
if (amnt // 25) % 2 != 0:
print("1 $25 Bill")
if (amnt // 10) % 2 != 0:
print(amnt // 10, "$10 Bills")
if (amnt // 5) % 2 != 0 and (amnt // 25) % 2 == 0:
print("1 $5 Bill")
if (amnt // 1) % 2 != 1:
print((amnt // 1), "$1 Bills")
I'm using the (//) operator since it tells you how many of the number on the right is in the number on the left. Then used the (%) operator with (!= 0). This seems to work for 100, 50, 25, but not for 10 and 1. How can I tackle this?
Your logic is wrong. This is the correct way.
if amount >= 100:
print(amount // 100, '100$ notes')
amount = amount % 100
if amount >= 50:
print('1 50$ notes')
amount = amount % 50
And so on
a cleaner solution would be to use a function to do that for you, just in case you decided to change the coin values.
print("Hi! Welcome to Python Bank. \nHow much would you like to withdraw?")
amnt = int(input("Please input amount: "))
def solve(m):
bills = [100, 50, 25, 10, 5, 1]
dic = {}
for bill in bills:
if m >= bill:
dic[bill] = m // bill
m -= dic[bill] * bill
return dic
def disp(dic):
s = ', '.join([ "{} ${} bills".format(dic[bill], bill) for bill in dic])
print(s)
disp(solve(amnt))
Assuming you have Python3, you can use f-strings, and you can always use a loop for things like these. That way, the logic is consistent for each bill size:
def print_change(amnt, bill_sizes=(100, 50, 25, 10, 5, 1)):
# loop over bill sizes
for bill_size in bill_sizes:
# skip if there isn't enough left for this bill
if amnt >= bill_size:
# remove n number of bills from amnt
n = amnt // bill_size
amnt -= n * bill_size
# print the results, with an 's' if there are more than one
print(f'{n} ${bill_size} Bill' + ('s' if n > 1 else ''))
print("Hi! Welcome to Python Bank. \nHow much would you like to withdraw?")
print_change(int(input("Please input amount: ")))
I simply just added an elif to check if they inputted 1 and it seems to do what I think you want.
print("Hi! Welcome to Python Bank. \nHow much would you like to withdraw?")
amnt = int(input("Please input amount: "))
if amnt >= 100:
if amnt // 100 >= 2:
print(amnt // 100, "$100 Bills")
else:
print("1 $100 Bill")
if (amnt // 50) % 2 != 0:
print("1 $50 Bill")
if (amnt // 25) % 2 != 0:
print("1 $25 Bill")
if (amnt // 10) % 2 != 0:
print(amnt // 10, "$10 Bills")
if (amnt // 5) % 2 != 0 and (amnt // 25) % 2 == 0:
print("1 $5 Bill")
if (amnt // 1) % 2 != 1:
print((amnt // 1), "$1 Bills")
elif amnt == 1:
print((amnt // 1), "$1 Bills")
The code provided below is not giving the output for "calculate Output Change in the least amount of coins/notes for change". I am new with Phyton and trying to learn, so anyone can help me spotting out and correcting what I have done wrong?. This application must- take inputs: Time in, Time Out; Output Cost, then ask for Payment in and the calculate Output Change in the least amount of coins/notes for change. The code is asking for inputs but not giving an output of calculating output change in least amount of coins/notes for change.
def print_euros(money, val):
while money <= val:
print("£" + str(val), end=", ")
money -= val
return money
def print_p(money, val):
while money <= val:
print(str(val), end="p,")
money -= val
return money
in_hour, in_min = map(int, input().split(':'))
out_hour, out_min = map(int, input().split(':'))
payment_in = input().split(',')
money_in = []
for i in payment_in:
money_in.append(int(i[1:]))
tot_money = sum(money_in)
tot_hours = 0
if out_hour <= in_hour:
tot_hours = 24 - in_hour + out_hour
else:
tot_hours = abs(out_hour - in_hour)
tot_mins = 0
if out_min <= in_min:
tot_mins = 60 - in_min + out_min
else:
tot_mins = abs(out_min - in_min)
if tot_mins == 60:
tot_hours += 1
tot_mins = 0
output_cost = tot_hours * 3
print("Output cost : £" + str(output_cost) + "." + str(tot_mins))
rem_change = 0
if tot_mins > 0:
rem_change = 100 - tot_mins
tot_money = tot_money - output_cost - 1
else:
tot_money -= output_cost
print("output change : ", end="")
tot_money = print_euros(tot_money, 20)
tot_money = print_euros(tot_money, 10)
tot_money = print_euros(tot_money, 5)
tot_money = print_euros(tot_money, 1)
rem_change = print_p(rem_change, 50)
rem_change = print_p(rem_change, 20)
rem_change = print_p(rem_change, 10)
rem_change = print_p(rem_change, 5)
rem_change = print_p(rem_change, 2)
rem_change = print_p(rem_change, 1)
I just started learning programming and I am trying to write a program in Python, that takes the amount that is supposed to be paid and the amount actually paid and calculates, what notes and coins should the cashier give back.
It seems to work fine for everything except the amounts under one dollar. I suspect it has something to do with decimal numbers, but I couldn't find the error. Also, sorry for my code, it's really messy and it could probably be done in a few lines, but I am total beginner.
amount_due = float(input('What is the amount you are supposed to pay? '))
amount_paid = float(input('What is the amount you paid? '))
one_hundreds = 0
twenties = 0
tens = 0
fives = 0
ones = 0
quarter = 0
dime = 0
nickel = 0
penny = 0
def calculate_difference():
global difference
difference = amount_paid - amount_due
difference = float(difference)
def evaluate_difference():
if difference < 0:
print("Sorry, you haven't paid enough money.")
quit()
elif difference == 0:
print('Awesome! You paid exactly how much you were supposed to pay.')
else:
check_hundreds()
def check_hundreds():
global one_hundreds
global difference
while difference >= 100:
one_hundreds += 1
difference -= 100
else:
check_twenties()
def check_twenties():
global twenties
global difference
while difference >= 20:
twenties += 1
difference -= 20
else:
check_tens()
def check_tens():
global tens
global difference
while difference >= 10:
tens += 1
difference -= 10
else:
check_fives()
def check_fives():
global fives
global difference
while difference >= 5:
fives += 1
difference -= 5
else:
check_ones()
def check_ones():
global ones
global difference
while difference >= 1:
ones += 1
difference -= 1
else:
check_quarters
def check_quarters():
global quarter
global difference
while difference >= 0.25:
quarter += 1
difference -= 0.25
else:
check_dimes()
def check_dimes():
global dime
global difference
while difference >= 0.1:
dime += 1
difference -= 0.1
else:
check_nickels()
def check_nickels():
global nickel
global difference
while difference >= 0.05:
nickel += 1
difference -= 0.05
else:
check_pennies()
def check_pennies():
global penny
global difference
while difference >= 0.01:
penny += 1
difference -= 0.01
def write_results():
global one_hundreds
global twenties
global tens
global fives
global ones
global quarter
global dime
global nickel
global penny
print('The cashier should return you ' + str(one_hundreds) + " one hundred dollar bills, " + str(twenties) + ' twenty dollar bills, ' + str(tens) + ' ten dollar bills, ' + str(fives) + ' five dollar bills, ' + str(ones) + ' one dollar bills, ' + str(quarter) + ' quarters, ' + str(dime) + ' dimes, ' + str(nickel) + ' nickels and ' + str(penny) + ' pennies.')
calculate_difference()
evaluate_difference()
write_results()
You have forgot to put () after check_quarters
P.S.
using globals is very bad programming style
I'm new to Python, currently doing the MIT edX course. We had a problem to complete where we had to use the bisection method to find the lowest payment a person had to make to pay off a credit card dept in a year.We were given the balance and the annual interest rate. My code below works but it does not look correct to me. Does anyone have any insight in this? Thanks
def payment(balance, annualInterestRate):
newBalance = 0
monthlyInterest = annualInterestRate / 12
maxPaybal = (balance * (1 + monthlyInterest) ** 12) / 12
minPaybal = balance/12
while round(newBalance, 2) != 0.01 or round(newBalance, 2) != 0.00:
guess = (minPaybal + maxPaybal) / 2.0
newBalance = balance
months = 12
while months > 0:
prevBalance = newBalance - guess
uptdBalance = prevBalance + (prevBalance * monthlyInterest)
newBalance = uptdBalance
months -= 1
if round(newBalance, 2) == 0.01 or round(newBalance, 2) == 0.00:
return "Lowest Payment: ", round(guess, 2)
elif newBalance < 0.00:
maxPaybal = guess
else:
minPaybal = guess
print(payment(balance, annualInterestRate))
My code:
monthlyInterestRate = annualInterestRate/12.0
low = balance/12
high = (balance*(1+monthlyInterestRate)**12)/12
guess = (low+high)/2
unpaidBalance = balance
month = 1
while True:
unpaidBalance= unpaidBalance-guess
while month < 13:
if unpaidBalance <= -0.1:
low = guess
month += 1
elif unpaidBalance >= 0.1:
high = guess
month += 1
else:
break
guess = (low + high)/2
print "Lowest Payment: " + str(round(guess, 2))
When I test it it gets stuck at the line "while month < 13:"
Why does it do this and how do I fix it?
If you break at each loop of inner while, you remains less than 13.
And this goes on and on since you proceed While True and do not update your guess.
I fear you are facing infinite looping there.
Your break statement breaks the closest loop, that is the While month < 13 loop. The next line is not read. guessis not updated. The while True is not broken.
Maybe you wanted to say
while month < 13:
unpaidBalance= unpaidBalance-guess
if unpaidBalance <= -0.1:
low = guess
elif unpaidBalance >= 0.1:
high = guess
month += 1
guess = (low + high)/2
here you are
No is the best solution, but it works
monthlyPaymentRate = (balance*annualInterestRate/12)/((1-(1+annualInterestRate/12)**-12))
interest = monthlyPaymentRate * (annualInterestRate/12)
#print (monthlyPaymentRate)
#print (interest)
monthlyPaymentRate = (monthlyPaymentRate - interest) +1
#print (monthlyPaymentRate)
balanceInit = balance
epsilon = 0.01
low = monthlyPaymentRate
while low*12 - balance > epsilon:
balances = balanceInit
for i in range(12):
minpay = monthlyPaymentRate
unpaybal = balances - minpay
interest = (annualInterestRate /12) * unpaybal
smontfinal = unpaybal + interest
balances = smontfinal
#print('Remaining balance: ' ,round(balances,2) )
if balances <0:
low = -1
break
if balances < 0 :
low = -1
else:
monthlyPaymentRate =monthlyPaymentRate + 0.001
print('Lowest Payment:' ,round(monthlyPaymentRate,2) )