python - Python:如何更改函数中全局变量的值?
问题描述
为什么我不能将变量 can_answer 更改为 False 而不会出现此错误?这只是我写的一些快速代码。
import random
questions = ["What's 1+1?", "What's 2+2?"]
def question():
global can_answer
can_answer = True
print(random.choice(questions))
def ans(answer):
if can_answer:
if can_answer == 2 or 4:
print('correct')
else:
print('wrong')
can_answer = False
else:
print('no questions to answer')
解决方案
在使用global var
变量之前使用
在这种情况下,猜你在这里写错了
if can_answer == 2 or 4:
不是吗answer
import random
questions = ["What's 1+1?", "What's 2+2?"]
def question():
global can_answer
can_answer = True
print(random.choice(questions))
def ans(answer):
if can_answer:
if can_answer == 2 or can_answer == 4:
print('correct')
else:
print('wrong')
can_answer = False
else:
print('no questions to answer')
推荐阅读
- python - Python 和压缩算法性能
- ios - Crashlytics iOS - 第 0 行崩溃 - Swift 来源
- python - Telegram Bot Inlinekeyboard ,回调另一个 inlinekeyboard
- c# - 如何解决“调用'gsapi_init_with_args'时发生错误:-100”将PDF转换为PDF/A时的问题-Ghostscript
- c++ - C++ islower() 函数调试断言失败错误
- sql - \copy 命令无法将 csv 表导入我的 AWS 数据库
- python-3.x - 将数据连接和发送到 SSL 套接字时,Python 程序没有收到响应
- excel - 将其下具有多行数据但没有该名称的行名称复制到该行名称下每一行的新列中
- selenium-webdriver - 如何在不添加 PDFBox 实用程序的方法参数 testng(来自 XML)的情况下实现 iTestContext 侦听器
- javascript - 在 Selenium Ruby 中单击操作后出现 Net Read Timeout 错误