Python Programs | IT Developer
IT Developer

Python Programs



Share with a Friend

Python Programs - Conditional Statements

Check if a number is a multiple of another - Python Program

To check if a number is a multiple of another in Python, the modulo operator (%) is used. If the remainder of the division of the first number by the second number is 0, then the first number is a multiple of the second.

Example 1 :

a = int(input("Enter first number: ")) b = int(input("Enter second number: ")) if b != 0 and a % b == 0: print(f"{a} is a multiple of {b}") else: print(f"{a} is not a multiple of {b}")

Output

OUTPUT  :
Enter first number: 12
Enter second number: 4
12 is a multiple of 4 

Example 2 :

def is_multiple(num1, num2): """ Checks if num1 is a multiple of num2. Args: num1: The number to be checked. num2: The potential divisor. Returns: True if num1 is a multiple of num2, False otherwise. """ if num2 == 0: return False # Division by zero is undefined return num1 % num2 == 0 # Get input from the user number1 = int(input("Enter the first number: ")) number2 = int(input("Enter the second number: ")) # Check and print the result if is_multiple(number1, number2): print(f"{number1} is a multiple of {number2}.") else: print(f"{number1} is not a multiple of {number2}.")

Output

OUTPUT  :
Enter the first number: 20
Enter the second number: 5
20 is a multiple of 5. 

Explanation

is_multiple(num1, num2) function:

  • This function takes two integer arguments, num1and num2.
  • It first handles the edge case where num2is 0, returning False as division by zero is not defined.
  • It then uses the modulo operator (%) to find the remainder when num1is divided by num2.
  • If the remainder is 0, it means num1is perfectly divisible by num2, indicating num1 is a multiple of num2. In this case, the function returns True.
  • Otherwise, if the remainder is not 0, num1is not a multiple of num2, and the function returns False.

User Input:

  • The program prompts the user to enter two numbers using input().
  • int()is used to convert the input strings into integers.

 

Conditional Check and Output:

  • The is_multiple()function is called with the user-provided numbers.
  • An if-elsestatement checks the boolean value returned by the function.
  • A formatted string literal (f-string) is used to print a clear message indicating whether the first number is a multiple of the second.