python giving me UnboundLocalError: local variable referenced before assignment when trying to work with variables
python giving me UnboundLocalError: local variable referenced before assignment when trying to work with variables
所以我目前正在学习 python 中的编码,并且我编写了这个基本的文字游戏。这个想法是,你与老板战斗,你有 66% 的机会赢得这场战斗,但如果你输了(33% 的机会),你会失去一条生命,如果你有 0 条生命,你就会输掉比赛。问题在于生命变量。它首先设置为 3,程序应该在每次失败后从玩家中减去 1 活,并在 lives 变量为 0 时执行 sys.exit。但是在第一次失败后程序崩溃并给出此错误:
Traceback (most recent call last):
File "file path", line 24, in <module>
boss()
File "file path", line 21, in boss
lives = lives - 1
UnboundLocalError: local variable 'lives' referenced before assignment
这是我的代码:
import random, sys
lives = 3
#title screen
print('SUPER NINJA WARRIORS PLANET')
print('press A to start')
menu = input()
if menu == 'A' or 'a':
pass
else:
print('press A to start')
def boss():
print('BOSS')
print('press X to attack')
attack = input()
number = random.randint(1, 3)
if number == 1:
print('Boss defeated!')
elif number == 2:
print('Boss defeated!!')
elif number == 3:
print('Boss defeated You!')
lives = lives - 1
while True:
boss()
if lives == 0:
sys.exit
elif lives != 0:
continue
根据 Python documentation,如果编译器在 function/method(本地范围)中看到变量赋值,它会自动将该名称标记为本地,因此不会考虑任何类似命名的外部变量。这就是为什么当它看到在局部变量赋值之前它在函数内部用于其他东西(检查你的情况)时,它会抛出一个错误,你实际上正在尝试使用一个尚未被使用的变量尚未分配(本地术语)。
如果您将 lives = lives - 1
更改为 new_lives = lives - 1
,则编译器会将 lives
视为全局变量并且不会抛出异常。但这会给您的情况带来更多问题。我建议将生命作为参数传递给函数 - def boss(lives):
并通过传递生命 boss(lives)
.
在循环中调用它
所以我目前正在学习 python 中的编码,并且我编写了这个基本的文字游戏。这个想法是,你与老板战斗,你有 66% 的机会赢得这场战斗,但如果你输了(33% 的机会),你会失去一条生命,如果你有 0 条生命,你就会输掉比赛。问题在于生命变量。它首先设置为 3,程序应该在每次失败后从玩家中减去 1 活,并在 lives 变量为 0 时执行 sys.exit。但是在第一次失败后程序崩溃并给出此错误:
Traceback (most recent call last):
File "file path", line 24, in <module>
boss()
File "file path", line 21, in boss
lives = lives - 1
UnboundLocalError: local variable 'lives' referenced before assignment
这是我的代码:
import random, sys
lives = 3
#title screen
print('SUPER NINJA WARRIORS PLANET')
print('press A to start')
menu = input()
if menu == 'A' or 'a':
pass
else:
print('press A to start')
def boss():
print('BOSS')
print('press X to attack')
attack = input()
number = random.randint(1, 3)
if number == 1:
print('Boss defeated!')
elif number == 2:
print('Boss defeated!!')
elif number == 3:
print('Boss defeated You!')
lives = lives - 1
while True:
boss()
if lives == 0:
sys.exit
elif lives != 0:
continue
根据 Python documentation,如果编译器在 function/method(本地范围)中看到变量赋值,它会自动将该名称标记为本地,因此不会考虑任何类似命名的外部变量。这就是为什么当它看到在局部变量赋值之前它在函数内部用于其他东西(检查你的情况)时,它会抛出一个错误,你实际上正在尝试使用一个尚未被使用的变量尚未分配(本地术语)。
如果您将 lives = lives - 1
更改为 new_lives = lives - 1
,则编译器会将 lives
视为全局变量并且不会抛出异常。但这会给您的情况带来更多问题。我建议将生命作为参数传递给函数 - def boss(lives):
并通过传递生命 boss(lives)
.