名称错误:未定义名称“linec”

2024-09-24 04:30:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我是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"

我做错什么了? 提前谢谢!在


Tags: textnameinforislinenotfile
3条回答

看起来你希望你的变量是全局变量,而不是函数内部的局部变量。您可以实际返回这些变量以创建新的全局变量:

def problem3_1(txtfilename):
    linec = 0
    wordct = 0     
    charct = 0

    text_file = open(txtfilename)

    for line in text_file:           
        linec = linec + 1
        charct = charct + len(line)
        for word in line.split():   
            wordct = wordct + 1

    text_file.close()
    return linec, wordct, charct

linex, wordct, charct = problem3_1("mytxtfile.txt")

最后,需要在for循环中添加字符计数。在

linec只存在于problem3_1()函数中。假设您打算调用函数并返回结果:

def problem3_1(txtfilename):
    linec = 0
    wordct = 0     
    charct = 0

    with open(txtfilename) as text_file:
        for line in text_file:           
            linec = linec + 1
            wordct += len(line.split())
            charct += len(line)

    return linec, wordct, charct

linec, wordct, charct = problem3_1("a_text_file.txt")
print(linec, wordct, charct)

我还添加了一个with以使用上下文管理器关闭文件。这样你就不会忘记关闭它,它是自动关闭的。在

这些变量只存在于函数内部。您可以使它们全局化,以便在函数外部打印,也可以在函数内部打印它们。在

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 ) 

相关问题 更多 >