0

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()
pythonOnlyPls
  • 21
  • 1
  • 1
  • 4
  • full traceback please. The function isn't called if my eyes see right... – Jean-François Fabre Jul 18 '17 at 20:37
  • What's `getAndVadlidateNext`? – user2357112 Jul 18 '17 at 20:38
  • 1
    Possible duplicate of [Python nested functions variable scoping](https://stackoverflow.com/questions/5218895/python-nested-functions-variable-scoping) – janos Jul 18 '17 at 20:40
  • So many typos in your post! Did you type it from scratch here? Wasn't copy/paste available? I.e., your function was defined as getAndValidate**Input** but you call it (I hope) as getAndVa**d**lidate**Next**! – AGN Gazer Jul 18 '17 at 20:46
  • Commented out sections because of what I'm working on. getAndValidateNext is the correct function name, fixed post. Sorry about typos, I just made the account and haven't posted before so the formatting was weird at first with ctrl+k etc. so yes I was writing it out for the first half. issue fixed, though – pythonOnlyPls Jul 18 '17 at 20:51

3 Answers3

4

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.

SH7890
  • 545
  • 2
  • 7
  • 20
  • ah duh. I just added it and it works properly. had to declare it as a global in getAndValidateNext and as a global where I defined it as 0. solved, thanks! – pythonOnlyPls Jul 18 '17 at 20:47
1

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
Cary Shindell
  • 1,336
  • 8
  • 25
1

global count should be inside the getAndValidateInput() function.

AGN Gazer
  • 8,025
  • 2
  • 27
  • 45