我经历了这几次并且没有任何错误,所以它可能是我的头脑。我也为你的眼睛做了什么道歉,这是我编程的第一年,并且可能犯了多个礼仪错误。
print('Befor we begin, when you are given options, I ask you to type your input as show, failure to do so will break the program and you will lose all of your progress')
def test():
print('it has worked!')
def stats():
global attack
global health
global mashealth
global agility
if race in ('human','Human'):
maxatk=4
maxagi=4
attack = lambda:random.randint(2,maxatk)
maxhealth = 20
health=20
agility = random.randint(maxagi,10)
elif race in ('Orc','orc'):
attack = random.randint(3,maxATK)
maxhealth = 25
agility = random.radint(maxAGI,10)
def main():
while True:
print('What would you like to do')
print('Rest Shop Fight')
answer=input('-')
if answer in ('Rest','rest'):
health=maxhealth
continue
def character():
global race
global name
global gender
print('What would you like the name of your character to be?')
name=input('-')
print()
print('What race will your character be?')
print('Human Orc Elf')
while True:
race = input('-')
if race in ('human','Human','Orc','orc','Elf','elf'):
break
else:
print('Not a valid response, try again')
continue
print()
print('What gender is your character')
gender=input('-')
print()
def goblin():
goblinatk=1
goblinhealth=100
while True:
print('You have encountered a goblin, what will you do?')
do=input('-')
if do == 'attack':
damage=attack()
goblinhealth=goblinhealth-damage
print('You did',damage,'damage to the goblin')
print('The goblin has',goblinhealth,'hp')
goblinatk=lambda:random.randint(3,10)
health=health-goblinatk
print('the goblin did',goblinatk,'to you')
print('you have',health,'hp')
if goblinhealth <0:
print('The goblin has died')
break
if health <0:
print('you have died')
break
character()
stats()
goblin()
test()
错误在这里
Traceback (most recent call last):
File "H:\16CoFrega\Code\Python\GAME.py", line 255, in <module>
goblin()
File "H:\16CoFrega\Code\Python\GAME.py", line 238, in goblin
health=health-goblinatk
UnboundLocalError: local variable 'health' referenced before assignment
答案 0 :(得分:2)
您需要将health
指定为全局变量,否则它将被视为局部变量,因为您在函数内部分配了它。示例 -
def goblin():
global health
goblinatk=1
goblinhealth=100
答案 1 :(得分:2)
def goblin():
............
health=health-goblinatk
............
看看这个函数定义。您的函数不知道health
是什么,因此它不允许您从health
下标内容。
因此,某种程度上,函数必须识别health
是什么。两种最常见的方式:
第一种方式,将health
声明为全局变量。现在可以在全球范围内识别health
。但这不是最好的方法,因为处理全局变量很难且容易出错,而且你已经处理了太多的全局变量。所以,我不会推荐它。我宁愿建议你用方法2替换所有全局变量。要理解我为什么这么说,Read This Question
第二种方式,推荐的方法是将health
变量作为函数的参数传递,最后从函数返回。
像这样:
def goblin(health):
............
health=health-goblinatk
............
return health
如果您已经归还了某些东西,请不要担心。使用python,您可以将多个变量作为元组返回。
return statement:
return a,b,c
调用声明:
a,b,c = func()
希望这有帮助:)