script_25.py - Prime Number Checker (Simple)
Code
#!/usr/bin/env python3
"""Prime number checker (simple)"""
num = int(input("Enter a number: "))
if num < 2:
print(f"{num} is not prime")
elif num == 2:
print(f"{num} is prime")
elif num % 2 == 0:
print(f"{num} is not prime (divisible by 2)")
else:
is_prime = True
for i in range(3, int(num**0.5) + 1, 2):
if num % i == 0:
is_prime = False
break
if is_prime:
print(f"{num} is prime")
else:
print(f"{num} is not prime")
Explanation
Line 4: num = int(input("Enter a number: "))
- int() converts to integer type
- num stores integer value
Line 6: if num < 2:
- Numbers less than 2 (0, 1, negatives) are not prime by definition
- Quick elimination of small numbers
Line 8: elif num == 2:
- 2 is the only even prime number
- Special case handling
Line 10: elif num % 2 == 0:
- % modulo operator checks remainder
- All even numbers (except 2) are not prime
- Eliminates half of all numbers quickly
Line 13: is_prime = True
- Boolean variable initialized to True
- Assumption: number is prime until proven otherwise
- Will be set to False if divisor found
Line 14: for i in range(3, int(num**0.5) + 1, 2):
- for loop (not covered in if/ category, but necessary here)
- range() generates sequence of numbers
- 3 is start value (already checked 2)
- num**0.5 is square root of num (float result)
- int() converts float to integer
- + 1 includes the square root in range
- 2 is step (only check odd numbers: 3, 5, 7, 9...)
- Optimization: only need to check up to √num
Line 15: if num % i == 0:
- Nested if inside for loop
- Checks if current number i divides num evenly
- If divisible, num is composite (not prime)
Line 16: is_prime = False
- Reassigns boolean variable to False
- Found a divisor, so number is not prime
Line 17: break
- Exits the for loop immediately
- No need to check further if divisor already found
- Optimization keyword
Line 18: if is_prime:
- After loop, check final boolean value
- True means no divisors were found