Founding Batch Offer · HLD · LLD · System Design at ₹799 until 30 Nov

Check Perfect Number in Python

Add the proper divisors of 6 and recover 6 with Python. A beginner number-property lesson excludes the input itself and tests the often-missed value one.

BeginnerConditional ProgramsExample 10 of 20
check-perfect-number.py
1# Program to check perfect number
2
3num = int(input("Enter a positive integer: "))
4
5if num <= 0:
6 print("Number must be positive.")
7else:
8 total = 0
9 for i in range(1, num):
10 if num % i == 0:
11 total += i
12
13 if total == num:
14 print(num, "is a perfect number")
15 else:
16 print(num, "is not a perfect number")

Output

6 is a perfect number

1 + 2 + 3 equals 6, so the perfect-number test succeeds.

In this one

  • Define proper divisors
  • Use an exclusive range endpoint
  • Compare a divisor sum with the input

How it works

  1. 1

    Reject num <= 0.

  2. 2

    Test each integer from 1 to num - 1 and add exact divisors.

  3. 3

    Compare total == num and print the selected result.

Edge cases

One

Enter 1.

There are no positive proper divisors, so the sum is zero and it fails.

Non-positive input

Enter 0.

The guard prints that the number must be positive.

What's going on

A perfect number equals the sum of its proper positive divisors. Proper means leave out the number itself. For 6, those divisors are 1, 2, and 3, and their sum is 6.

range(1, num) starts at one and stops before num. Each zero remainder identifies a divisor, which is added to total. Including num in that range would change the definition and make the comparison wrong.

The positive-input guard comes before the loop. For 1 the range is empty, total stays zero, and it does not qualify. Testing every smaller integer is easy to follow but slow for large inputs; factor pairs can later reduce the search to a square-root boundary.

After this program

If the idea is still fuzzy, read Day 8: Conditional Statements in the Python course. For a short check, try the Python quiz (300 questions). Stay with all 20 conditional programs, or see every topic on Python exercises.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

Why does range stop before num?

Pick an answer to check it.

Question 2

Why does 6 qualify?

Pick an answer to check it.

Questions people ask

Why does range stop before num?

Proper divisors exclude the number itself, so num must not be added.

Why does 6 qualify?

Its proper divisors 1, 2, and 3 add up to 6.

Is this approach efficient for very large inputs?

No. It tries every smaller positive integer, so the number of tests grows with num.