1

I have some code and I have assigned a variable as global but when trying to use the variable as validation in a separate function, it throws an exception.

This is the unfinished code (I know it won't work properly at the moment but I want to fix this first) for some school homework, I know there are probably much more efficient was to achieve my purpose but I want to understand why this isn't working.

def mainFunc():
    nameList = []
    print("1. Add name \n2. Display list \n3. Quit\n")
    choice = displayMenu()
    if choice == 1:
       addName()

    elif choice == 2:
    displayList()

    else:
        print("Program Terminating")

def displayMenu():
    global answer
    answer = int(input("Please enter your choice: "))
    answerCheck()

def answerCheck():
    if answer == 1 or answer == 2 or answer == 3:
        return(answer)
    else:
        answer = input("Invalid selection, please re-enter: ")
        answerCheck()

def addName():
    position = int(input("Please enter the position of the name: "))
    name = input("Please enter the name you wish to add: ")
    remove = nameList[position-1]
    nameList.remove(remove)
    nameList.add(name,position)
    print(nameList)



mainFunc()
Brownie
  • 13
  • 3
  • because of `global answer` see [this](http://stackoverflow.com/questions/8943933/variables-declared-outside-function?noredirect=1&lq=1) – Malatesh Oct 19 '16 at 10:01

1 Answers1

1

Python treats your variable answer as a local variable as in your answerCheck() function, under the else clause, there is an assignment done to the variable answer. Since there is an assignment involved within the local scope, python treats the variable to be in the local scope and this gives your issue. As long as you don't use assignment within your function, the global variable will be read.

You can test this by commenting out the line answer = input("Invalid selection, please re-enter: ") and calling the function. It should work fine.

In order to get your code to work, let python know that you are referencing the global variable using global answer in your answerCheck() function.

Ashan
  • 317
  • 1
  • 10