Common Python Syntax Errors and Solutions

This is meant to be a Python syntax cheatsheet for beginners and practitioners alike. Unlike Java, C, or C++, Python doesn’t use braces or semicolons to define its functions. No, Python’s function hierarchy is defined by whitespace or indentation. We will be covering how to use whitespace and indentation in Python and more.

In this post, we will cover:

  • Python Syntax Basics
    • Python Indentation and Whitespace Syntax Basics
    • Syntax and Best Practice for Importing Libraries and Modules in Python
    • Syntax for Declaring Variables in Python
    • Comments Syntax in Python
    • Placeholder Code Syntax in Python
    • List Comprehension Syntax in Python
  • Examples of Common Python Syntax Errors and Solutions
    • print Invalid Syntax for Python 2 vs Python 3
    • IndentationError: Expected an Indented Block
    • ImportError or ModuleNotFoundError: No Module Named xyz

Code for Python Syntax Errors and Solutions.

Python Syntax Basics

Once you’ve downloaded Python and opened up your first .py file, what do you do? Before you can get started crafting your own code, you have to learn the syntax of the language. One of the best things about Python is that it’s closer to English than most other programming languages. Let’s take a look at some of the things that separate Python syntax from English.

Python Indentation and Whitespace Syntax Basics

Indentation and whitespace are two important syntax concepts in Python. Python uses indentation and whitespace to check where a block of code belongs. Each “level” of logic requires each of its lines of code to be on the same indentation. Note that Python indentations are whitespace.

Correct indentation is most important when you are writing functions. The function declaration below shows that the code that belongs to a function should be indented. Any code that is not indented like the ... lines above the function declaration and at the bottom, is not part of the function.

def function():

Other than functions, it is also customary to leave a newline at the end of a Python file with no whitespaces.

Syntax and Best Practice for Importing Packages and Modules in Python

One of the most important things you’re going to need to do while programming is import other packages, libraries, or modules. In the example below, there are four import statements. We can import an entire package by calling import. If we only want to import a specific function we can use the from keyword and then the import keyword.

The fromimport keyword combination also allows importing from submodules in a package, denoted by a period. Finally, you can use the * sign to import all the submodules from a package, however this is bad practice. Some IDEs will do this by default and I just want to point this out so you don’t do this.

# imports
import os # good
from os import dup # good
from os.path import dirname # good
from os import * # BAD

Comment Syntax in Python

Another important part of programming are comments. Comments are meant to be additional bits of information that tell you more about the code. Common things that are commented include the function, the parameters, and the return values of functions and classes.

In Python, there are three basic ways to correctly comment. Single line comments can be started with a # sign. Multiline comments can be done two ways. Python accepts the use of either triple single quotes or triple double quotes to start and end multiline comments. Note that using triple double quotes technically makes a string, but can serve as a comment.

# single line comment
multiline comment
also a multiline comment

Placeholder Code Syntax for Python

Placeholder code is less common than importing packages or making comments. The most common use of placeholder code is for establishing functions before filling them out. You can use the ... symbol to represent code that you’ll fill out later so that most IDEs won’t mark it wrong. 

However, using the ... will throw an error during compilation. If you need to compile your program without filling out a function, you can use the pass keyword. The pass keyword exits the function.

def function():
   # ... (this doesn't compile)
   pass # placeholder code that does compile

List Comprehension Syntax in Python

Let’s look at something that is unique to Python – list comprehension. Yes, other programming languages have lists, but not like this. List comprehension might be one of the most iconic Pythonic things.

In the example below, I’ve shown three ways to do list comprehension in Python. First, you can directly write the values to the list. Second, you can use the range function to create a list. Thirdly, we can use the special list comprehension in Python that allows us to create a list from another list with for and in.

abc0 = [0, 1, 2]
abc1 = range(3)
abc2 = [_ for _ in range(3)]

Examples of Common Python Syntax Errors and Solutions

I’m also going to cover some examples of common Python syntax errors and solutions here. This is mostly for future me, as I covered in Why You Should Document Your Code and Solutions. These consist of errors I’ve run into more than once while either learning Python or using it in app development.

print Invalid Syntax for Python 2 vs Python 3

The only time I really encounter this error now is when I’m looking at old Python code. Python 2 is now deprecated and Python 3 has a different print syntax than Python 2. Python 3 requires you to use parentheses after the print keyword to print correctly, Python 2 did not.

In the example below, I use an f-string. We’ll cover this in more depth below.

print "abc" # Python 2
print(f"abc{abc0}") # Python 3

IndentationError: Expected an Indented Block

The “IndentationError: Expected an Indented Block” error is an error that I mostly encountered when I first started learning Python. This pretty much only comes up if you have incorrect indentation on a function or class. The way to solve this is to indent your lines correctly as shown above in the Indentation and Whitespace section.

ImportError or ModuleNotFoundError: No Module Named xyz

There are three ways that this error commonly happens. Firstly, there could be a Python environment issue. Secondly, it could do with the structure of your folders. Thirdly, it could be because you don’t have the right package installed.

If you’re having a Python environment issue when you get an import error, the first thing you want to do is check that you’re running the right environment. You can check this in the terminal or the IDE. If you are using VSCode, your Python environment is displayed in the bottom right corner.

Check Python Environment (VSCode)
Check Python Environment (VSCode)

See your environment in the terminal by looking to the left side for Anaconda.

Check Python Environment (Conda)
Check Python Environment (Conda)

The second type of common error with packages involving your directory structure only happens when you’re creating larger applications. Files can only “see” files that are either in the same directory as them or in a directory below them. This means that files do not automatically see the packages created in folders above them.

In the example below, files in src can access any other file. Files in analyze can access other files in nlp, scrape, and tst. The folders under tst can only access files in tst or below them, they don’t see the folders in src.

Example Directory Structure
Example Directory Structure

You can fix this error by moving your file into a directory that has sight of your desired packages, use a sys.path hack, or use pip install -e . to install the parent package in editable mode.

Thirdly, you may simply not have installed the package. This is the easiest fix, all you have to do is use pip or conda, whichever package manager you are using, to install your package. This usually comes up when there are packages that are Python SDK wrappers for other packages. For example, FFmpeg has multiple Python packages such as ffmpeg, python-ffmpeg, and ffmpeg-python, where each has a different API.

Python SyntaxError: invalid syntax from f strings

As shown above in the invalid print syntax segment, f-strings may also cause syntax errors in Python. Python 3 lets you use the character f in front of a string to format the string and insert variables directly by putting the variable name between braces in the string. The Python 3 f string provides the same functionality as the .format() function used in Python 2.

In the example below, xyz and f”abc{abc0}” are the same string. We’re using the abc0 variable from above again.

xyz = "abc{x}".format(x=abc0)
print(f"abc{abc0}") # Python 3

Summary of Common Python Syntax Errors and Solutions

This is an evolving post I’ll continue to add to as I continue to learn more Python. This post covers common Python syntax errors and the solutions I find to them. We cover the basics of Python syntax in a cheat sheet like fashion along with descriptions. 

Further Reading

I run this site to help you and others like you find cool projects and practice software skills. If this is helpful for you and you enjoy your ad free site, please help fund this site by donating below! If you can’t donate right now, please think of us next time.


Make a one-time donation

Make a monthly donation

Make a yearly donation

Choose an amount


Or enter a custom amount

Your contribution is appreciated.

Your contribution is appreciated.

Your contribution is appreciated.

DonateDonate monthlyDonate yearly
Yujian Tang