Have a go at it. The editor and the docs panel are open, and your code is saved as you type. Running it needs a free account — you’ll come back to exactly what you wrote.
Type Errors: Text That Looks Like a Number
"3" and 3 look similar and behave completely differently:
"3" + "4" # "34" strings concatenate 3 + 4 # 7 numbers add "3" + 4 # TypeError: can only concatenate str (not "int") to str "3" * 2 # "33" repeats the string 3 * 2 # 6
This is the single most common error when data arrives from a file or a form, because everything read from a file starts as text. A column of numbers in a CSV is a column of strings until you convert it.
Converting:
int("3") # 3
float("3.5") # 3.5
str(3) # "3"
int("3.5") # ValueError! int() will not parse a decimal string
float("3.5") # 3.5 use float, then int() if you really want to truncateYour task:
total_readings is meant to add up a list of numbers that arrived as strings. It currently returns "101520" instead of 45, because it is concatenating text rather than adding numbers.
Fix it so it returns the numeric total. Values may be decimals like "2.5", so convert with float.
Example Tests
Three numeric strings add up instead of concatenating
Input: {"readings":["10","15","20"]}
Expected: 45
Decimal strings are handled, so float not int
Input: {"readings":["2.5","0.5"]}
Expected: 3
An empty list totals 0
Input: {"readings":[]}
Expected: 0
def total_readings(readings):
"""
Add up sensor readings that arrived as strings.
This currently glues the text together instead of adding. Fix it.
Args:
readings: a list of strings, each one a number, e.g. ["10", "15"]
Returns:
The numeric total.
"""
total = ""
for reading in readings:
total = total + reading
return totalRun your code to see results
⌘↵ runs against the visible tests