Public Group

# [Python] How to write this better

This topic is 4090 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

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
Oh okay, I didn't realize I could set up a loop like that... But I guess that makes sense. Thanks for the tips

1. 1
Rutin
25
2. 2
JoeJ
20
3. 3
4. 4
5. 5

• 9
• 9
• 46
• 41
• 23
• ### Forum Statistics

• Total Topics
631749
• Total Posts
3002051
×