Home
Python
SyntaxError
Updated May 26, 2022
Dot Net Perls
SyntaxError. A Python program must have correct syntax. If it does not, a SyntaxError will occur—and the program will not be executed.
This error, unlike other errors, does not terminate a running program—an "except" statement cannot handle it. We must correct the error before our program can run.
IndentationError
Error
This program loops over a list of cat names. But in the for-statement, the trailing colon is missing. This results in a SyntaxError, which politely points out the missing colon character.
So To fix the program, we can add a colon to the indicated location. Until then, the program cannot be executed.
cats = ["Fluffy", "Mildred", "Joe"] for cat in cats print(cat)
File "C:\programs\file.py", line 5 for cat in cats ^ SyntaxError: invalid syntax
In this version of the program, no error occurs. The names of the three cats are correctly looped over and displayed to the console with the print statement.
for
print
cats = ["Fluffy", "Mildred", "Joe"] for cat in cats: print(cat)
Fluffy Mildred Joe
Try. A SyntaxError is not like other errors in Python. It cannot be handled in a try and except construct. There is no way to force the program to run correctly.
Note In an experiment, I found the SyntaxError penetrates all "except" statements. This error occurs before the program is run.
Summary. This error is a form of "compile-time" error: one that stops a program from ever being run. These errors prevent incorrect programs from ever causing trouble in the world.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on May 26, 2022 (rewrite).
Home
Changes
© 2007-2025 Sam Allen