Python function to check whether a number is perfect or not

Method 1: Using for loop

def check_perfect_number(num):
    sum = 0
    for i in range(1, num):
        if n % i == 0:
            sum += i
    return sum == num

n = int(input("Enter the number you want to check whether it is a perfect number or not: "))
print(check_perfect_number(n))

Output:

Enter the number you want to check whether it is a perfect number or not: 28
True

Explanation:

This first method is to use a for loop to iterate through all the divisors of the number and evaluates if the sum of the divisors is equal to the number itself. The Divisor of 28 is 1,2,4,7,14 and the Sum of the divisor is 1+2+4+7+14=28 thus, 28 is a perfect number.

Method 2:  Using a while loop

    if sum(divisors) == num:
        return True
    else:
        return False

n = int(input("Enter the number you want to check whether it is perfect number or not: "))
print( check_perfect_number(n))

Explanation:

Another approach is to search for divisors and add them to a list using a while loop. After the loop is complete, we determine whether the number itself and the sum of its divisors equal each other.

Method 3: Using list comprehension

def check_perfect_number(num):
    divisors = [i for i in range(1, num) if num % i == 0]
    if sum(divisors) == num:
        return True
    else:
        return False

n = int(input("Enter the number you want to check whether it is perfect number or not: "))
print(check_perfect_number(n))

Explanation:

Using list comprehension to search for divisors and add them to a list in one line is a shorter way. Then, determine whether the number itself equals the sum of the divisors.

Here is the end of our article on Python functions to check whether a number is perfect or not. We saw in total three methods i.e using for loop, while loop, and the concept of list comprehension.

Share:
Avatar of Dhvanil V

Author: Dhvanil V

Leave a Reply

Your email address will not be published. Required fields are marked *