Perfect Number Program in Python
Below are some of the ways by which we can check if the number is a perfect number or not in Python:
Using for Loop
In this approach, we simply take a number from the user and make a variable named Sum initially its value is 0 and then we make a logic by using the for loop along with the conditional statement of if/ else. Finally, we get proper output.
Python3
# Perfect Number by using For_loop Input_Number = 78 Sum = 0 for i in range ( 1 , Input_Number): if (Input_Number % i = = 0 ): Sum = Sum + i if ( Sum = = Input_Number): print ( "Number is a Perfect Number." ) else : print ( "Number is not a Perfect Number." ) |
Number is not a Perfect Number.
Using List Comprehension
Here, in checkIsPerfectNumber(input_Number_is), we leverage the beauty of list comprehension to succinctly end up aware of divisors. The sum of those divisors is then in contrast to the authentic huge range to envision perfection.
Python3
def checkIsPerfectNumber(number): divisors = sum ([i for i in range ( 1 , number) if number % i = = 0 ]) return number = = divisors input_Number_is = 6 if checkIsPerfectNumber(input_Number_is): print ( "Number is a Perfect Number." ) else : print ( "Number is not a Perfect Number." ) |
Number is a Perfect Number.
Using filter() method
In this technique, isPerfectNumberFilterMethod(number), The sum of those divisors is then in contrast to the specific amount to determine if it is exceptional.
Python3
def IsPerfectNumberFilterMethod(number): divisors = list ( filter ( lambda x: number % x = = 0 , range ( 1 , number))) return sum (divisors) = = number input_Number_is = 25 if IsPerfectNumberFilterMethod(input_Number_is): print ( "Number is a Perfect Number." ) else : print ( "Number is not a Perfect Number." ) |
Number is not a Perfect Number.
Perfect Number Program in Python
In this article, we will see how we can check if a number is a perfect number or not in Python.