Python Program to Check Whether a Given Number is Perfect Number

This is a Python Program to check if a number is a Perfect number.

Problem Description

The program takes a number and checks if it is a Perfect number.

Problem Solution

1. Take in an integer and store it in a variable.
2. Initialize a variable to count the sum of the proper divisors to 0.
3. Use a for loop and an if statement to add the proper divisors of the integer to the sum variable.
4. Check if the sum of the proper divisors of the number is equal to the variable.
5. Print the final result.
6. Exit.

Program/Source Code

Here is source code of the Python Program to check if a number is a Perfect number. The program output is also shown below.

 
n = int(input("Enter any number: "))
sum1 = 0
for i in range(1, n):
    if(n % i == 0):
        sum1 = sum1 + i
if (sum1 == n):
    print("The number is a Perfect number!")
else:
    print("The number is not a Perfect number!")
Program Explanation

1. User must enter the number and store it in a variable.
2. Use a for loop to generate numbers from 1 to n (where n is not included as we need the sum of the proper divisors of the number).
3. Using an if statement check if the number divided by i gives the remainder as 0 which is basically the proper divisor of the integer.
4. Then the proper divisors of the number are added to the sum variable.
5. If the sum of the proper divisors of the number is equal to the original number, tje number is a Perfect number.
6. The final result is printed.

advertisement
advertisement
Runtime Test Cases
 
Case 1:
Enter any number: 6
The number is a Perfect number!
 
Case 2:
Enter any number: 25
The number is not a Perfect number!

Sanfoundry Global Education & Learning Series – Python Programs.

To practice all Python programs, here is complete set of 150+ Python Problems and Solutions.

Note: Join free Sanfoundry classes at Telegram or Youtube

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.