Dark theme

When Python reacts


The message it comes back with is:

File "test1.py", line 4
    agents.append([random.randint(0,99),random.randint(0,99))
                                                            ^ SyntaxError: invalid syntax

You'll see that the caret is pointing at the end of the line, but this isn't where the problem is. This isn't unusual with syntax issues. If a piece of punctuation is missing the system will interpret the line as trying to do something different until that view breaks down, and it will flag the issue there. Here we're missing a square bracket towards the start of the line; as Python works its way across the line it first thinks we're trying to append a single number:

agents.append(random.randint(0,99))

then it hits the comma and assumes we're appending a tuple:

agents.append(random.randint(0,99),random.randint(0,99))

before finally hitting the ending square bracket and wondering what's going on. It's therefore there it flags the issue. With other issues Python might not realise there's an issue until the very end of the code, where it will suddenly flag that something is wrong – these are the hardest issues to solve as the message is almost no help at all and you need to close read the whole file. As these are often issues of indenting, that's the first thing to check.

Here's a file with five syntax issues in it: test2.py. Without running it, how many can you fix? Run it to check you caught them all.