def perfect_num(number):
return number > 0 and sum(i for i in range(1, number) if number % i == 0) == number
num = int(input("Enter a number: "))
if perfect_num(num):
print(f"{num} is a perfect number.")
else:
print(f"{num} is not a perfect number.")
Explanation:
1. The perfect_num Function
def perfect_num(number):
return number > 0 and sum(i for i in range(1, number) if number % i == 0) == number
number > 0:
Ensures the input is a positive integer. A perfect number must be positive.
sum(i for i in range(1, number) if number % i == 0):
Uses a generator expression to calculate the sum of all divisors of number (excluding the number itself).
i for i in range(1, number) iterates over all integers from 1 up to (but not including) number.
if number % i == 0 ensures that only divisors of number (numbers that divide evenly into number) are included.
== number: Checks if the sum of the divisors equals the original number, which is the defining condition for a perfect number.
2. Input from the User
num = int(input("Enter a number: "))
The user is prompted to enter a number.
The input is converted to an integer using int.
3. Check if the Number is Perfect
if perfect_num(num):
print(f"{num} is a perfect number.")
else:
print(f"{num} is not a perfect number.")
Calls the perfect_num function with the user input (num) as an argument.
If the function returns True, the program prints that the number is a perfect number.
Otherwise, it prints that the number is not a perfect number.
#source code --> clcoding.com
0 Comments:
Post a Comment