Search code examples
pythonfunctioncompiler-errorsglobal-variables

Why is python giving me an UnboundLocalError when I run this program?


Background

I am currently experimenting with computer learning, and I made a function where you enter "true" or "false" and the computer learns which boolean it is, after which the program prints the percent of correct guesses the computer made:

import math
import random
endgame = False
def oneround():
    Q1max = 1
    Q1min = -2
    guess = False
    answer = 0
    while guess == False:
        useranswer = input("True or False?")
        if useranswer == "True" or useranswer == "true":
            answer = True
            guess = True
        elif useranswer == "False" or useranswer == "false":
            answer = False
            guess = True
        
    corrects = 0
    incorrects = 0 
    howmanytimes = int(input("how many times do you want the computer to guess? (If you want to end the game, type in letters instead of a number.) "))
    for x in range(0,howmanytimes):
        choice = random.randint(Q1min,Q1max)
        if choice >= 0:
            guess = True
        else:
            guess = False
        if guess == answer:
            corrects += 1
            if guess == True:
                Q1max += 1
            else:
                Q1min -= 1
        else:
            incorrects += 1
            if guess == False:
                Q1max += 1
            else:
                Q1min -= 1
    percent = (corrects/howmanytimes)*100
    print ("The computer learned to guess correctly",(str(math.floor(percent))+"%"),"of the time.")
while endgame == False:
    try:
        oneround()
    except ValueError:
        endgame = True

I then tried to improve my program by adding 2 global variables, percentavg and percentavgnum, that will average all the success percentages together at the end of the program:

import math
import random
endgame = False
global percentavg
global percentavgnum
percentavg = 0
percentavgnum = 0
def oneround():
    Q1max = 1
    Q1min = -2
    guess = False
    answer = 0
    while guess == False:
        useranswer = input("True or False?")
        if useranswer == "True" or useranswer == "true":
            answer = True
            guess = True
        elif useranswer == "False" or useranswer == "false":
            answer = False
            guess = True
        
    corrects = 0
    incorrects = 0 
    howmanytimes = int(input("how many times do you want the computer to guess? (If you want to end the game, type in letters instead of a number.) "))
    for x in range(0,howmanytimes):
        choice = random.randint(Q1min,Q1max)
        if choice >= 0:
            guess = True
        else:
            guess = False
        if guess == answer:
            corrects += 1
            if guess == True:
                Q1max += 1
            else:
                Q1min -= 1
        else:
            incorrects += 1
            if guess == False:
                Q1max += 1
            else:
                Q1min -= 1
    percent = (corrects/howmanytimes)*100
    percentavg += percent
    percentavgnum += 1
    print ("The computer learned to guess correctly",(str(math.floor(percent))+"%"),"of the time.")
while endgame == False:
    try:
        oneround()
    except ValueError:
        endgame = True
print ("The computer guessed correctly",(str(math.floor(percentavg/percentavgnum))+"%"),"of the time")

Problem

But I keep getting this error whenever I run the program:

Traceback (most recent call last):
  File "main.py", line 49, in <module>
    oneround()
  File "main.py", line 44, in oneround
    percentavg += percent
UnboundLocalError: local variable 'percentavg' referenced before assignment

Does anyone know what I am doing wrong?


Solution

  • Use global. Put it at the top of the function with the variable names after it. Like this: global percentavg, percentavgnum
    NOTE: The names must be comma-separated.