Search code examples
loopsfor-loopiterationperfect-numbers

I need help generating a list of perfect numbers like 6,28, and 496. (My for-loop is a bit off in my second function)


I know my first function is correct and that it can validate a perfect number (i.e. 6, 28, 496). However, I'm struggling printing a list of perfect numbers. Meaning if I call listPerfect(500), I can't list the numbers 6,28, and 496. What am I missing?

Thank you for looking at my problem.

def perfect(n):
    x=0
    for i in range(1,n):
        if n%i==0:
            x+=i
        else:
            x=x
    if x==n:
        return True
    else:
        return False


def listPerfects(n):

    for i in range(1,n+1):

        if i == perfect(n):
            print(i)
        else:
            i=i

Solution

  • perfect(i) is returning True/False and you are comparing it with i.

    change it to

    if i == perfect(n): # Remove this 
    
    if perfect(i): #it should work