Lessons 22–23 · 2 lessons · M. R. Fayziyeva, D. M. Sayfurov, N. S. Xaytullayeva. Informatics and Information Technologies, Grade 9. “Nashriyot uyi Tasvir”, Tashkent, 2020
23
Working with errors in Python
Textbook: pp. 57–58
GoalTells the kinds of errors in a program (syntax, name, indentation) apart, reads an error message, finds the line of the error and fixes it.
New words
error message: the text Python shows with the line number and the kind of error when a program cannot run · xatolik xabariSyntaxError: the code breaks the writing rules, e.g. a missing quote or bracket · SyntaxErrorNameError: a name is used that has not been given a value or is spelled differently · NameErrorIndentationError: the line has a wrong indent (extra spaces at the start) · IndentationError
Explanation
When there is an error the program does not run (or stops) and Python shows an error message that has the line number and the kind of error. The most common one is SyntaxError: a quote or bracket is not closed, or a writing rule of the language is broken. NameError appears when an unknown name is used: the variable has not been given a value, or the name is spelled differently letter by letter, for example Print instead of print. An extra space at the start of a line gives an IndentationError, because indentation is also part of the rules for Python. To fix an error, read the message from the end, check the line it points to (and the line before it if needed), correct it and run the program again. Finding errors is an everyday part of a programmer’s job, so do not be afraid of the message – it helps you.
Worked examples
A quote is not closed: print("Salom) – SyntaxError (the string is not closed). The correct form is print("Salom").
Unknown name: print(nom) – NameError, because the variable nom has never been given a value. Print("Salom") also gives a NameError, because Python tells Print and print apart.
Class activity
“Error hunter”: pairs give each other a 3-line code with one error inside; the partner names the kind of error, points to the line and fixes it. (Read the error message together.)
Practice
1
What is wrong in the code print("Salom) and how is it fixed?
SyntaxError: the quote is not closed. The correct form: print("Salom").
2
If print(yosh) is written but yosh has not been given a value, which error appears?
NameError
3
Fix this code: Print("Dunyo")
print("Dunyo")
4
Why does an extra space at the start of a line lead to an error?
In Python indentation shows the structure of the program, so an unexpected indent gives an IndentationError.