Last updated: Apr 10, 2024
Reading time·2 min
The Pylance error "Statements must be separated by newlines or semicolons"
occurs when we have two or more statements on a single line, most commonly when
using print
as a statement instead of a function.
To solve the error, call print()
as a function instead.
Here is an example of how the error occurs.
import json # ⛔️ Statements must be separated by newlines or semicolons print json.dumps({'name': 'bobby'})
print
and json.dumps()
.To resolve the issue, call print()
as a function, because print
is a
function in Python 3 (not a keyword or a statement).
import json # ✅ Using print() as a function print(json.dumps({'name': 'bobby'}))
Notice that we called print() as a function with parentheses.
If you use Python 2, import print_function
from __future__
to make your code
Python 3 compatible.
from __future__ import print_function import json print(json.dumps({'name': 'bobby'}))
Here is another example of having multiple statements on the same line.
# ⛔️ Statements must be separated by newlines or semicolons a = 10 b = 20
To resolve the error, you have to move the second statement on a separate line.
a = 10 b = 20
You can also use semicolons to write multiple statements on a single line, but that is unusual and not recommended.
a = 10; b = 20
Semicolons are only necessary when you have to separate statements, in order to have multiple statements on the same line.
However, a much more common approach is to simply put each statement on a separate line.
Here is another example of using a semicolon to separate multiple statements.
a_list = ['bobby', 'hadz', 'com'] for item in a_list: print(item) # 👇️ semicolon if item == 'hadz': print('abc'); break
Notice that after the call to the print()
function, there is a semicolon.
The semicolon is used to separate the call to print()
and the use of the
break
statement.
When you separate the statements with a semicolon, they can be used on the same line.
However, a much more readable approach would be to write the two statements on separate lines.
a_list = ['bobby', 'hadz', 'com'] for item in a_list: print(item) if item == 'hadz': print('abc') break
I've also written an article on solving the Import "X" could not be resolved from source Pylance error.