0

Using a nested for loop, I wrote:

print("Change for $1")
dollar = 1
total_pennies = int(dollar * 100) # 100 pennies in a dollar #100
total_quarters = int(total_pennies/25) # 25 pennies in a quarter, 4 quarters in a dollar

for quarter in range(total_quarters): 
    remaining_quarter = total_pennies - quarter * 25
    for dime in range(int(remaining_quarter / 10)):
        remaining_dimes = remaining_quarter - dime * 10
        for nickel in range(int(remaining_dimes / 5)):
            penny = remaining_dimes - nickel * 5
            print(quarter, 'quarters', dime, 'dimes', nickel, 'nickels', penny, 'pennies')

But it doesn't give me "4 quarters, 0 dimes, 0 nickels, 0 pennies". Does anyone know how to fix this?

huy
  • 1

1 Answers1

1

Why it does not work

for quarter in range(total_quarters): 

If there are 4 quarters, this will loop 4 times, from 0 to 3 quarters, there will be no loop where quarter is 4. A way to fix this is:

for quarter in range(total_quarters + 1): 

Now, it will loop 5 times, where quarter is 0, 1, 2, 3, 4.

There is another issue with your code where all for loops will not be triggered if the previous value is 0. For example, if remaining_dimes is 0,

for nickel in range(int(remaining_dimes / 5)):

would mean

for nickel in range(0):

It will not loop.

You seem to also have missed a loop for pennies (1/100 of a dollar).

Link to solutions

I assume that you are doing this as a practice, and trying out your own methods, so I will link you to a helpful resource if you need more.

  • Is there any way to make the for loop work? – huy Sep 18 '21 at 22:44
  • This method is not the most efficient. It is dirty method but it get the work done. In every for loop, right before the nested one, check for the number of pennies left based on the current total. If it is 0, have a print statement with the rest of the coins as 0. For every coin except the smallest one (penny), ensure that your loop includes 0 and the largest value. – LemonsAndLigaments Sep 18 '21 at 23:33
  • Got it , thx a lot! – huy Sep 19 '21 at 00:08
  • Glad to have helped! Please accept this answer (https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work) so that people know this is solved. – LemonsAndLigaments Sep 19 '21 at 00:25