How to Use Semicolon in Python (Examples)

Semicolons are allowed in Python, but this is a rarely used style. However, in certain situations, a semicolon can come in handy.

Table of Contents

Tip: click or tap on images to view them in full screen.

About Semicolons in Python


The semicolon can be used at the end of a statement or expression in Python. These are examples of working code with semicolons:

>>> def c(value):
	value += 1;
	return value;

>>> print("Hello world!"); c(1);
Hello world!
2

Because Python uses line breaks as terminators instead of semicolons, the ending semicolon is redundant in this case.

So why do we need a semicolon in Python? We can use a semicolon as a separator in Python code.


Where and How You Can Use Semicolons in Python (Examples)


You can use semicolons in Python to separate multiple statements on one line. The semicolon indicates where one instruction/command ends and where the next begins.


Python Shell/IDLE

small program on a single line

>>> import random; random.randint(5, 10)
8

define a simple function

>>> def c(value): value += 1; return value

setup for timeit module

>>> import timeit
>>> s = "test = []; num = 1"
>>> timeit.timeit("test.append(num)", setup=s)
0.1927696485803348

OS command line

* running a short script from the command line

$ python -c "import sys; print(sys.stdout)"

Where You Shouldn't Use Semicolons


According to PEP 8, "compound statements (multiple statements on the same line) are generally discouraged". PEP 8 is a Style Guide for Python Code. This document introduces coding conventions for Python developers.

The following example is shown in the Style Guide to be incorrect:

# Wrong:
if foo == 'blah': one(); two(); three()

# Wrong:
if foo == 'blah': do_blah_thing()
do_one(); do_two(); do_three()

Using semicolons can reduce the readability of your code and confuse people.


Semicolons in pth Files


The semicolon is used in .pth files (Python path configuration file). Such files are located in Python's site-packages folder. The main purpose of pth file is to contain local paths to Python packages that need to be made importable. When the Python interpreter starts, local paths are added to sys.path.

These files can also contain code as a string. If the pth file contains code, that code is executed as is. However, the code must be limited to one line. In this case, the use of a semicolon is simply necessary.



Popular posts from this blog