Python semicolon: Why semicolon is allowed in Python

0
42
Python semicolon - Why semicolon is allowed in Python

If you are coming from C/C++, Java, or PHP, you see many semicolons in the code. The semicolons used in these statements represent a statement termination. The primary purpose of semicolons (;) in different programming languages is to discontinue the current statement. 

Python semicolon

Can I use the semicolon in Python? Yes, you can use the semicolon. Python does not mandate the use of semicolons for delimiting statements. Semicolons can delimit statements if you wish to put multiple statements on the same line. Semicolons are used only in atypical situations in Python.

To split statements in Python, use the semicolons.

A semicolon in Python denotes separation rather than termination.

See the below example.

print('Millie'); print('Bobby'); print('Brown')

Output

Millie
Bobby
Brown

Even though the language supports a semicolon for delimiting statements, most Python programmers never use it in their code. The reason is simple. Python is supposed to be a clean and readable programming language. Unfortunately, syntactic characters like semicolons add unnecessary clutter.

Why semicolon is allowed in Python

Why are semicolons allowed? Well, you can say that it’s a simple design decision. Python is good without a semicolon, but somebody thought adding it to the language would be nice.

When to Use a Semicolon in Python

The primary logical question is when to use the semicolon? The answer is that there are certain situations where semicolons come in handy.

When you’re working in an interpreter REPL (Python interactive shell, IDLE, or ipython), a value of the last expression is printed to the screen. Usually, this is the intended behavior.

Running a shell script.

The most common use would be to run a short script from the shell using python -c ‘<script>’. In this case, we have to type many expressions separated with semicolons because we can’t use indentation here.

python -c 'import math; t = math.pow(2, 3); print(int(t))’

Another use case is while using the exec() method.

exec('for i in [11, 21, 46]: print(i);print(i*3)')

The semicolon is legal. But that doesn’t mean that you should use it. But use it when it is necessary.

Using Semicolons with Loops in Python

If you are using a for loop, then a semicolon can be used if the full statement starts with a loop, and you use a semicolon to form a coherent statement like the body of the loop.

for i in range (3): print ('Homer') ; print('Simpson')

That is it for this tutorial.

Leave A Reply

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.