7.19 Hands-on Exercises & Mini Projects
Practice programs reinforcing Python operator concepts — a CPU usage calculator, a disk usage alert, an HTTP status code classifier, and a service health checker.
CPU Usage Calculator
Build a function that takes total CPU time used and elapsed time, and returns the percentage utilization using arithmetic operators.
def cpu_utilization(used_seconds, elapsed_seconds):
return (used_seconds / elapsed_seconds) * 100
>>> cpu_utilization(45, 60)
75.0
Disk Usage Alert
Build a function that returns an alert message using comparison operators against a configurable threshold.
def check_disk(percent_used, threshold=90):
return "ALERT" if percent_used > threshold else "OK"
>>> check_disk(95)
'ALERT'
Status Code Validator
Build a function using chained comparisons to classify any HTTP status code into its category.
def classify_status(code):
if 200 <= code < 300:
return "Success"
elif 300 <= code < 400:
return "Redirect"
elif 400 <= code < 500:
return "Client Error"
else:
return "Server Error"
>>> classify_status(301)
'Redirect'
Service Health Checker
Build a function combining logical operators to determine overall service health from multiple boolean signals.
def is_healthy(is_running, response_time_ms, error_rate):
return is_running and response_time_ms < 500 and error_rate < 0.05
>>> is_healthy(True, 230, 0.01)
True
>>> is_healthy(True, 800, 0.01)
False
Quick Interview Answer
“These exercises reinforce the chapter’s core ideas hands-on: the CPU calculator exercises arithmetic (
/and*), the disk alert exercises comparison plus the ternary operator, the status validator exercises chained comparisons across anif/elifladder, and the health checker exercisesand-chained logical operators with short-circuit evaluation skipping later checks once an earlier one already fails.”
Common Mistakes
- Using
/where//was intended (or vice versa) in the CPU calculator, producing a fractional result where a whole number was expected, or a truncated one where precision mattered. - Writing the status validator as separate
ifstatements instead ofif/elif, letting multiple branches match and return inconsistent results. - Ordering the health checker’s conditions without considering short-circuit performance — putting an expensive check before a cheap one that’s more likely to fail first.
Add More Questions to This Guide
Know a question that should be here? Share it and help the community!
Open Google Form