Python Program to Check if a Number is a Perfect Number

A number is said to be a Perfect Number when that is equal to the sum of all its positive divisors except itself. When it is required to check if a number is a perfect number, a simple ‘for’ loop can be used.

Below is the demonstration of the same −


 Live Demo

n = 6
my_sum = 0
for i in range(1, n):
   if(n % i == 0):
      my_sum = my_sum + i
if (my_sum == n):
   print("The number is a perfect number")
   print("The number is not a perfect number")


The number is a perfect number


  • The value for ‘n’ is specified.

  • The sum is initialized to 0.

  • The number is iterated over, and the sum is incremented.

  • If this sum is equal to the previously defined ‘n’, it is considered a perfect number.

  • Relevant messages are displayed on the console.