Python NameError,变量“未定义”

6
它返回的错误是:
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()

编辑:将全局变量global lives放在main()函数内返回错误:

UnboundLocalError: local variable 'lives' referenced before assignment

1
看看@chepner的答案。global声明应该在main函数中。如果你这样做,你的代码就可以正常工作了。 - zondo
我在compare()和main()中都为lives、win、rand_num和guess设置了全局变量,这似乎起作用了,但我仍然不确定这四个变量是否都需要在两个函数中使用,或者哪些变量在哪里需要。@Zondo - Kaos
为什么避免使用全局变量是好的,@Eli Korvigo?(顺便说一句,这是我能想到的唯一方法,我是编程新手;P) - Kaos
这里有一些不错的阅读材料,关于全局状态为何如此恶劣。 - Eli Korvigo
所有这些全局变量都可以(而且应该)作为函数参数。这些函数应该接受一些输入并返回一些输出,而不会改变全局状态。你在这里看到的是一些硬核过程式编程。 - Eli Korvigo
显示剩余5条评论
3个回答

8
你需要在函数 main 之外定义变量 "lives",然后在任何想要引用该全局变量的函数中使用 "global lives"。当你在一个函数中给变量赋值时,它会默认为本地作用域。使用 "global lives" 告诉该函数将 lives 当做参考对象指向全局作用域。
import random
import time

lives = 10
win = False
guess = 0
rand_num = 45

def main():
    global guess, rand_num, lives, win
    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 guess, rand_num, 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()

2

你没有在 main() 函数内声明 lives 为全局变量,因此它是该函数的局部变量。

def main():
    global guess, rand_num, lives
    ...

0
当你在函数内部声明变量时,它们只在该函数的作用域内有效。因此,将全局变量声明在函数外部,代码将正常工作。
import random
import time

guess = None
random_num = None
lives = 3
win = False


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()

现在这个可以运行得很好。关于全局变量与局部变量的更多信息,您可以阅读:http://www.python-course.eu/global_vs_local_variables.php


错误变为: UnboundLocalError:在赋值之前引用了本地变量“lives” - Kaos
修改了我的答案,请看一下。 - Teemo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接