I'm making an attack system in python with def, but i got an error saying that the variable got referenced before assignment, eventhough i wrote it before the def. Does anyone know how?
import random
import time
monster = 20
def fight():
print('Monster Spawned! Attack by
typing A')
A = str(input())
while (A == 'A'):
damage = range(1, 21)
damage_done=(random.choice(damage))
monster = monster - damage_done
print('Slish Slash!')
print(monster)
print(damage_done)
fight()
if (monster < 0):
print('Good Job')
EDIT 1: Error message is
Traceback (most recent call last):
File "main.py", line 17, in <module>
fight()
File "main.py", line 12, in fight
monster = monster - damage_done
UnboundLocalError: local variable
'monster' referenced before assignment
CodePudding user response:
global monster
monster = monster - damage_done
you are in a function and it can't access a variable outside of it, so say to the function that there is a global variable with this name, outside and that it's a global variable... if not, it will be considered as a local variable and it will search for the monster
variable inside the function
I think your code needs a rewrite:
import random
monster = 20
def fight():
print('Monster Spawned! Attack by typing A')
A = str(input())
global monster
if A == 'A':
while monster > 0:
damage = range(1, 21)
damage_done=(random.choice(damage))
monster = monster - damage_done
print('Slish Slash!')
print(monster)
print(damage_done)
else:
print('Good Job')
fight()
you want a while to run unless monster < 0
and if monster < 0
, then you want to print good job
.
CodePudding user response:
Add global monster
one line before monster=monster-damage_done
If you don't add that then python recognizes monster
as a local variable, thus the local variable is used before assignment.
CodePudding user response:
The variable monster
is global, but the variable monster
inside the fight()
method is local, so, to specify that you want to assign the global variable, use global
before monster
.
def fight():
print('Monster Spawned! Attack by typing A')
A = str(input())
global monster
while (A == 'A'):
damage = range(1, 21)
damage_done=(random.choice(damage))
monster = monster - damage_done
print('Slish Slash!')
print(monster)
print(damage_done)
CodePudding user response:
the name of the variable declared in your init area and within the function only have one thing in common; a name. You can declare it as a global variable, or better yet pass the value to your defined function as an argument.
I would suggest renaming it something else within the function as that can be confusing.
import random
import time
monster = 20
def fight(monster):
print('Monster Spawned! Attack by typing A')
A = str(input())
while (A == 'A'):
damage = range(1, 21)
damage_done=(random.choice(damage))
monster = monster - damage_done
print('Slish Slash!')
print(monster)
print(damage_done)
fight(monster)
if (monster < 0):
print('Good Job')