What Does Semicolon Do in Python

What Does Semicolon Do in Python

You can use a semicolon in Python to put multiple statements on one line.

For example:

print("Hello."); print("It is me."); print("How do you do?")

Output:

Hello.
It is me.
How do you do?

The semicolon acts as a statement delimiter. The Python interpreter knows that the statement ends after the semicolon and a new one begins.

Even though it is possible, most of the time you should not use a semicolon in Python.

When Use Semicolon in Python

A great use case for semicolons in Python is when you need to run a short Python script from the shell.

For example, open up your command line window and run the following command:

$ python -c 'for i in range (4): print ("Hi") ; print(f"The number is {i}")'

This results in the following:

Hi
This is the number 0
Hi
This is the number 1
Hi
This is the number 2
Hi
This is the number 3

As you might expect, adding the statements in the same line is the only easy way to run the script this way.

Conclusion

Today you learned what a semicolon does in python.

The semicolon delimits statements. This makes it possible to add multiple statements in one line by semicolon-separating them.

Thanks for reading. I hope you enjoy it.

Happy coding!

Further Reading

How to Write One-Liner For Loops in Python

Python Tips and Tricks

Share on facebook
Share on twitter
Share on linkedin

Leave a Comment

Your email address will not be published.