python的模块名称老是忘记_Python导入自己的模块-名称未定义

博主在尝试将Python游戏脚本拆分为模块,以便从不同文本文件中选择单词。遇到的问题是尝试在主脚本中调用`wordlist()`函数时出现`NameError`,提示`filename`未定义。当主脚本导入到amazement.py并运行后者时,代码能正常工作。博主寻求关于如何正确导入和使用文件名变量的指导。
摘要由CSDN通过智能技术生成

我想更新我的基本游戏。我已经做过脚本从文本文件中获取单词的操作,现在我想将它们分成模块,因为我有不同的文本文件和不同的单词。

我有我的主要脚本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

wordlist(filename)

NameError: name 'filename' is not defined

如果我以另一种方式执行此操作,则将主脚本导入amazement.py并运行后者,则代码可以正常运行。

任何线索我想念什么?还是Python初学者,所以请多多包涵。:)

感谢您的帮助/建议!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值