Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- coins = {200:'Toonies', 100:'Loonies', 25:'Quarters', 10:'Dimes', 5:'Nickles', 1:'Pennies'}
- #This is a dictionary. It holds different values, like a list, but with it you can actually give keys to your variables. The syntax is "key:variable", which means here for example, the key 10 corresponds to 'Dimes', and you can access it by using coins[10].
- change = input('Enter the amount of change in cents: ')
- for value in sorted(coins.keys(), reverse=True):
- #The for loop executes its instruction block once for every value in the iterable after the "in" keyword, with the name between "for" and "in" corresponding to these variables in turn.
- #The coins.keys function gives us a list with the keys of the dictionary, here the value of each coin. We then use the sorted function on it to sort the keys, because keys in a dictionary aren't always sorted nor are they in the order you defined them. Be very aware of that when using dictionaries.
- #We also tell the sorted function to reverse the list of keys via a parameter because we want to go through them from biggest to smallest.
- count = change/value
- change %= value
- #The %= operator is used to directly modify the variable it is applied on.
- #x %= y is equal to x = x%y.
- #This also works for every other operator.
- print "%s ($%d) : %d" % (coins[value], value/100.0, count)
- #This prints a formatted string. The %s and %d in the string will be replaced by the values between parenthesis placed after the % sign.
- #-----
- #Concise version :
- coins = {200:'Toonies', 100:'Loonies', 25:'Quarters', 10:'Dimes', 5:'Nickles', 1:'Pennies'}
- change = input('Enter the amount of change in cents: ')
- for value in sorted(coins.keys(), reverse=True):
- count = change/value
- change %= value
- print "%s ($%d) : %d" % (coins[value], value/100.0, count)
Advertisement
Add Comment
Please, Sign In to add comment