user9958601
user9958601

Reputation:

Python variable not defined error in math solver program

So I have some code which is supposed to be a math problem solver. In my full code, I have 20 problems, but I have included only 4 here as an example. It also has a point tracker, but there's a problem. Whenever I try to answer and it tells me if it's right or wrong, it sends an error.

Code:

from time import sleep
print('Math Solver\n')
print('You will be solving a series of math problems.')
def start():
    points = 0
    print('LET\'S BEGIN!')
def correct():
    print('Correct')
    points = points + 1
    sleep(2)
def wrong():
    print('Wrong')
    points = points - 1
    sleep(2)
start()
q1 = input("6+2?")
if q1 == "8":
    correct()
else:
    wrong()

q2 = input("10x3?")
if q2 == "30":
    correct()
else:
    wrong()

q3 = input("24-17?")
if q1 == "7":
    correct()
else:
    wrong()

q4 = input("54/6?")
if q1 == "9":
    correct()
else:
    wrong()

print('Game Over')
print('Your score was: ' + points)

Error:

Traceback (most recent call last):
  File "/home/pi/Documents/script.py", line 18, in <module>
    correct()
  File "/home/pi/Documents/script.py", line 9, in correct
    points = points + 1
UnboundLocalError: local variable 'points' referenced before assignment

Upvotes: 0

Views: 51

Answers (1)

Simas Joneliunas
Simas Joneliunas

Reputation: 3118

You are declaring points variable in a local scope:

def func1(): 
    points = 0
def func2():
    print(points) 
func1()
func2()  #error

Local scope means that the variable only exists within your defined function def name() and no other functions know about it. Thus when you try to call the variable from another function you get an error. for all code to have access to your points variable, you need to declare it in a global scope (outside and def func() calls). Then you can use this variable points in your function by calling global points:

points = 0

def func1():
    global points
    print(points) # 0
    points = 1
    print(points) # 1

def func2():
    global points
    print(points) # 1

func1() #prints 0 then 1
func2() #prints 1

Upvotes: 1

Related Questions