简体   繁体   中英

TypeError: unsupported operand type(s) for -: 'NoneType' and 'int'

I am trying to write a function called aliquot_chain which takes as its argument a starting value a and a number of iterations n , both non-negative integers. It should return a list of length n+1 , starting with a , where each number in the list (starting from the second) is the sum of the factors of the previous number not including that number itself.

I am keeping get this message:

unsupported operand type(s) for -: 'NoneType' and 'int'.

Can anyone explain what this mean and how I can fix my code? (I am required to use while True in the aliquot_chain function.)

def factor_sum(a):
    s=0
    if a==0:
        return s
    else:
        if a%(a**0.5)==0:
            k=int((a)**0.5)
            s+=k
        else:
            k=int((a)**0.5)+1
        for n in range(1,k):
            if a%n==0:
                s +=n
                s +=int(a/n)
def aliquot_chain(a):
    l=[a]
    while True:
        l.append(factor_sum(l[-1])-l[-1])
        if len(set(l))!=len(l):
            del l[-1]
            return l
        
print(aliquot_chain(28))

Factor_sum doesn't return anything if the if a==0 evaluates to false, so it returns None, which is why you try to do None-something

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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