Common Type Mistakes
Unit ID: M02-U07 Estimated active time: 22-30 minutes
Diagnose before converting
When Python reports a type-related error, do not add random conversions until the code runs. First ask:
- What value do I have?
- What is its current type?
- What operation am I asking for?
- What type does that operation require?
- Is conversion valid for the task?
Mistake 1: adding text and a number
planned_hours = "32"
extension_hours = 2
total_hours = planned_hours + extension_hours
Python raises TypeError. If "32" is valid numeric input, convert it:
total_hours = int(planned_hours) + extension_hours
print(total_hours)
Result: 34.
Do not convert extension_hours to text unless the real goal is to produce a label.
Mistake 2: joining output unsafely
score = 8
print("Score: " + score)
Use an f-string:
print(f"Score: {score}")
Mistake 3: confusing assignment and comparison
status = "available"
print(status == "available")
The first = assigns. The second == compares. Using = where a comparison is required causes a syntax error in ordinary expressions.
Mistake 4: using a method without calling it
raw_name = " PYTHON "
clean_name = raw_name.strip
print(clean_name)
This stores the method object instead of calling it. Add parentheses:
clean_name = raw_name.strip()
print(clean_name)
Mistake 5: indexing beyond the string
code = "M02"
print(code[3])
Valid positive indexes are 0, 1, and 2. Index 3 raises IndexError. Inspect len(code) and check the required position.
Mistake 6: changing case after comparison
entered_status = " AVAILABLE "
matches = entered_status == "available"
clean_status = entered_status.strip().lower()
print(matches)
The comparison happened before cleaning, so matches is False. Clean first, then compare:
clean_status = entered_status.strip().lower()
matches = clean_status == "available"
Execution order applies to transformations as well as variable creation.
Repair practice
Diagnose and repair:
raw_duration = " 3.5 "
duration = raw_duration.strip
next_duration = duration + 1
print("Next duration: " + next_duration)
A clear repair is:
raw_duration = " 3.5 "
clean_duration = raw_duration.strip()
duration = float(clean_duration)
next_duration = duration + 1
print(f"Next duration: {next_duration}")
Takeaway
Type errors usually reveal a mismatch between the value you have and the operation you requested. Inspect, explain, and then make the smallest valid conversion. You are now ready to clean and summarise a complete supplied record.
