python - 为什么我在 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()
解决方案
将该行移至global win_or_lose
重置函数的顶部。范围声明通常应该是其函数的第一行。
推荐阅读
- c++ - 在 MacOS 上找不到提升 multi_index
- node.js - 具有 cwe-352 漏洞的 node.js / express 应用程序
- python - 基于 Python Panda 的拆分和分组 json 行文件
- reactjs - 反应类组件是否与角度类组件相似?
- pytest - 使用 pytest.main() 创建 html 报告时出现问题
- serial-port - 在重定向端口监视器中将端口输出配置为 PROMPT FOR FILENAME 未打开对话框以将文件保存到文件夹
- stock - 完美时机的算法交易。我想在 11:00:00 的准确时间下订单
- java - 使用 java 和 mybatis spring 在 EKS 中运行的应用程序向 oracle 插入和更新值的问题
- ruby - 如何在 ruby 循环中停止在特定范围内
- r - 基于满足条件的行数子集数据框