Editor

Python Program to Check a Perfect Number

Beginner · Numbers · CBSE class 11 practical list

A perfect number is a positive whole number equal to the sum of its proper divisors, which are all its divisors except the number itself. For example, 28 is perfect because 1 + 2 + 4 + 7 + 14 = 28. This program finds the proper divisors of a number and checks whether they add up to it.

Program

perfect_number.py
num = 28 # or: num = int(input("Enter a number: "))
# Collect every number below num that divides it exactly
divisors = []
for i in range(1, num):
if num % i == 0:
divisors.append(i)
total = sum(divisors)
print(f"Proper divisors of {num}: {divisors}")
print(f"Sum of proper divisors: {total}")
if num > 0 and total == num:
print(num, "is a perfect number")
else:
print(num, "is not a perfect number")
Output
Proper divisors of 28: [1, 2, 4, 7, 14]
Sum of proper divisors: 28
28 is a perfect number

How it works

  1. The loop tries every number from 1 to num - 1 and keeps the ones where num % i == 0, which means i divides num with no remainder.
  2. sum(divisors) adds up all the proper divisors that were found.
  3. If that sum equals the number itself, the number is perfect.
  4. The num > 0 check stops 0 from being reported as perfect, since it has no proper divisors and their sum would also be 0.

Another way to write it

Find all perfect numbers up to 1000

Find all perfect numbers up to 1000
def is_perfect(n):
total = 0
for i in range(1, n // 2 + 1):
if n % i == 0:
total += i
return n > 1 and total == n
print("Perfect numbers up to 1000:")
for n in range(1, 1001):
if is_perfect(n):
print(n)
Output
Perfect numbers up to 1000:
6
28
496

No proper divisor can be bigger than half the number, so the function only checks up to n // 2, which halves the work.

Try it yourself

Set num to 6 and then to 12, and compare each divisor sum with the number.

Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.

All Python programs · CBSE class 12 practical file · Python exercises