为什么我的代码说未定义名称“ count”

时间:2020-05-09 23:55:38

标签: python python-3.x function

words = input("Text: ")

def l_creator():
    count_char()
    count_sentences()
    print((count / sentence) * 100)

def count_char():
    count = 0
    for i in words:
        if i != ' ':
            count += 1  #number of words
    return count

def count_sentences():
    for i in words:
        a = words.split(' ') #number of sentences
    sentence = len(a) * 100
    return sentence


l_creator()

为什么此代码不起作用?我尝试在其他形式的代码中使用关键字Global,并且尝试了多种形式的代码适应性,但似乎无法正确实现。

这是在函数内部调用函数的正确形式吗?

终端提示:

File "read.py", line 32, in <module>
    l_creator()
  File "read.py", line 14, in l_creator
    count_char(count)
NameError: name 'count' is not defined

1 个答案:

答案 0 :(得分:0)

另一种解决方案是在代码中添加两行: 添加到:count_char():

global count

和count_sentences():

global sentence

Nb:在这种情况下,您不需要从函数中“返回”任何东西。