How to find perfect number in Python

Published on Aug. 22, 2023, 12:16 p.m.

To find if a number is a perfect number in Python, you can add all of its proper positive divisors (except the number itself) and check if the sum is equal to the number. Here’s an example program in Python:

num = int(input("Enter any positive integer: "))
sum = 0

for i in range(1, num):
    if num % i == 0:
        sum += i

if sum == num:
    print(num, "is a perfect number")
else:
    print(num, "is not a perfect number")

In this program, we prompt the user to enter a positive integer and convert the input to an integer using the int() function. Then we use a for loop to iterate through all numbers from 1 to num - 1. For each number, we check if it’s a divisor of num using the % operator. If it is, we add it to the sum variable. Finally, we check if sum is equal to num, and print the appropriate message to the console.

You can also modify the program to check a range of numbers by using another for loop to iterate through the range of numbers you want to check.

Tags:

related content