Python program for perfect number

Python program for perfect number

Before writing any program for a given problem, we have to understand the problem for which we are creating a solution program. So, let's understand what a perfect number is.

Perfect number

If a given number is equal to the sum of its all divisors, then we call such number as 'Perfect number.'

Example of perfect number: 6 is a perfect number because sum of all divisors of 6 i.e., 1, 2 & 3, is equal to 6 (1 + 2 + 3 = 6). But, in the same way, 15 is not a perfect number.

A Python Program to Check Perfect Number

In this tutorial, we will write a program so that we can check if the given number in the program is perfect or not. We will take the number as user input and return the output that the number given by the user is a perfect number or not.

We will implement the following steps in the program for checking perfect number:

Step 1: We will take a positive integer from the user and store it in a num variable.

Step 2: We will initialize the num variable to find out the proper sum of divisors up to 0.

Step 3: Then, we will use a for loop in the program and if statement to add all the proper divisors of the number given as input.

Step 4: We will use the if else statement condition to check if the sum of all divisors is equal to the actual number or not.

Step 5: If the condition satisfies, the program will print, "The number given by you is a perfect number!" Otherwise, the program will print, "The number given by you is not a perfect number!"

Step 6: Exit the function.

Let's understand the implementation of above steps through the following Python program:

Example – 

 # Define default perfect number checker function
 def PerChecker (a):
     sums = 0 # sum variable
     for j in range (1, a): # for loop to find total sum
         if (a % j == 0):
             sums = sums + j # sum of all values
     if (sums == a): # a perfect number
        print ("The number" ,a, " is a Perfect number!")
     else: # not a perfect number
         print ("The number" ,a, " is not a Perfect number!")    
 # Taking number from user as input
 num = int (input ("Enter a positive integer: "))
 # Calling out function
 PerChecker (num) 

Output:

 Enter a positive integer: 6
 The number 6 is a Perfect number!
 Enter a positive integer: 37
 The number 37 is not a Perfect number! 

Explanation – 

As we can see that, when we gave six as user input, the program return that it is a perfect number, but when we gave 37 as user input, the program returned 37 is not a perfect number. So, we can check any number is a perfect number or not in our Python program by implementing the above-explained approach.