Skip to content

script_14.py - Divisibility Checker

Code

Python
#!/usr/bin/env python3
"""Divisibility checker"""

num = int(input("Enter a number: "))
divisor = int(input("Check divisibility by: "))

if divisor == 0:
    print("Cannot divide by zero")
elif num % divisor == 0:
    print(f"{num} is divisible by {divisor}")
else:
    print(f"{num} is not divisible by {divisor}")

Explanation

Line 4-5: Variable assignments - Both input() calls converted to int type - num stores the number to check - divisor stores what to divide by - Integer type appropriate for divisibility checks

Line 7: if divisor == 0: - Validates input before attempting division - Checks for zero divisor (undefined in mathematics) - Prevents potential errors in later calculations - Guard clause pattern - check error conditions first

Line 9: elif num % divisor == 0: - Only executed if divisor != 0 (safe to use modulo) - % is modulo operator (returns remainder) - When remainder equals 0, number is evenly divisible - Example: 10 % 2 = 0 (divisible), 10 % 3 = 1 (not divisible)

Line 10: f-string usage - {num} and {divisor} are placeholders - Embeds both variables in the output string - Multiple variables can be used in one f-string

Line 11: else: - Executes when divisor is not zero AND remainder is not zero - Means division would have a remainder (not evenly divisible)