script_21.py - Number Range Checker
Code
#!/usr/bin/env python3
"""Number range checker"""
num = int(input("Enter a number: "))
if 1 <= num <= 10:
print("Number is between 1 and 10")
elif 11 <= num <= 20:
print("Number is between 11 and 20")
elif 21 <= num <= 30:
print("Number is between 21 and 30")
else:
print("Number is outside 1-30 range")
Explanation
Line 4: num = int(input("Enter a number: "))
- int() converts to integer type
- num stores integer value
Line 6: if 1 <= num <= 10:
- Chained comparison - Python allows multiple comparisons
- Equivalent to (1 <= num) and (num <= 10)
- Both <= comparisons must be True
- Checks if num is in range 1 to 10 (inclusive on both ends)
- More readable than if num >= 1 and num <= 10
- Evaluates left to right: first checks 1 <= num, then checks num <= 10
Line 8: elif 11 <= num <= 20:
- Same chained comparison pattern
- Checks range 11-20 inclusive
- Only evaluated if previous condition False
Line 10: elif 21 <= num <= 30:
- Checks range 21-30 inclusive
Line 12: else:
- Catches all numbers outside 1-30 range
- Includes negatives, zero, numbers > 30
- Examples: -5, 0, 31, 100