Python 为什么我的代码中没有定义名称“count”

Python 为什么我的代码中没有定义名称“count”,python,python-3.x,function,Python,Python 3.x,Function,为什么这个代码不起作用?我曾尝试在其他形式的代码中使用关键字Global,我也尝试过对代码进行多种调整,但似乎都做不好 这是调用函数内部函数的正确形式吗 终端提示: words = input("Text: ") def l_creator(): count_char() count_sentences() print((count / sentence) * 100) def count_char(): count = 0 for i in word

为什么这个代码不起作用?我曾尝试在其他形式的代码中使用关键字Global,我也尝试过对代码进行多种调整,但似乎都做不好

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

终端提示:

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()

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

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
数一数句子:

global count

注意:在这种情况下,您不需要从函数中返回任何内容。

您需要将函数调用的返回保存为一个变量,如count=count\u char和句子=count\u sentences,然后只需除以count/句子即可。值得注意的是,count\u char函数中的count对于l\u creator函数来说并不存在,它不是一个全局变量,它是函数本身的局部变量,因此如果不将它分配给l_creator函数中的变量,它将无法工作。
global sentence