Why does Python locate Syntax error in next line?

The entire code is here:

A change I made in the add_book_to_user function brought this error, but I did not change that line, and it didn’t throw an error before!

Traceback (most recent call last):
 File "populate.py", line 1, in <module>
   from TomeRater import *
 File "/home/ben/Nextcloud/codn/programming-with-Python.Cdcdm/Projekte/TomeRater/TomeRater.py", line 177
   if user_books:
                ^
SyntaxError: invalid syntax

Well, turns out I was missing a ) after print() statement on line 176. Why is Python finding the syntax error in the next line, not on line 176?

If you review the Python documentation:

8.1. Syntax Errors

Syntax errors, also known as parsing errors, are perhaps the most common kind of complaint you get while you are still learning Python:

 File "<stdin>", line 1
   while True print('Hello world')
                  ^
SyntaxError: invalid syntax

The parser repeats the offending line and displays a little ‘arrow’ pointing at the earliest point in the line where the error was detected. The error is caused by (or at least detected at) the token preceding the arrow: in the example, the error is detected at the function print() , since a colon ( ':' ) is missing before it. File name and line number are printed so you know where to look in case the input came from a script.

I have highlighted the relevant bit in bold.

The ^ symbol does not necessarily point to your error in the Python traceback - it shows you the furthest point that the Python interpreter was able to get to before it encountered your error, and threw the exception.

So, your error was detected at if user_books: because there was a missing ) before it, so this is as far as the interpreter got. :slight_smile:

4 Likes