What is a Perfect Number in Python? Exploring the Concept and Python Program to Find Them
By Rohit Sharma
Updated on Oct 10, 2025 | 26 min read | 14.26K+ views
Share:
For working professionals
For fresh graduates
More
By Rohit Sharma
Updated on Oct 10, 2025 | 26 min read | 14.26K+ views
Share:
Table of Contents
A perfect number in Python is a number that equals the sum of all its proper divisors, excluding itself. For example, 6 is perfect because its divisors 1, 2, and 3 add up to 6. This concept, rooted in mathematics, is often used in coding challenges to test logic and problem-solving skills. Python makes it simple to check whether a number is perfect through loops, conditions, and functions.
In this guide, you’ll read more about what makes a number perfect, how the logic works, and different Python programs to find them. You’ll also explore function-based, loop-based, and recursive methods, advanced techniques like list comprehension, performance comparisons, and real-world examples to practice and master this concept.
Want to secure a high-paying career in data science? Enroll in upGrad’s industry-aligned Data Science Courses to advance your career in 2025!
Popular Data Science Programs
A perfect number in Python is a number that equals the sum of all its proper divisors (excluding itself).
To find one, you can break the problem into small, simple steps. Let’s go through each step with examples and outputs.
Start by asking the user for a number and then find its divisors using a for loop.
A divisor is any number that divides the given number completely (remainder = 0).
Code:
num = int(input("Enter a number: "))
divisors = []
for i in range(1, num):
if num % i == 0:
divisors.append(i)
print("Divisors:", divisors)
Example Input:
Enter a number: 6
Output:
Divisors: [1, 2, 3]
Explanation:
The numbers 1, 2, and 3 divide 6 evenly. These are its proper divisors.
Once you have the divisors, add them up using Python’s built-in sum() function.
Code:
sum_of_divisors = sum(divisors)
print("Sum of divisors:", sum_of_divisors)
Output:
Sum of divisors: 6
Explanation:
1 + 2 + 3 = 6, which is equal to the original number.
Also Read: Python In-Built Function [With Syntax and Examples]
Now, compare the sum of divisors with the original number.
If both are equal, it’s a perfect number.
Code:
if sum_of_divisors == num:
print(num, "is a perfect number")
else:
print(num, "is not a perfect number")
Output:
6 is a perfect number
Explanation:
Since the sum equals the number itself, 6 is perfect.
Also Read: Top 48 Machine Learning Projects [2025 Edition] with Source Code
Let’s put all the steps together into one complete script.
Code:
num = int(input("Enter a number: "))
divisors = []
for i in range(1, num):
if num % i == 0:
divisors.append(i)
print("Divisors:", divisors)
print("Sum of divisors:", sum(divisors))
if sum(divisors) == num:
print(num, "is a perfect number")
else:
print(num, "is not a perfect number")
Example Input:
Enter a number: 28
Output:
Divisors: [1, 2, 4, 7, 14]
Sum of divisors: 28
28 is a perfect number
Explanation:
When you add up all the divisors of 28, you get 28. That’s why it’s a perfect number.
Input Number |
Divisors |
Sum of Divisors |
Perfect Number? |
6 | 1, 2, 3 | 6 | Yes |
10 | 1, 2, 5 | 8 | No |
28 | 1, 2, 4, 7, 14 | 28 | Yes |
12 | 1, 2, 3, 4, 6 | 16 | No |
Here’s how the logic flows:
Start
↓
Input a number
↓
Find all divisors
↓
Add them up
↓
Compare with the original number
↓
If equal → Perfect number
Else → Not perfect
↓
End
This foundational logic can be extended to check perfect numbers within a range or using functions and recursion.
Also Read: Top 36+ Python Projects for Beginners and Students to Explore in 2025
Using functions in Python makes your program cleaner, reusable, and easier to test.
Instead of writing the same code repeatedly, you can define a function that checks whether a number is perfect and then call it whenever needed.
Let’s see how you can create a perfect number program in Python using functions step by step.
Start by defining a function named is_perfect_number() that takes a number as an argument.
Inside the function, you’ll calculate the sum of all divisors and compare it with the original number.
Code:
def is_perfect_number(num):
divisors = []
for i in range(1, num):
if num % i == 0:
divisors.append(i)
return sum(divisors) == num
Explanation:
2. Calling the Function
You can now call the function with any number and print the result.
Code:
number = int(input("Enter a number: "))
if is_perfect_number(number):
print(number, "is a perfect number")
else:
print(number, "is not a perfect number")
Example Input:
Enter a number: 6
Output:
6 is a perfect number
Explanation:
The divisors of 6 are [1, 2, 3], and their sum equals 6.
The function returns True, so the message confirms it’s a perfect number.
Also Read: How to Call a Function in Python?
You can also use the same function to check multiple numbers in a loop.
This shows the advantage of writing reusable functions.
Code:
for n in range(1, 31):
if is_perfect_number(n):
print(n, "is a perfect number")
Output:
6 is a perfect number
28 is a perfect number
Explanation:
The program loops from 1 to 30, checks each number, and prints the perfect ones.
4. Function-Based Program Summary
Step |
Action |
Purpose |
1 | Define the function is_perfect_number() | Encapsulates the logic |
2 | Use a loop to find divisors | Identifies factors |
3 | Sum and compare divisors | Checks the condition |
4 | Call the function | Reuses the code easily |
Define function → Input a number → Find divisors → Sum divisors → Return True/False → Print result
By using functions, you make your perfect number program in Python more structured and maintainable.
This approach forms a strong base for building advanced versions, such as using recursion or checking perfect numbers within a range.
Also Read: Most Important Python Functions [With Examples] | Types of Functions
Data Science Courses to upskill
Explore Data Science Courses for Career Progression
Using a while loop to check for perfect numbers in Python is another approach that beginners can try.
It works similarly to a for loop but gives you more control over the loop counter and conditions.
This section will show you how to write a perfect number program in Python using while loop with clear examples and outputs.
Start by taking input from the user and initializing variables:
Code:
num = int(input("Enter a number: "))
i = 1
sum_of_divisors = 0
Example Input:
Enter a number: 28
2. Finding Divisors Using While Loop
Use a while loop to check each number from 1 to num - 1.
Add the number to sum_of_divisors if it divides num completely.
Code:
while i < num:
if num % i == 0:
sum_of_divisors += i
i += 1
print("Sum of divisors:", sum_of_divisors)
Output:
Sum of divisors: 28
Explanation:
The loop checks every number less than 28 and sums the divisors: 1 + 2 + 4 + 7 + 14 = 28.
After calculating the sum of divisors, compare it with the original number.
Code:
if sum_of_divisors == num:
print(num, "is a perfect number")
else:
print(num, "is not a perfect number")
Output:
28 is a perfect number
Explanation:
Since the sum equals 28, the program correctly identifies it as a perfect number.
Also Read: Master Python While Loop Syntax with These Easy Examples!
Code:
num = int(input("Enter a number: "))
i = 1
sum_of_divisors = 0
while i < num:
if num % i == 0:
sum_of_divisors += i
i += 1
print("Sum of divisors:", sum_of_divisors)
if sum_of_divisors == num:
print(num, "is a perfect number")
else:
print(num, "is not a perfect number")
Example Input:
Enter a number: 6
Output:
Sum of divisors: 6
6 is a perfect number
Input Number |
Sum of Divisors |
Perfect Number? |
6 | 6 | Yes |
10 | 8 | No |
28 | 28 | Yes |
12 | 16 | No |
Using a while loop is a simple, clear way to implement a perfect number program in Python.
It also helps beginners understand how loops work and how conditions can be combined to solve problems efficiently.
Also Read: Enhance Your Python Skills: 10 Python Projects You Need to Try!
Recursion is a technique in Python where a function calls itself to solve a problem.
You can use recursion to check for perfect numbers in a clean and elegant way.
This approach helps you understand function calls and how logic can repeat automatically.
To check a perfect number using recursion, you need:
Steps in simple terms:
Code:
def sum_of_divisors(num, i=1):
if i == num:
return 0
if num % i == 0:
return i + sum_of_divisors(num, i + 1)
else:
return sum_of_divisors(num, i + 1)
Explanation:
Also Read: Top 40 Pattern Programs in Python to Master Loops and Recursion
Once the sum of divisors is calculated recursively, compare it with the original number.
Code:
number = int(input("Enter a number: "))
if sum_of_divisors(number) == number:
print(number, "is a perfect number")
else:
print(number, "is not a perfect number")
Example Input:
Enter a number: 28
Output:
28 is a perfect number
Explanation:
The recursive function calculates 1 + 2 + 4 + 7 + 14 = 28.
Since the sum equals the original number, it’s perfect.
Code:
def sum_of_divisors(num, i=1):
if i == num:
return 0
if num % i == 0:
return i + sum_of_divisors(num, i + 1)
else:
return sum_of_divisors(num, i + 1)
number = int(input("Enter a number: "))
print("Sum of divisors:", sum_of_divisors(number))
if sum_of_divisors(number) == number:
print(number, "is a perfect number")
else:
print(number, "is not a perfect number")
Example Input:
Enter a number: 6
Output:
Sum of divisors: 6
6 is a perfect number
Input Number |
Sum of Divisors |
Perfect Number? |
6 | 6 | Yes |
10 | 8 | No |
28 | 28 | Yes |
12 | 16 | No |
Using recursion for a perfect number program in Python demonstrates a different approach compared to loops and makes your code concise and readable.
Also Read: GitHub Project on Python: 30 Python Projects You’d Enjoy
Once you understand basic methods, you can explore advanced ways to find perfect numbers in Python.
These approaches make your code cleaner, more Pythonic, and sometimes more efficient.
Python’s list comprehension allows you to calculate divisors and their sum in a single line.
Code:
num = int(input("Enter a number: "))
sum_of_divisors = sum([i for i in range(1, num) if num % i == 0])
if sum_of_divisors == num:
print(num, "is a perfect number")
else:
print(num, "is not a perfect number")
Example Input:
Enter a number: 28
Output:
28 is a perfect number
Why it works:
The list comprehension [i for i in range(1, num) if num % i == 0] generates all divisors efficiently.
Then sum() adds them, and the result is compared with the number.
You can use lambda and filter() to find divisors without explicit loops.
Code:
num = int(input("Enter a number: "))
divisors = list(filter(lambda x: num % x == 0, range(1, num)))
sum_of_divisors = sum(divisors)
if sum_of_divisors == num:
print(num, "is a perfect number")
else:
print(num, "is not a perfect number")
Example Input:
Enter a number: 6
Output:
6 is a perfect number
Explanation:
filter() selects numbers that divide num evenly.
sum() calculates the total, and the check confirms perfection.
Also Read: Lambda and Anonymous Function in Python
3. Using Object-Oriented Programming (OOP)
You can encapsulate the logic in a class for reusable and organized code.
Code:
class PerfectNumber:
def __init__(self, num):
self.num = num
def divisors_sum(self):
return sum([i for i in range(1, self.num) if self.num % i == 0])
def check_perfect(self):
return self.divisors_sum() == self.num
number = int(input("Enter a number: "))
pn = PerfectNumber(number)
if pn.check_perfect():
print(number, "is a perfect number")
else:
print(number, "is not a perfect number")
Example Input:
Enter a number: 28
Output:
28 is a perfect number
Key Takeaways
Subscribe to upGrad's Newsletter
Join thousands of learners who receive useful tips
Sometimes, you might want to find all perfect numbers within a specific range instead of checking just one number.
Python makes this easy by combining loops with the logic for a perfect number program in Python.
You can iterate through a range of numbers and check each number individually.
Code:
start = int(input("Enter start of range: "))
end = int(input("Enter end of range: "))
for num in range(start, end + 1):
sum_of_divisors = sum([i for i in range(1, num) if num % i == 0])
if sum_of_divisors == num:
print(num, "is a perfect number")
Example Input:
Enter start of range: 1
Enter end of range: 100
Output:
6 is a perfect number
28 is a perfect number
Explanation:
You can also define a function to check perfect numbers and call it within the range loop.
Code:
def is_perfect(num):
return sum([i for i in range(1, num) if num % i == 0]) == num
start = 1
end = 100
for n in range(start, end + 1):
if is_perfect(n):
print(n, "is a perfect number")
Output:
6 is a perfect number
28 is a perfect number
Benefits of Using a Function:
You may also Read: Free Python Course with Certificate
Range |
Perfect Numbers |
1 – 50 | 6, 28 |
1 – 100 | 6, 28 |
1 – 500 | 6, 28, 496 |
Key Takeaways
This approach is helpful when you want to find all perfect numbers in Python for exercises, projects, or coding challenges.
Though both are mathematically 'perfect,' perfect numbers and perfect squares differ significantly in their fundamental structure, frequency, and the computational complexity involved in their identification. Understanding these distinctions is key to appreciating their unique places in number theory.
The key distinction between perfect numbers and perfect squares boils down to this:
To further illustrate the differences, consider the following table:
Feature | Perfect Squares | Perfect Numbers |
Definition | Integer multiplied by itself ((n = k^2)) | Sum of proper positive divisors equals the number |
Operation | Multiplication | Addition |
Derivation | Squaring an integer | Summing proper divisors |
Relationship | Number and its square root | Number and its proper divisors |
First Few | 1, 4, 9, 16, 25, 36, 49... | 6, 28, 496, 8128... |
How Common? | Infinitely many | Relatively rare; only a few are known |
In essence, while both terms involve a special property of integers, the nature of that property—multiplicative for perfect squares and additive for perfect numbers—sets them distinctly apart. Perfect squares are easily generated and verified, unlike the computationally expensive perfect number in Python. Understanding this difference is crucial when exploring various classifications and characteristics within number theory.
Also Read: Python Tutorial: Setting Up, Tools, Features, Applications, Benefits
Let's now consider the practical aspects of identifying perfect number in Python and perfect squares in Python. The following section will explore the computational considerations of finding these elusive numbers.
So far, we have shown how understanding perfect numbers, while a specific mathematical concept, plays an integral part in demonstrating core programming principles like iteration, conditional logic, and algorithmic thinking. In Python, you can find perfect numbers by iterating through integers, identifying their divisors, and checking if their sum equals the original number.
upGrad empowers your Python journey beyond exploring concepts like perfect number program in Python to building a successful career. A leading online learning platform, upGrad boasts over 10 million learners, 200+ courses, and 1,400+ hiring partners.
In India, upGrad offers the following Python-related courses.
For those looking to get into advanced courses, upGrad offers a specialized Executive Post Graduate Certificate in AI and Data Science to fast-track your tech career as well.
Unlock the power of data with our popular Data Science courses, designed to make you proficient in analytics, machine learning, and big data!
Stay informed and inspired with our popular Data Science articles, offering expert insights, trends, and practical tips for aspiring data professionals!
While there aren't any widely known direct cryptographic applications of perfect numbers themselves, their properties, especially their connection to Mersenne primes, are highly relevant. Mersenne primes are often used in primality testing, a fundamental component of many cryptographic algorithms like RSA. Understanding the distribution and characteristics of specific number types, even seemingly niche ones, can indirectly contribute to the development of more secure and efficient algorithms. Exploring such mathematical relationships is crucial for breakthroughs in secure communication.
Beyond the Euclid-Euler theorem, which definitively links all even perfect numbers to Mersenne primes, the sequence of perfect numbers is quite sparse. There are no other easily discernible or well-established patterns governing their occurrence.
The existence of odd perfect numbers remains one of the oldest unsolved problems in mathematics, and their potential distribution, if they exist, is unknown. This area continues to be a rich topic of mathematical investigation.
The search for even perfect numbers is intrinsically linked to the search for Mersenne primes (2p−1). For 2p−1 to be prime, the exponent p itself must be prime. This means that every newly discovered Mersenne prime directly leads to the discovery of a new even perfect number.
Consequently, advancements in primality testing algorithms, especially those optimized for Mersenne numbers, are critical drivers in the ongoing quest to find larger and larger perfect numbers. It's a symbiotic relationship where progress in one area fuels discoveries in the other.
Yes, concepts like "almost perfect numbers" (where the sum of proper divisors is one less than the number) or amicable numbers (pairs of numbers where the sum of proper divisors of each equals the other) are actively studied in number theory and might indeed find more niche applications.
While they may not directly translate to large-scale industry use, they can inspire specialized algorithm design, contribute to computational number theory research, and offer unique challenges in areas like recreational mathematics or specific types of data structure optimization. These related concepts often provide fertile ground for exploring computational efficiency.
The primary difficulty in finding larger perfect numbers stems from two significant computational hurdles. First, it requires discovering increasingly large Mersenne primes, which becomes exponentially more demanding as the exponent (p) grows.
Current methods for testing the primality of such enormous numbers are highly complex and time-consuming. Second, even after a potential Mersenne prime is identified, verifying if the corresponding number is truly perfect involves calculating and summing all its proper divisors. For extremely large integers, this divisor summation process can be computationally intensive, often requiring specialized algorithms and significant processing power.
While not direct one-to-one analogies, the core idea of a mathematical object being "self-referential" in terms of its components, where the sum or combination of its parts equals the whole, can be seen in other mathematical fields. For example, in graph theory, concepts like self-complementary graphs exhibit a similar property where a graph is isomorphic to its complement.
In abstract algebra, certain algebraic structures might possess properties where elements are defined by the sum or product of their substructures. These are loose parallels, but they demonstrate how the elegant balance seen in perfect numbers resonates across different mathematical domains.
Absolutely. The persistent pursuit of discovering new perfect numbers, especially through writing a perfect number program in Python or other languages, has significantly spurred the development and refinement of primality testing algorithms. The necessity of efficiently checking the primality of large Mersenne numbers has led to the creation of highly optimized tests, such as the Lucas-Lehmer test.
This area of research has indirectly influenced the design of more efficient methods for integer factorization and divisor summation, which are fundamental operations in many computational fields, including cryptography and scientific computing.
Perfect numbers are prominent in recreational mathematics and often feature in mathematical puzzles due to their intriguing definition and captivating rarity. They can serve as benchmarks for coding challenges, inspire thought experiments about number properties, and provide a fascinating gateway for enthusiasts to delve deeper into the wonders of mathematics beyond typical textbook problems. Their elegance makes them naturally appealing to curious minds.
Given the direct link between even perfect numbers and Mersenne primes, studying the distribution of perfect numbers is inherently tied to the distribution of these specific types of prime numbers.
While perfect numbers are exceedingly rare, any insights gained into their pattern, or the lack thereof, can indirectly offer clues about the distribution of Mersenne primes, which are a crucial subset of all prime numbers. Therefore, research into perfect numbers contributes to the broader understanding of how prime numbers are spread across the number line, a fundamental question in number theory.
Historically, perfect numbers have been imbued with a certain mystique and symbolic significance. Ancient Greek mathematicians, like Nicomachus in his Introductio Arithmetica, viewed them as representing harmony, completeness, or divine perfection due to their unique self-referential property. This philosophical interpretation often stemmed from the belief that numbers held inherent meaning and structure in the cosmos.
While modern mathematics focuses on their properties analytically, their historical and cultural significance underscores the human fascination with patterns and order found within numbers.
Intuitively, perfect numbers are rare because they require an exact balance: the sum of a number's divisors (excluding itself) must exactly equal the number itself. As numbers grow larger, they generally acquire more divisors, which usually makes the sum of their proper divisors either far less than the number (deficient) or significantly greater (abundant).
A very specific combination of prime factors is required for this sum to perfectly match the number. It's like trying to balance a complex scale with many weights perfectly; finding that exact equilibrium point is an infrequent occurrence.
834 articles published
Rohit Sharma is the Head of Revenue & Programs (International), with over 8 years of experience in business analytics, EdTech, and program management. He holds an M.Tech from IIT Delhi and specializes...
Speak with Data Science Expert
By submitting, I accept the T&C and
Privacy Policy
Start Your Career in Data Science Today
Top Resources