My program contains a variable which is created locally but which I want to use in another function, is there anyway I can do this? [duplicate]

StackOverflow https://stackoverflow.com/questions/23615762

Question

My program contains quite a lot so I'm not going to bore you with the details, if there are any other problems that you spot which I haven't, you don't need to point them out unless you have a serious case of OCD. Here is the parts of the program relevant to the question I'm asking.

def LettersIntoCode():
    cluesFile = open("clues.txt", 'r+')
    cluesLines = cluesFile.readlines()
    cluesFile.close()
    clues = {}
    for line in cluesLines:
        clues[line[1]] = line[0]
    CodedFile = open('words.txt')
    print()
    for line in CodedFile:
        ***WordsWithChanges = (''.join(clues.get(c,c) for c in line.strip('\r\n')))***
        print(WordsWithChanges)
    CodedFile.close()

def GameCompletion():
    SolvedFile = open("solved.txt", 'r')
    ***while WordsWithChanges != SolvedFile***:
        MenuChoice()
    SolvedFile.close()

When called upon this error pops up:

    while WordsWithChanges != SolvedFile:
NameError: global name 'WordsWithChanges' is not defined

Now don't worry about anything else but the Bold and Italic although you may find the other stuff useful for understanding purposes. I've tried putting inglobal WordsWithChanges but as most will know that didn't work, thanks for your co-operation, if you need anything just ask!

Était-ce utile?

La solution

For a quick-and-dirty fix you could use a global declaration when defining the original variable:

global WordsWithChanges

But that is considered very bad practice and I would not recommend it.


To really fix your problem: This is occurring because if you create a variable in a scope, it is only available in that scope. Therefore a variable can be locally but not globally defined. As I said in my comment, this indicates you should probably rethink the program logic.

Autres conseils

If you want to avoid making the variable global, what you can do is return it from the original function and call that function in the 2nd function you want to use it in, setting a new variable equal to the return value.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top