Errors & Tracebacks
Errors are not failure, they are feedback. When Python cannot run a line it stops and prints a traceback. Read it from the bottom up: the last line names the error type and gives a short message, and the lines above point at where it happened.
The three you will meet first
- SyntaxError means the code is shaped wrong, so Python cannot even start. Usually a missing
:, a missing quote, or an unmatched bracket. - NameError means you used a name Python has never seen. Usually a typo, or using a variable before it is created.
- TypeError means an operation got the wrong kind of value, like adding a number to a string:
"age: " + 30.
print("hi) # SyntaxError: missing closing quote
print(totl) # NameError: 'totl' is not defined
print("n" + 5) # TypeError: can only concatenate str (not "int") to strHow to fix a TypeError when mixing text and numbers
Convert the number to text first with str(...), or better, use an f-string which converts for you:
age = 30
print("age: " + str(age)) # age: 30
print(f"age: {age}") # age: 30 (cleaner)Tracebacks feel scary at first. After a week of reading them they become the fastest debugging tool you own.
The snippet below is meant to define describe(age) so that describe(30) returns the string "age: 30", but it has a bug that raises a TypeError (you cannot add a number to a string). Fix the function so it returns the correct text. Use str(age) or an f-string. Then print describe(30).
This lesson is locked
Lessons open one at a time. Finish the previous lesson to unlock this one.