Python NameError,变量“未定义”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37955081/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 20:08:57  来源:igfitidea点击:

Python NameError, variable 'not defined'

pythonvariablespython-3.5

提问by Kaos

the error it returns is:

它返回的错误是:

NameError: name 'lives' is not defined

I know the code isn't as efficient as possible, this is one of my first projects, however whatever i try to do this error pops up, I've tried making a global for it but that didn't help. I would really appreciate some help with this, thanks!

我知道代码不是尽可能高效,这是我的第一个项目之一,但是无论我尝试做什么都会弹出这个错误,我已经尝试为它创建一个全局但没有帮助。我真的很感激这方面的帮助,谢谢!

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

EDIT: putting global lives inside main() returns the error:

编辑:将全局生命放入 main() 返回错误:

UnboundLocalError: local variable 'lives' referenced before assignment

回答by Carl 'Subzidion' Hiltbrunner

You need to define the variable "lives" outside of the function main, then any function where you want to reference that global variable you say "global lives." When you are in a function and assign a value to a variable, it assumes it is in the local scope. using "global lives" tells that function to look to the global scope as the reference of lives.

您需要在函数 main 之外定义变量“lives”,然后在要引用该全局变量的任何函数中定义“global life”。当您在函数中并为变量赋值时,它假定它在局部作用域中。使用“全局生命”告诉该函数将全局范围视为生命的参考。

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

回答by chepner

You didn't declare livesto be global inside main(), so it is local to that function.

您没有lives在 内部声明为 global main(),因此它对该函数是本地的。

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

回答by Teemo

When you declare it inside function they are only available in that function scope, so declare global variables outside functions and code will work fine.

当您在函数内部声明它时,它们仅在该函数范围内可用,因此在函数和代码之外声明全局变量将正常工作。

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

And now this works fine. For more info about gloval vs local variables you can read: http://www.python-course.eu/global_vs_local_variables.php

现在这工作正常。有关全局变量与局部变量的更多信息,您可以阅读:http://www.python-course.eu/global_vs_local_variables.php