Skip to content

script_9.py - Find All Divisors of a Number

Code

Python
#!/usr/bin/env python3
"""Find all divisors of a number"""

num = int(input("Enter a number: "))

print(f"Divisors of {num}:")
for i in range(1, num + 1):
    if num % i == 0:
        print(i)

Explanation

Line 4: num = int(input("Enter a number: ")) - num stores integer to find divisors for

Line 6: print(f"Divisors of {num}:") - Prints header before loop - Executes once, not part of loop

Line 7: for i in range(1, num + 1): - Iterates from 1 to num (inclusive) - Need to include num itself (it's always a divisor) - Example: if num=12, checks 1,2,3,4,5,6,7,8,9,10,11,12

Line 8: if num % i == 0: - Conditional statement inside loop - % modulo gives remainder of division - Remainder of 0 means i divides num evenly (is a divisor) - Example: 12 % 3 = 0 (3 is divisor), 12 % 5 = 2 (5 is not) - Not every iteration prints (only when condition True)

Line 9: print(i) - Indented under if (not directly under for) - Only executes when i is a divisor - Prints one number per line