By the end of this tutorial, you will be able to catch, analyze, fix, and prevent various python syntax errors.
Materials Required: Latest version of Python (Python 3), an integrated development environment (IDE) of your choice (or terminal), stable internet connection
Prerequisites/helpful expertise: Basic knowledge of Python and programming concepts
Python syntax errors are extremely common, especially among those still learning the language. Although they can be frustrating, they are relatively easy to fix. Troubleshooting syntax errors will help you prevent them from occurring in the future.
Term | Definition |
Traceback | When an error occurs, you can trace it back to the source using this Python module. A traceback reports the function calls made at a given point in your code. Tracebacks are read from the bottom upwards. |
Syntax | In programming, syntax is the set of rules that defines the structure of a language. |
Interpreter | An interpreter is a computer program that translates source code (high-level programming language) into machine code that the computer can execute. |
Reserved keywords | Reserved keywords are words in a programming language that have predefined meanings. They are used to develop programming instructions. Reserved keywords cannot be used as identifiers for other elements. |
Parser | A parser is an interpreter component. It breaks information into smaller components that are easier for the interpreter to convert into machine code. |
If you have ever used a scientific or graphing calculator, you have likely already identified and resolved a syntax error on your own. Syntax errors occur when you enter a character or string that is unrecognizable to a system’s interpreter. Instead of executing the program, the parser raises the error, and the interpreter reports it.
Example:
If your error message contains the term 'SyntaxError,' there are a few possible culprits. Try troubleshooting it with the following checklist:
in
out of if x not in list
will prompt the interpreter to report an invalid syntax.
SyntaxError: 'continue' not properly in loop
IndentationError
and TabError
.
Can you identify the issue in this code?
1 2
positive = 'should' negative = 'shouldn't'
If you run these lines of code, you'll get a syntax error. The issue lies in Line 2, where the apostrophe in the word "shouldn't" closes the string, so the interpreter doesn't know what to do with the final "t". You can fix the error by using double quotes around "shouldn't" instead, like this:
1 2
positive = 'should' negative = "shouldn't"
Need help?
TypeError
and NameError
are a couple examples of exceptions. You can learn more about exceptions in Python’s errors and exceptions documentation.
You can now successfully identify each of the most common Python syntax errors. Now that you know what to look for, read the next section for guidance about where to look.
Carets and tracebacks can be extremely helpful in determining where the issue lies in your code. However, they aren’t always precise. The line or character that a caret points to indicates where the interpreter first noticed the issue. It doesn’t necessarily mean that is where the error occurred. At times, the code may run normally because it hasn’t yet needed to execute the instruction that contains the error. A traceback might even alert you to an error that exists in an entirely different file.
Example:
Here are a few actions you can take to trace a syntax error back to its origin:
Need help?
Python syntax errors are easy to correct. The challenge lies in finding out why they occur and where they exist in the code. In the following section, you will strengthen your understanding of how changes in syntax can impact the behavior of an interpreter or integrated development environment (IDE.)
Example
In the code block above, the error message reads SyntaxError: unmatched ')'
. If you examine line two, you will find the extra parentheses after print(message)
. Let’s remove that extra parentheses and try running the code.
Now, use the exercises below to practice identifying and correcting common mistakes on your own. If you'd like to practice in an interactive environment, you can copy and paste each exercise into your preferrend environment or click this link (note: it may take a few moments for the Jupyter Notebook to load).
Exercise 1
1 2
student_names = ['Luis', 'Divya', 'Maria', 'Mimi'] student_names.append('Arnold)
The string Arnold
is missing the closing quote mark.
Exercise 2
1 2 3 4
nums = [3, 8, -4, 22, 0] for num in nums num = num+1
The for loop is missing a colon.
Exercise 3
1 2 3 4 5
fruits = ['apples', 'bananas', 'oranges', 'grapes'] new_fruits = ['pears', 'cherries', 'tangerines'] fro fruit in new_fruits: fruits.append(fruit)
The reserved keyword for
is misspelled as fro
on line 3
As mentioned above, Python syntax errors are common. There is no guaranteed way to guard against them completely. However, you can take action to avoid them. Start by committing the following key takeaways to memory.
Another way to stay current on Python releases and tips is to get involved with the Python community. Consider subscribing to the free Python email newsletter or connecting with peers by joining the Python programming Slack channel. Here are a few other resources worth bookmarking:
Continue to build upon your foundational knowledge of Python by completing a Guided Project like Concepts in Python: Loops, Functions and Returns. For a deeper exploration of the language, consider enrolling in an online course like Python for Everybody from the University of Michigan on Coursera.
This content has been made available for informational purposes only. Learners are advised to conduct additional research to ensure that courses and other credentials pursued meet their personal, professional, and financial goals.