Probably it’s not that line but a line before it. Python’s ability to tell you where an error really happens is fairly limited (although, it should be better at this). Imagine you have this:
print("I am a person"
print("I will print it")
If I throw that into a file named test.py
and run it I get your error:
$ python test.py
File "test.py", line 2
print("I will print it")
^
SyntaxError: invalid syntax
Now, the actual error is on line 1 because I forgot a )
at the end of line one, but Python is stupid and keeps trying to parse line 1 bleeding into line 2 before it detects an error. It’s when it detects an error that it reports the line, not where the error really is.
That means if you keep looking at line 9 in your code and it looks fine, you have to go one line at a time backwards to find your errors. Line 8, 7, 6, 5 and so one.
The next thing to do is run your code more often. If you’ve got an error at line 9 and have no idea what line caused it then you probably wrote all the code and ran it once. How I code is I write 1 or 2 lines, run it, write 1 or 2 lines more, run it, and repeat until I’ve written all the code. You should be running your code once for every 1 or 2 “lines” of code.
The only caveat is sometimes you have to do this:
while true:
pass
Pass tells python “I’ll fill this in later, so just pass it by”. Then you can run that to make sure it runs, and then fill in the while true
.
Final recommendation: If you hit an error like this and you’re completely stuck, don’t spend a week staring at your code. Delete it and write it again, but do it slowly one line at a time. Think of programming like a video game named Rogue where you get to a point and die so you just start over, but each run through the dungeon is easier because you get better.
Let me know if that helped.