Python Practice › Loop Programs › Program 37
Perfect number check
Write a Python program to check whether a number is perfect: the sum of its factors (excluding itself) equals the number, like 28 = 1 + 2 + 4 + 7 + 14.
Input
28, 12
Output
28 is perfect 12 is not perfect (factor sum 16)
Approach
- Add every divisor smaller than n and compare.
Solution
for n in [28, 12]: total = 0 for d in range(1, n): if n % d == 0: total += d print(n, "is perfect" if total == n else f"is not perfect (factor sum {total})")Output
28 is perfect 12 is not perfect (factor sum 16)
Line by line
Line 3
Divisors are tested up to n – 1, so the number itself is excluded.
Learn the concept
New to this topic? Read the lesson, then come back.