Python NameError,变量“未定义" [英] Python NameError, variable 'not defined'

查看:45
本文介绍了Python NameError,变量“未定义"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

它返回的错误是:

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

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

putting global lives inside main() returns the error:

UnboundLocalError: local variable 'lives' referenced before assignment

推荐答案

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

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.

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

这篇关于Python NameError,变量“未定义"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆