我是python新手。我试图运行下面的函数,但它显示错误“NameError:name'linec'is not defined”。我不明白如何解决这个问题。在
以下是我的职能:
def problem3_1(txtfilename):
linec = 0
wordct = 0
charct = 0
text_file = open(txtfilename)
for line in text_file:
linec = linec + 1
for word in line.split():
wordct = wordct + 1
charct = charct + len(line)
text_file.close()
print(linec, wordct, charct ) # "NameError: name 'linec' is not defined"
我做错什么了? 提前谢谢!在
看起来你希望你的变量是全局变量,而不是函数内部的局部变量。您可以实际返回这些变量以创建新的全局变量:
最后,需要在for循环中添加字符计数。在
linec
只存在于problem3_1()
函数中。假设您打算调用函数并返回结果:我还添加了一个
with
以使用上下文管理器关闭文件。这样你就不会忘记关闭它,它是自动关闭的。在这些变量只存在于函数内部。您可以使它们全局化,以便在函数外部打印,也可以在函数内部打印它们。在
相关问题 更多 >
编程相关推荐