Jure Štabuc Jure Štabuc - 26 days ago 21
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
print("""
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()]
print(the_list)

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

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

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

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

#filename = "words/amazement_words.txt"
wordlist(filename)
main()


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.

amazement.py:

filename = "amazement_words.txt"


I get this error:

File "jumble_game.py", line 49, in <module>
wordlist(filename)
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

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:

1.

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

Comments