How to Identify and Resolve Python Syntax Errors

Written by Coursera • Updated on

By the end of this tutorial, you will be able to catch, analyze, fix, and prevent various python syntax errors.

[Featured image] A person in a white long-sleeved shirt sits at a desk investigating a Python syntax error in thier code on a laptop and tablet.

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.

Glossary

TermDefinition
TracebackWhen 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.
SyntaxIn programming, syntax is the set of rules that defines the structure of a language.
InterpreterAn interpreter is a computer program that translates source code (high-level programming language) into machine code that the computer can execute.
Reserved keywordsReserved 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.
ParserA parser is an interpreter component. It breaks information into smaller components that are easier for the interpreter to convert into machine code.

What is a syntax error?

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: Syntax Error Example 1

How to determine the cause of a Python syntax error

If your error message contains the term 'SyntaxError,' there are a few possible culprits. Try troubleshooting it with the following checklist:

  • Did I misspell a keyword? A typo or misspelling could be causing you to see an invalid syntax error.

  • Am I missing a keyword entirely? Leaving out a critical keyword will return the same syntax error as a misspelling. For example, leaving in out of if x not in list will prompt the interpreter to report an invalid syntax.

  • Have I misused a Python keyword? Remember that you cannot use a reserved keyword to define a function. A keyword also cannot be assigned to a variable. Sometimes, you might move a keyword outside of a loop during development. In this case, your syntax error message will be more specific. It will read: SyntaxError: 'continue' not properly in loop

  • Are your keyword arguments in the correct order? In both function definitions and function calls, positional arguments must always be followed by keyword arguments.

  • Are the spaces consistent? Python uses whitespace (indentation) to determine the scope, or, logical grouping of blocks of code. Accordingly, the indentation level of each statement must be consistent throughout the entire block to avoid invalid syntax. Two subclasses of Python syntax errors exist surrounding indentation problems: IndentationError and TabError.

  • Did you use the proper case for variable names and function names? Constant variable names should be in uppercase. In contrast, variable names in a function must be in lowercase. Function names follow the same case rules as variable names.

  • Is there any missing or mismatched punctuation? Brackets, parentheses, commas, and quotes are frequently to blame for Python syntax issues. Remember that using (=) to separate values and keys doesn't work for Python syntax. Use the colon instead. The colon is also essential for ending block statements like loops. A few more punctuation issues you can check for include:

    • Closing square brackets and parentheses
    • Commas after dictionary elements
    • Missing or misused quotes in a string. Python syntax allows the use of single (‘), double (“) and triple (“‘) quotes for string literals as long as the same one used to begin it also ends it. For example, when using a single quote to start a string literal, the same single quote must be used to end it.

Try it yourself

Can you identify the issue in this code?

PYTHON
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:

PYTHON
1
2
positive = 'should' 
negative = "shouldn't"

Need help?

What if the above section didn't cover my Python syntax error? Sometimes, a syntactically correct statement can still cause an error during execution. These execution errors are called exceptions. 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.

How to identify the source of the error

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: Syntax Error Example 2

Step by step

Here are a few actions you can take to trace a syntax error back to its origin:

  1. Start at the traceback and move backward through the code until you find the error.

  2. Think about every part of your code that may be affected. A traceback might alert you to an error that exists in an entirely different file.

  3. If you are copying a piece of code from another source, retrace your steps and compare each line of your code to the source’s code. Keep in mind that the piece of code you’re copying may contain the syntax error.

  4. Evaluate your programming environment. If you feel like you have tried everything and you still haven’t found the error, you and the interpreter may not be looking at the same code. One way to check for this issue is to intentionally place a syntax error somewhere in your code and attempt to run it. If the new error goes undetected, your issue likely lies in the setup of your environment.

Need help?

I still can’t find the error. What can I do? If you still can’t locate the syntax error in your code, consider reviewing syntax rules in the Python Language Reference. You can also try taking a short break. Returning to this tutorial with a fresh perspective may help you discover something you missed.

How to resolve Python syntax errors

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 Syntax Error Example 3

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. Example 3 Correct

Try it yourself

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

PYTHON
1
2
student_names = ['Luis', 'Divya', 'Maria', 'Mimi']
student_names.append('Arnold)

The string Arnold is missing the closing quote mark.

Exercise 2

PYTHON
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

PYTHON
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

How to prevent Python syntax errors

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.

Key takeaways

  • Strings require quotes on both ends.
  • Consistency in spacing and indentation is essential to Python syntax.
  • Use colons when writing loops, conditionals, and function definitions.
  • Keyword arguments should always follow positional arguments.
  • Tracebacks are not always precise. You may need to start at the traceback and work your way up through the code to find your syntax error.
  • You can not assign a reserved keyword to a variable. You can also bookmark this page or a few resources in the next section for reference.

Resources

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:

Expand your knowledge of Python with Coursera.

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.


Written by Coursera • Updated on

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.

Learn without limits