codescracker
python

Python Program to Check Perfect Number



« Previous Program Next Program »

This article is created to cover the program in Python that checks whether a number entered by user is a perfect number or not. Here are the list of programs covered in this article:

What is a Perfect Number ?

A perfect number is a number that is equal to the sum of its positive divisors, excluding the number itself. That is, the number 6 has divisors 1, 2, and 3 (excluding 6 itself). And 1+2+3 is equal to 6. Therefore 6 is a perfect number.

Check Perfect Number using for Loop

The question is, write a program in Python that checks whether a number is a perfect or not using for loop. Here is its answer:

print("Enter the Number:")
num = int(input())
sum = 0
for i in range(1, num):
  if num%i==0:
    sum = sum+i
if num==sum:
  print("It is a Perfect Number")
else:
  print("It is not a Perfect Number")

Here is its sample run:

python program check perfect number

Now supply the input say 6 and press ENTER key to check and print whether it is a perfect number or not as shown in the snapshot given below:

check perfect number python

Modified Version of Previous Program

This is the modified version of previous program, uses end= and str(). Rest of the things are almost similar to previous program. The end= is used to skip printing of an automatic newline. And the str() converts any type into a string type.

print(end="Enter the Number: ")
num = int(input())
sum = 0
for i in range(1, num):
  if num%i==0:
    sum = sum+i
if num==sum:
  print("\n" + str(num) + " is a Perfect Number")
else:
  print("\n" + str(num) + " is not a Perfect Number")

Here is its sample run with user input 496:

python check perfect number

Check Perfect Number using while Loop

The question is, write a Python program to check for perfect number using while loop. Here is its answer:

print(end="Enter the Number: ")
num = int(input())
sum = 0
i = 1
while i<num:
  if num%i==0:
    sum = sum+i
  i = i+1
if num==sum:
  print("\n" + str(num) + " is a Perfect Number")
else:
  print("\n" + str(num) + " is not a Perfect Number")

Python Online Test


« Previous Program Next Program »



© Copyright 2021. All Rights Reserved.

CodesCracker