Python Program to find Perfect Number

Vijaya Kumar Chinthala
3 min readOct 19, 2020

What is a perfect number?

Any number can be perfect number in Python, if the sum of its positive divisors excluding the number itself is equal to that number.

For example, 6 is a perfect number in Python because 6 is divisible by 1, 2, 3 and 6. So, the sum of these values are: 1+2+3 = 6 (Remember, we have to exclude the number itself. That’s why we haven’t added 6 here). Some of the perfect numbers are 6, 28, 496, 8128 and 33550336 so on

Python Program to find Perfect Number using For loop

Output:

Explanation:

From the above Python perfect number example

Let the user Entered value be: n = 6

First Iteration

For the first Iteration, n = 6, sum1 = 0 and i = 1

If (n% i == 0)
6 % 1 == 0

If statement is succeeded here So,

sum1 = sum1 + i
sum1 = 0 +1 = 1

Second Iteration

For the second Iteration the values of both Sum and i has been changed as: sum = 1 and i = 2

If (n% i == 0)
6 % 2 == 0

If statement is succeeded here So,

sum1 = sum1 + i
sum1 = 1 + 2 = 3

Third Iteration

For the third Iteration o this python perfect number program, the values of both Sum and i has been changed as: sum1 = 3 and i = 3

If (n % i == 0)
6 % 3 == 0

If statement is succeeded here So,

sum1 =sum1 + i
sum1 = 3 + 3 = 6

For the fourth and fifth iterations condition inside the if condition will fail

6 % 4 == 0 (FALSE)

6 % 5 == 0 (FALSE)

So, compiler will terminate the for loop.

In the next line we have If statement to check whether the value inside the Sum variable is exactly equal to given Number or Not.

If the condition (sum1 == n) is TRUE then below print statement will execute

The number is a perfect number

--

--