In this simple python program, we need to check the number is a perfect number. It is a number-based python program.
For a better understanding of this example, we always recommend you to learn the basic topics of Python programming listed below:
This Simple python program is on the perfect number. A number is called a perfect number if it is a positive number and the sum of all the proper divisors of that number is equal to the number itself. In this basic python program, we need to check if the user's input is a perfect number or not and print the result.
For example, let us take a number 6. We know the divisors of 6 are 1, 2, 3, and let's check the divisors' sum.1 + 2 + 3 = 6, so it's a match and 6 is a perfect number.
To implement this logic in the python program example, we have to accept the number from the user and open a for loop in python from 1 to that number. Check all the divisors of the given number using the mod operator in python language. If
the python if condition satisfies, add that divisor to the variable sum, which has the previous sum of the divisors. After all the iteration of the for loop
, check the sum and numbers are equal or not. If it is equal, then it is a perfect number else
, not a perfect number.
STEP 1: Accept the number from the user using the input method in the python programming language and convert the string to an integer using int()
.
STEP 2: Initialize a variable for the sum as zero.
STEP 3: Open a for loop
from 1 to the number to find all the divisors.
STEP 4: Use an if condition to check the number mod i is zero. if it's a zero then it is a divisor.
STEP 5: Add the number to the sum if it is a divisor using python basic syntax.
STEP 6: Check using an if
condition that number is equal to the sum if so the print the number is perfect number using print statement in python language.
n = int(input("Enter any number: "))
sum1 = 0
for i in range(1, n):
if(n % i == 0):
sum1 = sum1 + i
if (sum1 == n):
print("The number is a Perfect number")
else:
print("The number is not a Perfect number")
Enter any number : 6 The number is a Perfect number