[Tutor] UnboundLocalError and Break
Dave Angel
davea at ieee.org
Thu Oct 1 05:13:57 CEST 2009
Corey Richardson wrote:
> Luke Paireepinart wrote:
>> If your code's more than 10 lines long or so, put it on pastebin.com
>> <http://pastebin.com> and send us the link rather than inlining the
>> whole thing. You could also send it as an attachment.
>> Your formatting is all screwed up and I can't read the code at all,
>> but I have an idea about your error.
>>
>> Hmmm...thats odd. I didn't do anything different....but I can do
>> that.http://pastebin.com/m518f612f
>
>> <http://mail.python.org/mailman/listinfo/tutor>
>>
>>
>
The pastebin version of the code is substantially different than the
original pasted version, and although the error message doesn't
correspond to the posted code, at least there's enough to identify the
particular error.
Line 21: playHp -= damage #Player takes damage (I think...I will
have to work that out)
in the function monsAttk() is trying to modify a local variable playHp,
without initializing it. Nowhere else in the function is that variable
referenced or defined.
So you get a
UnboundLocalError: local variable 'playHp' referenced before assignment
What you undoubtedly meant to do is to subtract damage from the *global*
variable playHp. But without a global declaration, that's not what
happens. It tries instead to adjust a local variable by that name. And
of course that local is unbound.
The "fix" could be to make the function look like this:
1.
def monsAttk (damage, attack): #A monsters attack
2. global playHp #declare that we'll be modifying a
global variable by this name, not defining a local
3.
if attack > deff: #Monster hit
4.
playHp -= damage #Player takes damage (I think...I will
have to work that out)
5.
print "You have sustained", damage, "damage, with",
damage-playHp, "remaining" #Inform player of their statu
I have to try hard to resist attacking your indiscriminate use of global
variables. But you said to just help on the one problem....
DaveA
More information about the Tutor
mailing list