Bummer! That course has been retired.

Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

Coin change exercise program

The program works fine. But one thing i don't quite understand is that why do the program knows the total 's values when compared to amount in line 34 even though we never add the entry's value to it every time the user input a value?

import random

print('The purpose of this game is to enter a number of coins value that')
print('adds up to a display target value')
print('Enter coin values as 1-penny, 5-nickel, 10-dime, and 25-quarter')
print('Hit return after the last entered coin value')
print('----------------')

terminate = False
empty_str = ''

#To give targeted value
while not terminate:
    amount = random.randint(1,99)
    print('Enter coins value that add ups to {}'.format(amount))
    game_over = False
    total = 0

    while not game_over:
        valid_entry = False

        while not valid_entry:
            if total == 0:
                entry = input('Enter first coins: ')
            else:
                entry = input('Enter next coins: ')


            if entry in {empty_str, '1', '5','10','25'}:
                valid_entry = True
            else:
                print('Invalid entry')

        if entry == empty_str:
            if total == amount:
                print('Correct!')
            else:
                print('Sorry you only entered {} cents'.format(total))
            game_over = True

        else:
            total = total + int(entry)
            if total > amount:
                print('Sorry total amount exceed {} cents.'.format(amount))
                game_over = True

            if game_over:
                entry = input('Try again ?(Y/N)' )

                if entry == 'N':
                    terminate = True

print('Thanks for playing. Goodbye!')

1 Answer

Steven Parker
Steven Parker
243,215 Points

That test you are looking at is only done when nothing is entered.

:point_right: But when a new value is entered, it is added to the total on line 42 where it says: "total = total + int(entry)".

Thanks =)