我想更新我的基本混乱游戏.我已经这样做了脚本从文本文件中获取单词,现在我想将它们分成模块,因为我有不同的文本文件.
我有我的主脚本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()
Run Code Online (Sandbox Code Playgroud)
我希望将文件amazement.py导入到jumble_game.py中,因为我希望用户选择将从中选择单词的组.
amazement.py:
filename = "amazement_words.txt"
Run Code Online (Sandbox Code Playgroud)
我收到此错误:
File "jumble_game.py", line 49, in <module>
wordlist(filename)
NameError: name 'filename' is not defined
Run Code Online (Sandbox Code Playgroud)
如果我以另一种方式执行,将主脚本导入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
| 归档时间: |
|
| 查看次数: |
4366 次 |
| 最近记录: |