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

相关内容

  • 没有找到相关文章

最新更新