8.17 Hands-on Exercises
Practice programs reinforcing Python type conversion concepts — a safe user input converter, a resilient CSV parser, and a log analyzer that classifies status codes safely.
User Input Converter
Build a function that safely converts input() text to int, float, or bool based on a requested target type, with sensible error handling.
def convert_input(value, target_type):
try:
if target_type == bool:
return value.strip().lower() in ("true", "yes", "1")
return target_type(value)
except (ValueError, TypeError):
return None
>>> convert_input("42", int)
42
>>> convert_input("yes", bool)
True
>>> convert_input("abc", int)
None
CSV Parser
Build a function that reads CSV rows and converts specified numeric columns, handling any row with bad data gracefully.
import csv, io
def parse_ages(csv_text):
reader = csv.DictReader(io.StringIO(csv_text))
result = []
for row in reader:
try:
row["age"] = int(row["age"])
except ValueError:
row["age"] = None
result.append(row)
return result
>>> parse_ages("name,age\nAlice,30\nBob,N/A")
[{'name': 'Alice', 'age': 30}, {'name': 'Bob', 'age': None}]
Log Analyzer
Build a function that extracts and converts status codes from log lines, classifying each safely even if a line is malformed.
def classify_status_line(status_str):
try:
code = int(status_str)
except ValueError:
return "invalid"
if 200 <= code < 300:
return "success"
elif 400 <= code < 500:
return "client_error"
elif code >= 500:
return "server_error"
return "other"
>>> classify_status_line("404")
'client_error'
>>> classify_status_line("N/A")
'invalid'
Mini Projects
- Config loader — reads a dict of raw string values and converts each to its declared type (
int/float/bool), reporting any that fail. - CLI calculator — safely converts two
input()values tofloatand applies a chosen arithmetic operator, handling invalid input without crashing. - Environment-variable validator — checks a list of required env vars exist and are convertible to their expected types before a script proceeds.
Quick Interview Answer
“These exercises reinforce the chapter’s core ideas hands-on: the input converter exercises
try/exceptaround a dynamic target type plus the boolean-string gotcha, the CSV parser exercises per-row resilience so one bad record doesn’t crash the whole import, and the log analyzer combines safe conversion with chained-comparison classification from 7.12 Chained Comparisons.”
Common Mistakes
- Letting one malformed CSV row crash the entire parse instead of catching the conversion failure per-row and continuing.
- Forgetting the boolean branch in
convert_inputneeds its own logic — callingbool(value)directly on a string would always returnTruefor any non-empty input. - Not handling the case where
target_typeitself is invalid or unexpected, instead of assuming callers always pass one of the anticipated types.
Add More Questions to This Guide
Know a question that should be here? Share it and help the community!
Open Google Form