【问题标题】:Python NameError, variable 'not defined'Python NameError,变量“未定义”
【发布时间】: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


【解决方案1】:

您需要在函数 main 之外定义变量“lives”,然后在任何要引用该全局变量的函数中定义“global 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
        ...
    

    【讨论】:

      【解决方案3】:

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

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

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

      【讨论】:

      • 错误变为:UnboundLocalError: local variable 'lives' referenced before assignment
      • 改了答案,看看
      猜你喜欢
      • 1970-01-01
      • 2021-06-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多