Imagine your Python program is syntactically incorrect. In that case, the interpreter will display an error message. It also points to the file and line where the error occurred.
Syntax error occurs when your code is grammatically off. In natural languages, grammar matters, but text with errors can usually be understood and read. Everything in programming is strict. The slightest violation and the program won't even start. An example would be a forgotten semicolon, misplaced brackets, and other details.
Here is an example of some code with a syntax error:
print('Hodor)
If we run the code above, we'll see the following message:
$ python index.py
File "index.py", line 1
print('Hodor)
^
SyntaxError: EOL while scanning string literal
On the one hand, it is easy to work with syntax errors because they're related to the grammatical rules of writing code, not to the meaning of the code. You can fix them once you find them. On the other hand, the interpreter cannot always clearly indicate this violation. Sometimes you should put a missing brace in a different place than the error message says.
Linter errors
We've already learned how to write simple programs, so we can explore how to write them correctly.
We should write the code in a certain way so it is easy to understand and maintain. There are coding standards — rules describing different aspects of writing code.
There is one Python standard — PEP8. It answers almost all questions about how to design any part of the code you can think of. This document contains all the rules that we must follow. We would advise newcomers to get used to looking at the PEP8 standard and to keep it in mind as you write your code.
Today, you don't need to remember all the rules because there are special programs that check the code automatically and tell you about any violations. These programs are linters. They ensure the code meets the standards. There are a few linters in Python, and the most popular one is flake8.
Take a look at an example:
result = 1+ 3
The linter says you are breaking a rule — E225 missing whitespace around operator. According to the standard, we must separate all operators from operands with spaces.
The E225 rule is one of many. Other ones describe indents, titles, brackets, mathematical operations, line lengths, and other aspects.
Particular rules may seem small and unimportant, but they work together to form the foundation of good code. A list of all flake8 rules is available in the documentation.
You will already be familiar with one linter because the Hexlet platform uses it to check your code in practice assignments. Soon you will start using it outside of Hexlet when you do training projects. You will set up a linter, and it'll check the code during real-life development and tell you about violations.