pythonOnlyPls
pythonOnlyPls

Reputation: 21

UnboundLocalError: local variable 'count' referenced before assignment

Throwing error at "count+=1". I tried making it a global etc. and it still gave an issue. It's more of a joke than anything, but I'd like to know why it isn't working.

import math
def delT():
    #inputs
    #float inputs
    #do math
    #print results
    global count
    count=0
    def getAndValidateNext():
        #print menu
        getNext=input("select something")
        acceptNext=["things","that","work"]
        while getNext not in acceptNext:
            count+=1
            print("Not a listed option.")
            if count==5:
                print("get good.")
                return
            return(getAndVadlidateNext())
        if getNext in nextRestart:
            print()
            return(delT())
        if getNext in nextExit:
            return
    getAndVadlidateNext()
delT()

Upvotes: 0

Views: 15439

Answers (3)

AGN Gazer
AGN Gazer

Reputation: 8388

global count should be inside the getAndValidateInput() function.

Upvotes: 1

SH7890
SH7890

Reputation: 555

You need to move your global keyword down into your function.

count=0
def getAndValidateInput():
    global count
    #print menu
    #So on and so forth

Now you should be able to access your count variable. It has to do with scoping in Python. You have to declare a variable is global in each function that you want to use it in, not just where it is define.

Upvotes: 4

Cary Shindell
Cary Shindell

Reputation: 1386

I ran into the same issue once, it turned out to have to do with the scope and having a function definition within another function definition. What worked was writing separate functions that would create and modify a global variable. Like this for example:

def setcount(x):
    global count
    count = x
def upcount():
    global count
    count += 1

Upvotes: 1

Related Questions