0

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!

  • I don't really see the point of using those functions. Easiest way to solve the problem would be to get rid of them altogether. – anon582847382 May 12 '14 at 18:03
  • `LettersIntoCode` should return `WordsWithChanges`, so that this value can used in the caller. – Daniel May 12 '14 at 18:04

2 Answers2

0

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.

La-comadreja
  • 5,627
  • 11
  • 36
  • 64
0

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.

anon582847382
  • 19,907
  • 5
  • 54
  • 57
  • This isn't really doing much good as when I type 'var = WordsWithChanges' it claims that WordsWithChages is not defined? – user3495049 May 12 '14 at 18:24
  • @user3495049 It looks like the latter option may be too difficult to implement for know. Use the first option for a fix, and then start dealing with that sort of thing when the program is fully working. – anon582847382 May 12 '14 at 18:26