Python Programs | IT Developer
IT Developer

Python Programs



Share with a Friend

Python Programs - Operators and Expressions

Check if a number is divisible by 3 and 5 - Python Program

# Prompt the user to enter a number number = int(input("Enter an integer: ")) # Check for divisibility by both 3 and 5 if number % 3 == 0 and number % 5 == 0: print(f"The number {number} is divisible by both 3 and 5.") # Check for divisibility by 3 only elif number % 3 == 0: print(f"The number {number} is divisible by 3 but not by 5.") # Check for divisibility by 5 only elif number % 5 == 0: print(f"The number {number} is divisible by 5 but not by 3.") # If not divisible by either 3 or 5 else: print(f"The number {number} is neither divisible by 3 nor by 5.")

Output

 
OUTPUT 1:
Enter an integer: 15
The number 15 is divisible by both 3 and 5. 


OUTPUT 2:
Enter an integer: 10
The number 10 is divisible by 5 but not by 3.

OUTPUT 3:
Enter an integer: 9
The number 9 is divisible by 3 but not by 5.

Explanation

  • Input:

The program first prompts the user to "Enter an integer:" using the input() function. The entered value is then converted to an integer using int() and stored in the number variable.

  • Divisibility Check:
    • The ifstatement checks if number is divisible by both 3 and 5. This is done using the modulo operator (%). If number % 3 == 0 (remainder when divided by 3 is 0) AND number % 5 == 0 (remainder when divided by 5 is 0), then the number is divisible by both. 
    • The elifstatements handle cases where the number is divisible by only one of them. elif number % 3 == 0 checks for divisibility by 3 only, and elif number % 5 == 0 checks for divisibility by 5 only. 
    • The elseblock executes if none of the above conditions are met, meaning the number is not divisible by either 3 or 5.
  • Output:

Based on the divisibility checks, an appropriate message is printed to the console using an f-string to include the entered number in the output.