# How to check a perfect number using Python

In this tutorial, we will learn how to check a perfect number in Python.

## Perfect Number:

In number theory, a perfect number can be defined using two definitions.

**Definition 1:** A positive integer which is equal to the sum of its all positive divisors (excluding itself) can be termed as a perfect number.

for an example let us consider a number 6. Integral divisors of 6 are 1,2,3 and 6, we can observe that 1+2+3=6. So, according to the definition of a perfect number 6 is a perfect number.

**Note: **Here, while adding the integral divisors of 6 we didn’t include 6 for addition. While using definition 1 it’s quite important to keep this in mind.

**Definition 2: **A number which is half of the sum of all its integral divisors including the number itself can be termed as a perfect number. Let’s consider an example to understand this concept. Let’s consider 28 as our test case, we have 1,2,4,7,14 and 28 as integral divisors of 28. Now, according to definition 2, we can form an equation as 1+2+4+7+14+28=56, here 56=2*28. Therefore, we can state that the number(28) is half of the sum(56) of all its integral divisors.

**Note: **In here while considering the divisors for our equation we haven’t left the number we are considering, rather we have considered it in the addition and then checked the validity of the number according to the definition.

## Check Perfect Number Using Python:

**Let’s try to code by using definition 1:**

#scan a number from user nm=int(input("Enter the number: ")) #take a variable sum to store sum sum=0 #use a for loop to check integral divisors for i in range(1,nm): if nm%i==0: sum=sum+i #condition for definition 1 if sum==nm: print("a perfect number.") else: print("not a perfect number.")

nm=int(input("Enter the number: "))

Here we take the input from the user and the cast it into an integer for further access.

sum=0

Let’s take a variable ‘sum’ where we can store the sum of all the divisors of the number given by the user.

for i in range(1,nm):

we have used a for loop to find all the integral divisors of the number given by the user. The loop will iterate from 1 to nm-1 as we want to exclude the number itself.

if nm%i==0: sum=sum+i

the ‘if’ statement is used to check if ‘i’ divide our number completely, and if it does then we can add that number to the ‘sum’. After the end of the loop, we will have the summation of all the integral divisors of the given number.

if sum==nm: print("a perfect number.") else: print("not a perfect number.")

Here, we check the condition according to the parameters of definition 1, i.e if the sum of all the integral divisor(excluding the number) of the number is equal to the number then the number can be termed as a perfect number.

Output: Enter the number: 6 a perfect number.

Enter the number: 45 not a perfect number.

Also read:

## Leave a Reply