Python Programs | IT Developer
IT Developer

Python Programs



Share with a Friend

Python Programs - Functions

Function to check if a number is perfect or not - Python Program

Example 1 :

def is_perfect(num): """Check if number is perfect.""" return sum(i for i in range(1, num) if num % i == 0) == num print(is_perfect(28))

Output

 
OUTPUT  :
True

Example 2 : Advanced Program

def is_perfect_number(num): """ Checks if a given number is a perfect number. Args: num (int): The number to be checked. Returns: bool: True if the number is perfect, False otherwise. """ if num <= 0: # Perfect numbers are positive integers return False sum_of_divisors = 0 # Iterate from 1 up to (but not including) the number itself for i in range(1, num): if num % i == 0: # If 'i' is a divisor of 'num' sum_of_divisors += i return sum_of_divisors == num # Test cases print(f"Is 6 a perfect number? {is_perfect_number(6)}") print(f"Is 28 a perfect number? {is_perfect_number(28)}") print(f"Is 12 a perfect number? {is_perfect_number(12)}") print(f"Is 0 a perfect number? {is_perfect_number(0)}") print(f"Is 1 a perfect number? {is_perfect_number(1)}")

Output

 
OUTPUT  :
Is 6 a perfect number? True
Is 28 a perfect number? True
Is 12 a perfect number? False
Is 0 a perfect number? False
Is 1 a perfect number? False

Explanation:

is_perfect_number(num) function:

  • Takes an integer numas input.
  • Handles non-positive numbers: It first checks if numis less than or equal to 0. Perfect numbers are defined as positive integers, so it returns False for non-positive inputs.
  • Initializes sum_of_divisors: A variable sum_of_divisorsis initialized to 0 to store the sum of the proper divisors.
  • Iterates through potential divisors: A forloop iterates from 1 up to num - 1. This range ensures that only proper divisors (excluding the number itself) are considered.
  • Checks for divisibility: Inside the loop, if num % i == 0:checks if i divides num If it does, i is a proper divisor.
  • Adds divisors to sum: If iis a divisor, it is added to sum_of_divisors.
  • Compares sum to number: Finally, the function returns Trueif sum_of_divisors is equal to num, indicating it is a perfect number; otherwise, it returns False.