Python Program to Check Perfect Number
hardLoopsPython
A perfect number equals the sum of its divisors other than itself: 6, 28, 496, 8128.
The question
Read a positive integer and print whether it is a perfect number: equal to the sum of its divisors other than itself (6 = 1 + 2 + 3).
The code
program.py
n = int(input())
total = 0
for d in range(1, n):
if n % d == 0:
total += d
if total == n:
print(n, "is a perfect number")
else:
print(n, "is not a perfect number")Input
12
Output
12 is not a perfect number
How it works
- 1Loop d from 1 to n − 1.
- 2Whenever n % d == 0, d is a divisor — add it to total.
- 3If total equals n, the number is perfect.
Common mistakes
- Including n itself in the loop (range(1, n + 1)), which doubles the total.
- Starting total at 1 and the loop at 1, which counts 1 twice.
Now solve a similar question yourself
A new Python question every time, checked instantly.
