首页 > 解决方案 > 为什么我在 python 上的全局声明之前得到“变量分配”

问题描述

我跑了这个,我得到了错误

  File "C:\Users\Herec\AppData\Local\Programs\Python\Python38\lib\runpy.py", line 194, in _run_module_as_main
    return _run_code(code, main_globals, None,
  File "C:\Users\Herec\AppData\Local\Programs\Python\Python38\lib\runpy.py", line 87, in _run_code
    exec(code, run_globals)
  File "c:\Users\Herec\.vscode\extensions\ms-python.python-2021.1.502429796\pythonFiles\lib\python\debugpy\__main__.py", line 45, in <module>
    cli.main()
  File "c:\Users\Herec\.vscode\extensions\ms-python.python-2021.1.502429796\pythonFiles\lib\python\debugpy/..\debugpy\server\cli.py", line 444, in main
    run()
  File "c:\Users\Herec\.vscode\extensions\ms-python.python-2021.1.502429796\pythonFiles\lib\python\debugpy/..\debugpy\server\cli.py", line 285, in run_file
    runpy.run_path(target_as_str, run_name=compat.force_str("__main__"))
  File "C:\Users\Herec\AppData\Local\Programs\Python\Python38\lib\runpy.py", line 264, in run_path
    code, fname = _get_code_from_file(run_name, path_name)
  File "C:\Users\Herec\AppData\Local\Programs\Python\Python38\lib\runpy.py", line 239, in _get_code_from_file
    code = compile(f.read(), fname, 'exec')
  File "c:\Users\Herec\OneDrive\Desktop\python stuffz\shehzad.py", line 41
    global win_or_lose
    ^
SyntaxError: name 'win_or_lose' is assigned to before global declaration"

我试过看一个全局变量的例子,但我没有运气,我没有看到我做错了什么。

import random

wins = 0
win_or_lose = True

def reset():
    number = random.randint(1, 3)

    guess_count = 0
    guess_limit = 3
    out_of_guesses = False
    guess = ""
    print("Welcome to the Guessing Game!\nYou have 3 guesses")

    if number == 1:
        word = "Ketchup"
        phrase = "it's red and a condiment"

    if number == 2:
        word = "book"
        phrase = "Mrs. Freeman makes you take a log everyday on how much you use it"

    if number == 3:
        word = "pp"
        phrase = "Shehzad says it whenever we sleep in minecraft"

    print(phrase)

    while out_of_guesses == False and guess != word:
        if guess_count < guess_limit:
            guess = input("Enter a guess: ")
            guess_count += 1
        else:
            out_of_guesses = True
    if out_of_guesses:
        print("You're out of guesses, YOU LOSE!")
        win_or_lose = False
    else:
        print("You guessed correct, YOU WIN!")

    global win_or_lose
    if win_or_lose == True:
        wins += 1

    print("you have ",wins,"wins!")

    _reset = input("would you like to try again?")

    if _reset == "y" or reset == "yes":
        reset()
    else:
        print("you had a total of ",wins,"wins!")
        print("i hope to see you again, and goodbye!")
reset()

标签: pythonpython-3.xvisual-studio-code

解决方案


将该行移至global win_or_lose重置函数的顶部。范围声明通常应该是其函数的第一行。


推荐阅读