[英]Import Python module 'NameError: name 'contact' is not defined' error
[英]Python import own module - name not defined
我想更新我的基本游戲。 我已經做過腳本從文本文件中獲取單詞的操作,現在我想將它們分為模塊,因為我有不同的文本文件和不同的單詞。
我有我的主要腳本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()
我希望將文件amazement.py導入jumble_game.py,因為我希望用戶選擇從中選擇單詞的組。
amazement.py:
filename = "amazement_words.txt"
我收到此錯誤:
File "jumble_game.py", line 49, in <module>
wordlist(filename)
NameError: name 'filename' is not defined
如果我以另一種方式執行此操作,則將主腳本導入amazement.py並運行后者,則代碼可以正常運行。
任何線索我想念什么? 還是Python初學者,所以請多多包涵。 :)
感謝您的幫助/建議!
您所說的問題是標准的名稱空間/范圍問題。 您已經在amazement.py范圍內創建了一個變量,但沒有在jumble_game.py命名空間中創建了一個變量。 結果,如果不告訴程序從何處獲取該變量,就無法訪問amazement.py中的頂級變量。
您可以做幾件事。 我將列出兩個:
1。
from amazement import filename
如前所述,這將允許您使用術語“文件名”。
或2。
將所有對filename
引用替換為amazement.filename
。
您可以在此處閱讀有關范圍和名稱空間的更多信息: http : //sebastianraschka.com/Articles/2014_python_scope_and_namespaces.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.