AI Ustoz UZ: learn artificial intelligence in Uzbek

Reading an error message and fixing it

Intermediate level · lesson 4 · about 12 min

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 range

The 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, KeyError are the most common.
  • Test the fix too.

Exercise

What error does print("Yosh: " + 20) give?

Answer and explanation
  1. TypeError: text cannot be added to a number; you need str(20). (correct answer)incompatible types: text + number.
  2. NameError: print was not found.print exists; the problem is the types.
  3. No error.Python does not allow such an addition.

Code exercises

  1. 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 with str(...); if the key is missing, use odam.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.