Python Program for checking Perfect Number or Not

In this tutorial, we will discuss a python program for checking Perfect Number or Not.
Before going to the program first, let us understand what is a Perfect Number.

Perfect Number:
A perfect number is a positive integer that is equal to the sum of its proper divisors, excluding itself.
For example, 6, 28, and 496 are perfect numbers.

Related: Python Program for checking if a number is prime or not

Program code for checking if a number is perfect or not in Python

# Perfect Number Checker in Python
def is_perfect(num):
    if num <= 1:
        return False
    sum_of_divisors = sum([i for i in range(1, num) if num % i == 0])
    return sum_of_divisors == num

number = int(input("Enter a number: "))
if is_perfect(number):
    print(f"{number} is a perfect number.")
else:
    print(f"{number} is not a perfect number.")

Explanation

  1. Function Definition: The is_perfect function takes an integer num as input and returns True if the number is perfect, and False otherwise.
  2. Sum of Divisors: The function calculates the sum of all divisors of the number (excluding itself) using a list comprehension.
  3. Main Program: The program prompts the user to enter a number and then checks if it is perfect using the is_perfect function.

Output

Python Program for checking Perfect Number or Not

  • When you run the above program, it will prompt you to enter a number.
  • After entering the number, it will check whether the number is perfect or not and print the result.

Conclusion

  • In this tutorial, we learned how to check if a given number is a perfect number using a python program.
  • Understanding this concept is essential for solving various mathematical problems and competitive programming challenges.
  • Practice this example to enhance your programming skills and understanding of perfect numbers.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *