0

Why can't I change the variable can_answer to False without getting this error? This is just some quick code I wrote.

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')
daniel
  • 73
  • 1
  • 6
  • For starters, `can_answer == 2 or 4:` is not doing what you think it is doing, that is equivalent to `can_answer == 2`, you need to use `can_answer == 2 or can_answer == 4`, in any case, what error are you getting exactly? I'm assuming an `UnboundLocal` error in `ans`? Well, you have to do the same thing you did in `question`. But you **shouldn't be relying on mutable global state to begin with**. That is an anti-pattern. There is a reason Python defaults to local – juanpa.arrivillaga Nov 13 '19 at 19:24
  • 1
    Also, to make this more complete on top of what was mentioned, can you show how you are calling all this? The code you are showing does not show how you are calling your methods in question. – idjaw Nov 13 '19 at 19:26
  • @toolic That's not really necessary, because it reads the variable before assigning it. So it uses the global variable automatically. – Barmar Nov 13 '19 at 19:27
  • thanks i think that worked sorry for being such a noob ): – daniel Nov 13 '19 at 19:41

1 Answers1

1

Use the global var before using the variable

In this case, guess you wrote wrong here

    if can_answer == 2 or 4:

Isn't 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')
Manualmsdos
  • 1,505
  • 3
  • 11
  • 22
Ramon Medeiros
  • 2,272
  • 2
  • 24
  • 41