(Very Newbie) Problems defining a variable

Bruno Desthuilliers bruno.42.desthuilliers at websiteburo.invalid
Fri Dec 12 06:56:16 EST 2008


febaen at gmail.com a écrit :
> #!/usr/bin/python
> #Py3k, UTF-8
> 
> bank = int(input("How much money is in your account?\n>>"))
> target = int(input("How much money would you like to earn each year?
> \n>>"))
> 
> interest = 0
> i = 0
> 
> while interest < target:
> #determine the interest rate to use
> 	if bank >= 9999:
> 		rate = 0.006
> 	elif bank >= 10000 and bank <= 24999:
> 		rate = 0.0085
> 	elif bank >= 25000 and bank <= 49999:
> 		rate = 0.0124
> 	elif bank >= 50000 and bank <= 99999:
> 		rate = 0.0149
> 	elif bank >= 100000:
> 		rate = 0.0173

(snip)

> I'm pretty certain that that is also the problem in the code. I'm
> pretty sure it's a problem with the 'if' statements', and it looks
> like it's one of those mistakes that's so simple you look back on it
> and laugh at yourself. If you put in a bank number <= 9999, it fails,
> saying  "NameError: name 'rate' is not defined".  If you put in one
> higher, it runs correctly, but thinks that the rate is 0.006

Indeed. That's what you asked for. If bank is >= 9999, then rate will be 
set to 0.006, and the following tests will be skipped. Else - since you 
just don't handle the case -, rate is not defined at all.

I guess you wanted your first test to be:

    if bank <= 9999:
       ...

FWIW, when using if/elif that way, make sure you always end with a 
"default" else clause (even if just to signal you didn't expect to be 
there...)

HTH





More information about the Python-list mailing list