Every Python coder hates semicolons
; to terminate statements.
If you’re like me and somebody shows you the following Python code, you’ll start to wonder if the person confused Python with Java or C++.
Python Semicolon Example [One-Liner]
Here’s how one may use the semicolon:
x = 'hi'; y = 'young'; z = 'friend'; print(x, y, z);
If you run this Python one-liner with semicolons, you’ll get the following output:
hi young friend
On the first view, it doesn’t even look like Python code! C++ has semicolons. Java has semicolons. But Python is supposed to be a semicolon-free language, isn’t it?
Python Semicolon Meme
Well, as it turns out, Python knows the
; quite well:
Python Semicolon Meaning
The meaning of the semicolon in programming languages such as Java and C++ is to terminate the current statement. In those languages, you’ll use it after every single line. Without it, the interpreter believes that the code has not terminated yet and it starts looking for more. Any Java or C++ coder knows situations where an error occurred because they forgot to use a semicolon in their code.
In Python, however, semicolons have a slightly different meaning. They allow you to create so-called compound statements. The
if construct is a compound statement. The
for loop is a compound statement. And, a number of semicolon-separated Python statements are compound statements.
For example, here are three Python statements:
print('a') print('b') print('c')
Now, let’s compress the same three Python statements into one by using the semicolon to create a compound statement:
print('a'); print('b'); print('c')
Different code. Same result.
Python No Semicolons
In many articles (here and here and here), Python coders recommend NOT to use semicolons. They are often considered not to be “Pythonic”. Why? Because they’re considered unreadable and unnecessary. The Zen of Python states that Python code must be readable:
>>> import this The Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those!
Readability counts! And: Sparse is better than dense!
Python Semicolon For Loop
Can you use the semicolon in combination with the for loop? Yes you can! But only if the whole statement begins with the for loop and you use the semicolon to create a compound statement as loop body. You cannot use the semicolon to separate a normal expression from a Python loop:
# ALLOWED print('a'); print('b'); print('c') # ALLOWED for i in range(3): print('a'); print('b') # NOT ALLOWED print('a'); for i in range(3): print('b')
The third statement throws a syntax error:
You can try this yourself in our interactive Python shell:
Exercise: Fix the faulty code and check the result.
Python Semicolon After Break
Can you use a semicolon after the break keyword? The answer is: yes, of course. You can use the semicolon almost everywhere. It doesn’t make any sense to do so though.
while True: if True: break; print('hi') # hi
Python Trailing Semicolon at End of Line
In Python, you can use the semicolon just right before the end of line. You could even end every line with a semicolon:
print('hi'); name = 'Ann'; print(name);
There is only one application I can think of: confusing readers to wonder which programming language you’re using. 😉
Python Semicolon Invalid Syntax
You’ll get a syntax error if you try to separate a normal Python statement from a block statement such as the for loop, the while loop, or the if block:
# NOT ALLOWED print('a'); for i in range(3): print('b')
Python throws a syntax error. There’s no reason for this other than that it’s confusing for the reader. In fact, the code is not ambiguous in this case—so Python could theoretically allow it. But it would open the door to extremely nested and confusing one-liners that no coder can understand.
(Well — I’d love to use this feature anyways to create even more advanced Python One-Liners. What can I do? I love them.)
Python Semicolon If
You can use the semicolon to compress a multi-line if body in a single line:
if 2+2 == 4: a = 4-2; print(a) # 2
Again, you cannot use the semicolon to separate a normal Python statement from an if block though:
a = 4-2; if 2+2 == 4: print(a) # 2
This results in a syntax error!
Python Semicolon Lambda
Can you use the semicolon inside a lambda function? The answer is no!
But you can define a simple function in a single line, separating the return statement from some other body statements through the semicolon:
def f(x): y = x+x; return x
If you print an example run, you’ll see that Python has no problem with this statement:
print(f(2)) # 2
For the lambda function, it doesn’t make sense. Why? Because the “body” of the lambda function calculates the return value of the function call. If you had a semicolon, you’d create multiple results—one for each semicolon-separated expression. It’s not clear how to resolve this clash! So, understandably, the creators of Python avoided this ambiguity.
Summary: Python Semicolon Use
You’ll use the semicolon mostly to write Python one-liners. Here are some usages of the semicolon:
- To write Python one-liners just for fun—if this is you, check out my book “Python One-Liners”!
- To write Python one-liners to be executed from your command line.
- To compress trivial statements and save a bit of space—such as
x=2; y=3and you don’t like
x, y = 2, 3.
- To pass one-liners into the
timeitfunction and measure the elapsed runtime.
Where to Go From Here?
Enough theory. Let’s get some practice!
Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation. To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?
You build high-value coding skills by working on practical coding projects!
Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?
If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.
Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.
While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com. He’s author of the popular programming book Python One-Liners (NoStarch 2020), coauthor of the Coffee Break Python series of self-published books, computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.