pythonfunctionperfect-numbers

Perfect numbers program python


I'm taking an intro course for python, and in one excercise we are to write a function where we type in a number and return bool True or False, if the number is a perfect number. Then we are to create another function that takes an upperlimit and will check every number up until that limit and if it is a perfect number, to print the perfect number. As of now my problem is with the 2nd half of this excersie, and instead of printing out the perfect number, it will print out how many there are with "True". Again the first function IS suppouse to return True or False, so I'm not sure how we can get the 2nd function to print out the actual number!

def perfect(num):
    x=1
    adding=0
    while x<num:
        if num % x == 0:
            adding=adding+x
        x=x+1

    if adding==num:
        #print(num)
        return (adding==num)
    else:
        return False

def perfectList(upperlimit):
    x=1
    while x<upperlimit:
        if perfect(x)==True:
            print(perfect(x))
        x=x+1

Solution

  • Your second function is very close.

    def perfectList(upperlimit):
        x=1
        while x < upperlimit:
            if perfect(x)==True:
                print(x) # changed from print(perfect(x))
            x=x+1
    

    you just needed to change to print(x) (the number) not print(perfect(x)) , which returns whether the number is a perfect number.