【发布时间】:2022-01-10 16:18:22
【问题描述】:
它返回的错误是:
NameError: name 'lives' is not defined
我知道代码不是尽可能高效,这是我的第一个项目之一,但是无论我尝试做什么都会弹出此错误,我尝试为它创建一个全局但没有帮助。非常感谢您对此的帮助,谢谢!
import random
import time
def main():
global guess,rand_num
win = False
rand_num = 45
lives = 10
while lives > 0 and win == False:
guess = int(input("Guess a number!"))
compare()
print("Well done!")
time.sleep(3)
def compare():
global lives,win
if guess == rand_num:
print("You guessed correct!")
win = True
elif guess > rand_num:
print ("Guess lower!")
lives = lives - 1
else:
print ("Guess higher!")
lives = lives - 1
def repeat():
replay = input("would you like to play again? Y/N")
if replay == "Y":
print("enjoy!")
main()
elif replay == "N":
"Goodbye then, hope you enjoyed!"
time.sleep(3)
os._exit
else:
print("please enter Y or N")
repeat()
main()
repeat()
编辑:将全局生命放在 main() 中会返回错误:
UnboundLocalError: local variable 'lives' referenced before assignment
【问题讨论】:
-
看看@chepner 的回答。
global声明应该在main函数中。如果你这样做,你的代码就可以正常工作。 -
一般建议:避免使用全局变量。编写函数,而不是过程。 Python 程序员通常使用 4 个空格进行缩进。
-
我在 compare() 和 main() 中为所有 4 个生命值、胜利值、rand_num 和猜测值都设置了全局值,这似乎有效,但我仍然不确定是否需要所有 4 个值在两者中,或者在哪里需要哪些。 @Zondo
-
为什么避免全局变量是好的@Eli Korvigo? (ps这是我能弄清楚如何做到这一点的唯一方法,正如我在我的问题中所说的那样,我是编码新手;P)
-
如果您在该函数中设置变量,您应该声明全局变量。要使
x = 4影响全局命名空间,您需要将x声明为全局。print x,你不知道。
标签: python variables python-3.5