Reading an error message and fixing it
When Python reports an error, the last line of the message matters most: it gives the type and cause of the error. The lines above it show on which line of code it happened.
royxat = [1, 2, 3]
print(royxat[5])OutputIndexError: list index out of rangeThe most common errors: NameError (a variable was not defined), TypeError (incompatible types, for example text + number), IndexError (the list has no such index), KeyError (the dictionary has no such key). A number becomes text with str(son); to read a dictionary value without an error when the key is missing, use dictionary.get("key", "default").
If you ask artificial intelligence for help, give the full error message together with your own code. Read and test the suggested fix as well: it can lead to a different error.
Remember
- The last line of the message is the error type and cause.
NameError,TypeError,IndexError,KeyErrorare the most common.- Test the fix too.
Exercise
What error does print("Yosh: " + 20) give?
Answer and explanation
TypeError: text cannot be added to a number; you needstr(20). (correct answer)incompatible types: text + number.NameError:printwas not found.printexists; the problem is the types.- No error.Python does not allow such an addition.
Code exercises
- The code gives two errors. Fix them so the output is:
Ism: Ali,Yosh: 20,Shahar: nomalum(when there is no city key).
Hint: Turn the number into text withstr(...); if the key is missing, useodam.get("shahar", "nomalum").
Do the exercise in the app.
Practical task
Make a small error on purpose (for example, ask for a key that does not exist), read the error message and explain it in your own words.
- I reproduced the error
- I explained the message in my own words
Glossary
Interactive mode: search, progress and Python exercises.
