Python Program to Check Perfect Number

1. Introduction

In this tutorial, we will learn how to write a Python program to check if a number is a perfect number.

A perfect number is a number that is the sum of its proper divisors. The smallest perfect number is 6, which is the sum of 1, 2, and 3. Other perfect numbers are 28, 496, and 8128.

2. Program Steps

1. Define a number to check for being a perfect number.

2. Find all the divisors of the number.

3. Sum the divisors and compare the sum to the original number.

4. If the sum is equal to the original number, it is a perfect number.

5. Print the result.

3. Code Program

# Function to check if a number is a perfect number
def is_perfect_number(number):
    # Initialize the sum of divisors
    sum_of_divisors = 0
    # Find the divisors of number
    for i in range(1, number):
        if number % i == 0:
            sum_of_divisors += i
    # Check if the sum of divisors is equal to the number
    return sum_of_divisors == number

# Number to be checked
num_to_check = 28
# Check if the number is a perfect number and print the result
if is_perfect_number(num_to_check):
    print(f"{num_to_check} is a perfect number.")
else:
    print(f"{num_to_check} is not a perfect number.")

Output:

28 is a perfect number.

Explanation:

1. The function is_perfect_number accepts an integer number as its argument.

2. It initializes sum_of_divisors to 0 to accumulate the sum of the proper divisors of number.

3. A for loop iterates over all integers from 1 to number - 1, checking if each i is a divisor using the modulus operator number % i.

4. If i is a divisor, it is added to sum_of_divisors.

5. After the loop, the function compares sum_of_divisors to number. If they are equal, the function returns True, indicating that number is perfect.

6. The function is called with num_to_check set to 28, and based on the function's return value, a message is printed stating whether 28 is a perfect number.

7. The output confirms that 28 is a perfect number, as the sum of its divisors (1, 2, 4, 7, 14) equals 28.

Comments