(Very Newbie) Problems defining a variable

feba febaen at gmail.com
Fri Dec 12 07:05:21 EST 2008


On Dec 12, 5:56 am, Bruno Desthuilliers <bruno.
42.desthuilli... at websiteburo.invalid> wrote:
> feb... 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


that's it, thanks! was confused with it being basically in a column of
all >= *.

I replaced it with

	if bank <= 0:
		print("You're in the red!")
		quit()
	elif bank >= 1 and bank <= 9999:
		rate = 0.0060
	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
	else:
		print("What's this doing here?")

which also changes it to keep it from going on forever if you put in a
negative amount. Out of curiosity, would you still recommend applying
an 'else' clause in this case? I don't see how it could ever be
triggered, even if there's an error of some kind



More information about the Python-list mailing list