AppDividend
Latest Code Tutorials

Python semicolon: Why semicolon is allowed in Python

0

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 main 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. Semi-colons can be used to delimit statements if you wish to put multiple statements on the same line. Semi-colons are used only in atypical situations in Python.

To split statements in Python, use the semicolons.

A semi-colon in Python denotes separation rather than termination. See the following example.

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

Output

Millie
Bobby
Brown

Even though the language supports a semi-colon 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. Syntactic characters like semi-colons 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 it would be nice to add it to the language.

When to Use a Semicolon in Python

The main 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 whole 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

Your email address will not be published.

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