I am in a beginner scripting class where we need to write some code that makes change based on integer input. It also needs to print the correct plurality for each coin type. I am having some trouble getting my code to work, as it stops at the first operation it performs and I'm not sure how to get it to continue. I'm guessing it has something to do with how I've laid out all these elif statements and I'm not sure what the proper thing to do is to get the code to continue if it still has a remainder for the change:
# Get input for amount of change
change = int(input())
# If change is less than 1, print 'No change'
if change < 1:
print('No change')
# If change is over 199, subtract and print 'X Dollars'
elif change > 199:
print(change // 100, 'Dollars\n')
change = change % 100
# If change is 100-199, subtract and print '1 Dollar'
elif 99 < change <= 199:
print('1 Dollar\n')
change = change % 100
# If remaining change is 50-99, subtract and print 'X Quarters'
elif 49 < change <= 99:
print(change // 25, 'Quarters\n')
change = change % 25
# If remaining change is 25-49, subtract and print '1 Quarter'
elif 24 < change <= 49:
print('1 Quarter\n')
change = change % 25
# If remaining change is 25, print '1 Quarter' and set change to 0
elif change == 25:
print('1 Quarter')
change = 0
# If remaining change is 20-24, subtract and print '2 Dimes'
elif 19 < change <= 24:
print('2 Dimes\n')
change = change % 10
# If remaining change is 10, print '1 Dime' and set change to 0
elif change == 10:
print('1 Dime')
change = 0
# If remaining change is 5-9, subtract and print '1 Nickel'
elif 4 < change <= 9:
print('1 Nickel\n')
change = change % 5
# If remaining change is 2-4, subtract and print 'X Pennies'
elif 1 < change <= 4:
print(change // 1, 'Pennies')
change = change % 1
# If remaining change is 1, print '1 Penny' and set change to 0
elif change == 1:
print('1 Penny')
change = 0
Could anyone give me an idea? Thank you for your time.
Always subtract what you have already matched from the rest of the change. And then continue using IF not ELIF, since elif will never match again once a previous if matched.
# Get input for amount of change
change = int(input())
# If change is less than 1, print 'No change'
if change < 1:
print('No change')
# If change is over 199, subtract and print 'X Dollars'
if change > 199:
print(change // 100, 'Dollars\n')
change = change - change // 100 * 100
# If change is 100-199, subtract and print '1 Dollar'
if 99 < change <= 199:
print('1 Dollar\n')
change = change - 100
# If remaining change is 50-99, subtract and print 'X Quarters'
if 49 < change <= 99:
print(change // 25, 'Quarters\n')
change = change - change // 25 * 25
# ....
and so on...