(Very Newbie) Problems defining a variable

Tim Rowe digitig at gmail.com
Fri Dec 12 19:12:39 CET 2008

Since we all seem to be having a go, here's my take. By pulling the
rates and thresholds into a dictionary I feel I'm getting a step
closer to the real world, where these would presumably be pulled in
from a database and the number of interest bands might vary. But is
there a tidier way to get 'thresholds'? I was a bit surprised that
rates.keys() didn't give me a list directly, so although the 3.0
tutorial says "The keys() method of a dictionary object returns a list
of all the keys used in the dictionary, in arbitrary order (if you
want it sorted, just apply the sort() method to )" that's not /quite/
such a given, because "the list of keys" doesn't seem to be there for
the sorting any more.

Is there a tidy way of making rates and thresholds local to get_rate,
without recalculating each time? I suppose going object oriented is
the proper way.


rates = {0: 0.006, 10000: 0.0085, 25000: 0.0124, 50000: 0.0149, 100000: 0.0173}
thresholds = list(rates.keys())

def get_rate(balance):
    for threshold in thresholds:
        if balance >= threshold:
            return rates[threshold]
        return 0.0

balance = int(input("How much money is in your account?\n>>"))
target = int(input("How much money would you like to earn each year?\n>>"))

if balance <= 0:
    print("You'll never make your fortune that way!\n")
    interest = 0
    year = 0
    while interest < target:
        rate = get_rate(balance)
        interest = balance * rate
        balance += interest
        year += 1
        print("Year %s, at %s rate: %s paid, %s in bank." % (year,
rate, interest, balance))

Tim Rowe

More information about the Python-list mailing list