Python Program to Check if a Number is Perfect

Introduction

A perfect number is a positive integer that is equal to the sum of its proper divisors, excluding itself. For example, 6 is a perfect number because its divisors are 1, 2, and 3, and 1 + 2 + 3 = 6. This tutorial will guide you through creating a Python program that checks whether a given number is a perfect number.

Example:

  • Input: 28

  • Output: 28 is a perfect number

  • Input: 10

  • Output: 10 is not a perfect number

Problem Statement

Create a Python program that:

  • Takes a number as input.
  • Checks if the number is a perfect number.
  • Displays whether the number is perfect or not.

Solution Steps

  1. Take Input from the User: Use the input() function to get a number from the user.
  2. Convert Input to an Integer: Convert the input string to an integer using int().
  3. Find the Proper Divisors: Iterate through all numbers from 1 to half of the given number, and find the divisors.
  4. Calculate the Sum of Divisors: Sum all the proper divisors.
  5. Check if the Sum Equals the Original Number: Compare the calculated sum to the original number.
  6. Display the Result: Use the print() function to display whether the number is a perfect number.

Python Program

# Python Program to Check if a Number is Perfect
# Author: https://www.rameshfadatare.com/

# Step 1: Take input from the user
num = int(input("Enter a number: "))

# Step 2: Find the proper divisors and calculate their sum
sum_of_divisors = sum(i for i in range(1, num) if num % i == 0)

# Step 3: Check if the sum equals the original number
if sum_of_divisors == num and num != 0:
    print(f"{num} is a perfect number")
else:
    print(f"{num} is not a perfect number")

Explanation

Step 1: Take Input from the User

  • The input() function prompts the user to enter a number. The input is converted to an integer using int().

Step 2: Find the Proper Divisors and Calculate Their Sum

  • The program iterates over all numbers from 1 to num-1, checking if each is a divisor of num. The proper divisors are summed using a generator expression within the sum() function.

Step 3: Check if the Sum Equals the Original Number

  • The program checks if the sum of the proper divisors is equal to the original number. If they are equal, the number is a perfect number.

Step 4: Display the Result

  • The print() function is used to display whether the number is a perfect number.

Output Example

Example 1:

Enter a number: 28
28 is a perfect number

Example 2:

Enter a number: 10
10 is not a perfect number

Example 3:

Enter a number: 6
6 is a perfect number

Conclusion

This Python program demonstrates how to check whether a number is a perfect number by calculating the sum of its proper divisors. It’s a useful exercise for understanding loops, conditionals, and mathematical concepts in Python.

Leave a Comment

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

Scroll to Top