# [Python] How to write this better

## Recommended Posts

glBender    156
Alright, so I've figured out that there is almost always a better way to do things with Python than I'm already doing. Just for practice, I decided to write a function to calculate the correct change(in US coins) to give to a person given a cash amount. This was the simplest way I could figure out to do it, any ideas for improvements?

def calc(amount):
# pairs the amounts with the names
types = [(25,'quarters'),(10,'dimes'),(5,'nickels'),(1,'pennies')]
for t in types:                    #for each kind of coin(greatest to least)
count = (amount)/t[0]          #how many coins will go into that amount
if count > 0:                  #if at least one
print str(count) +' '+t[1] #print out the number
amount -= count*t[0]       #subtract that amount from the total



##### Share on other sites
I really don't like using tuples like that (ie. using hardcoded indices), so one suggestion I have is:

def calc(amount):    # pairs the amounts with the names    types = [(25,'quarters'),(10,'dimes'),(5,'nickels'),(1,'pennies')]    for coinValue, coinName in types:       #for each kind of coin(greatest to least)        count = (amount)/coinValue          #how many coins will go into that amount        if count > 0:                  	    #if at least one            print count, coinName           #print out the number            amount -= count*coinValue       #subtract that amount from the total

Makes things a lot more explicit :).

EDIT: Don't need str() when printing count, and separating by comma adds in a ' '.

[Edited by - cow_in_the_well on May 7, 2007 2:12:49 AM]

##### Share on other sites
glBender    156
Oh okay, I didn't realize I could set up a loop like that... But I guess that makes sense. Thanks for the tips