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)

StackOverflow https://stackoverflow.com/questions/22139651

Question

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
Was it helpful?

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 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top