Zed-King Institute

    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

    1. 1Loop d from 1 to n − 1.
    2. 2Whenever n % d == 0, d is a divisor — add it to total.
    3. 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.

    Faster: check divisors only up to n // 2

    No number has a divisor bigger than its half (other than itself), so the loop can stop at n // 2. For 8128 that is half the work.

    program.py

    n = int(input())
    total = 0
    for d in range(1, n // 2 + 1):
        if n % d == 0:
            total += d
    if total == n:
        print(n, "is a perfect number")
    else:
        print(n, "is not a perfect number")

    Input

    28

    Output

    28 is a perfect number

    Print all perfect numbers from 1 to 1000 using a function

    Move the check into a function that returns True or False, then call it for every number in the range.

    program.py

    def is_perfect(n):
        total = 0
        for d in range(1, n):
            if n % d == 0:
                total += d
        return total == n
    
    for n in range(1, 1001):
        if is_perfect(n):
            print(n)

    Input

    (no input)

    Output

    6
    28
    496

    Questions students ask

    What is a perfect number in Python?
    A perfect number is equal to the sum of its divisors, leaving out the number itself. 28 is perfect because 1 + 2 + 4 + 7 + 14 = 28. In Python you find the divisors with n % d == 0 inside a loop and add them up.
    What are the first four perfect numbers?
    6, 28, 496 and 8128. The next one is 33,550,336, which is why exam questions never go past 8128.
    Is 1 a perfect number?
    No. 1 has no divisor other than itself, so the sum is 0, and 0 is not equal to 1. The program on this page prints "1 is not a perfect number".

    Now solve a similar question yourself

    A new Python question every time, checked instantly.

    Practice questions

    Preparing for NIELIT O Level?

    This program is the kind asked in the M3 (Python) theory paper and the PR-3 practical exam.

    More in Loops