Perfect number program in Python with example

In this tutorial you will learn how to write a program in Python programming language to check a given number is perfect or not.

This program is a little bit tricky and logical.

But Before directly moving on to writing and learning the program first you should know 

What is Perfect Number?

A perfect number is a positive integer that is equal to the sum of its positive divisors, excluding the number itself.

Let’s understand it with an example

6 is a positive number and its divisor is 1,2,3 and 6 itself.

But we should not include 6 as by the definition of a perfect number.

Let’s add its divisor excluding itself

1+2+3 = 6 which is equal to the number itself.

It means 6 is a Perfect Number.

How our program will behave?

Python program for perfect numbers is written below. This program will take a positive number as input.

Suppose you want to check whether a number is perfect or not then you have to give that number as an input to this below program at the time of execution.

After the calculation, it will give you appropriate output.

If the number is perfect then 

Below is a program to check a given number is perfect or not in Python

num = int(input("please give a number: "))
sum=0
for i in range(1,(num//2)+1):
    remainder = num % i
    if remainder == 0:
        sum = sum + i
if sum == num:
    print("given input is perfect number")
else:
    print("given input is not a perfect number") 

Output 1:

please give a number: 65
given input is not a perfect number

Output 2:

please give a number: 6
given input is perfect number

Leave a Comment