简体   繁体   English

Python为什么我定义的函数(其输出是列表)不断收到nonetype错误

[英]Python why does my defined function which output is a list keep receiving nonetype error

I define a function which output is to print a list. 我定义了一个输出要打印列表的函数。 then i want to compare that list with len(l2) which is some other list in my code but i keep receiving this error that my defined function's output is a NoneType and it cant be compared with integers how can i solve this problem? 然后我想将该列表与代码中的其他列表len(l2)进行比较,但是我不断收到此错误,即我定义的函数的输出为NoneType,并且无法与整数进行比较,我该如何解决此问题? Im new to programming so please answer simply 我是编程新手,请简单回答

l = []
for i in range(0, 3):
    x = int(input())
    l.append(x)
def prime_counter(n):
    b = 1
    l1 = []
    while b <= n:
        k = 0
        if n % b == 0:
            j = 1
            while j <= b:
                if b % j == 0:
                    k = k + 1
                j = j + 1
            if k == 2:
                l1.append(b)
        b = b + 1
for i in range(0, len(l)):
    l2 = []
    if len(prime_counter(l[i])) > len(l2):
        l2.extend(prime_counter(l[i]))
print(l2)

When you don't have any return statement in a function, None is returned automatically. 当函数中None任何return语句时,将自动返回None So, you need to return some object from a function that the caller of the function can use further. 因此,您需要从函数中返回一些对象,该函数的调用者可以进一步使用该对象。

This is happening in your prime_counter function; 这是在您的prime_counter函数中发生的; you're supposed to return the l1 list from it but you're returning nothing warranting len(None) which would error out as None singleton does not have any length associated with it. 你应该返还l1从中名单,但你回来什么warranting len(None)这会出错误的None单没有任何相关的长度。

You need to return the l1 list from prime_counter : 您需要从prime_counter返回l1列表:

def prime_counter(n):
    b = 1
    l1 = []
    while b <= n:
        ...
        ...
    return l1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM