Jure Štabuc Jure Štabuc - 1 year ago 80
Python Question

Python import own module - name not defined

I want to update my basic jumble game. I already did that the script gets words from a text file, now I want to separate them into modules as I have different text files with different words.

I have my main script, jumble_game.py:

import random
import amazement

#Welcome the player
Welcome to Word Jumble.
Unscramble the letters to make a word.

def wordlist(file):
with open(file) as afile:
global the_list
the_list = [word.strip(",") for line in afile for word in line.split()]

def main():
score = 0
for i in range(4):
word = random.choice(the_list)
theWord = word
jumble = ""
position = random.randrange(len(word))
print("The jumble word is: {}".format(jumble))

#Getting player's guess
guess = input("Enter your guess: ").lower()

#congratulate the player
print("Congratulations! You guessed it")
score +=1

print ("Sorry, wrong guess.")
print("You got {} out of 10".format(score))

#filename = "words/amazement_words.txt"

I want the file amazement.py to be imported into jumble_game.py because I want the user to select the group, from which the words will be chosen.


filename = "amazement_words.txt"

I get this error:

File "jumble_game.py", line 49, in <module>
NameError: name 'filename' is not defined

If I do it the other way, importing the main script into amazement.py and run the latter, the code functions without a problem.

Any clue what am I missing? Still a Python beginner so bear with me. :)

Thanks for help/suggestions!

Answer Source

The problem you've stated is a standard namespace/scope problem. You've created a variable within the scope of amazement.py, but not in the jumble_game.py namespace. As a result, you can't access the top level variable in amazement.py without telling your program from where to get that variable.

You can do a few things. I'll list two:


from amazement import filename

This will allow you to use the term "filename" as you've described.

or 2.

Replace any reference to filename with amazement.filename.

You can read more about scopes and namespace here: http://sebastianraschka.com/Articles/2014_python_scope_and_namespaces.html

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download