首页 > 解决方案 > 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')

标签: pythonglobal-variableslocal-variables

解决方案


在使用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')

推荐阅读