私はいくつかのコードを持っていますが、変数をグローバルとして割り当てましたが、別の関数で変数を検証として使用しようとすると例外がスローされます。割り当て前にローカル変数が参照されていますが、変数がグローバルです
これは未完成のコードです(私はそれが現時点では適切に動作しないことを知っていますが、私はこれを最初に修正したいと思っています)。私の目的を達成するためにはるかに効率的ですが、なぜこれが機能していないのかを理解する。
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()
「グローバル回答」のため、[this](http://stackoverflow.com/questions/8943933/variables-declared-outside-function?noredirect=1&lq=1)を参照してください。 – malatesh