Python Code Example: Perfect number

A perfect number is a positive integer that is equal to the sum of its proper divisors, excluding itself. In other words, a perfect number is a number that is the sum of all its positive divisors, excluding the number itself. This concept has been studied in number theory since ancient times.

This Python script checks whether a given number is a perfect number.

Code Example

sum = 0
number = int(input("Enter a number to check for perfect: "))

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

if sum == number:
    print(str(number) + " is a perfect number")
else:
    print(str(number) + " is not a perfect number")

Output

Enter a number to check for perfect: 28
28 is a perfect number

Code Explanation

The code starts by initializing a variable sum to 0, which will be used to keep track of the sum of the proper divisors of the input number.

Next, the code asks the user to input a number, and converts the input to an integer using the int function. The input value is then stored in the variable number.

The code then uses a for loop to iterate over the numbers from 1 to number – 1. For each number i in the range, the code uses an if statement to check if i is a proper divisor of number, which means that number is divisible by i without a remainder. If number is divisible by i, the code adds i to the sum variable.

After the for loop, the code uses another if statement to check if the sum of the proper divisors of number is equal to number. If sum is equal to number, the code prints the message “X is a perfect number”, where X is the value of number. If sum is not equal to number, the code prints the message “X is not a perfect number”.

The str function is used to convert the value of number to a string representation, so that it can be concatenated with the string literals in the print statements.

This code demonstrates how to use a for loop and an if statement to determine if a number is a perfect number, which is a positive integer that is equal to the sum of its proper divisors.