How to Write the Python if Statement in one Line
- online practice
Have you ever heard of writing a Python if statement in a single line? Here, we explore multiple ways to do exactly that, including using conditional expressions in Python.
The if statement is one of the most fundamental statements in Python. In this article, we learn how to write the Python if in one line.
The if is a key piece in writing Python code. It allows developers to control the flow and logic of their code based on information received at runtime. However, many Python developers do not know they may reduce the length and complexity of their if statements by writing them in a single line.
For this article, we assume you’re somewhat familiar with Python conditions and comparisons. If not, don’t worry! Our Python Basics Course will get you up to speed in no time. This course is included in the Python Basics Track , a full-fledged Python learning track designed for complete beginners.
We start with a recap on how Python if statements work. Then, we explore some examples of how to write if statements in a single line. Let’s get started!
How the if Statement Works in Python
Let’s start with the basics. An if statement in Python is used to determine whether a condition is True or False . This information can then be used to perform specific actions in the code, essentially controlling its logic during execution.
The structure of the basic if statement is as follows:
The <expression> is the code that evaluates to either True or False . If this code evaluates to True, then the code below (represented by <perform_action> ) executes.
Python uses whitespaces to indicate which lines are controlled by the if statement. The if statement controls all indented lines below it. Typically, the indentation is set to four spaces (read this post if you’re having trouble with the indentation ).
As a simple example, the code below prints a message if and only if the current weather is sunny:
The if statement in Python has two optional components: the elif statement, which executes only if the preceding if/elif statements are False ; and the else statement, which executes only if all of the preceding if/elif statements are False. While we may have as many elif statements as we want, we may only have a single else statement at the very end of the code block.
Here’s the basic structure:
Here’s how our previous example looks after adding elif and else statements. Change the value of the weather variable to see a different message printed:
How to Write a Python if in one Line
Writing an if statement in Python (along with the optional elif and else statements) uses a lot of whitespaces. Some people may find it confusing or tiresome to follow each statement and its corresponding indented lines.
To overcome this, there is a trick many Python developers often overlook: write an if statement in a single line !
Though not the standard, Python does allow us to write an if statement and its associated action in the same line. Here’s the basic structure:
As you can see, not much has changed. We simply need to “pull” the indented line <perform_action> up to the right of the colon character ( : ). It’s that simple!
Let’s check it with a real example. The code below works as it did previously despite the if statement being in a single line. Test it out and see for yourself:
Writing a Python if Statement With Multiple Actions in one Line
That’s all well and good, but what if my if statement has multiple actions under its control? When using the standard indentation, we separate different actions in multiple indented lines as the structure below shows:
Can we do this in a single line? The surprising answer is yes! We use semicolons to separate each action in the same line as if placed in different lines.
Here’s how the structure looks:
And an example of this functionality:
Have you noticed how each call to the print() function appears in its own line? This indicates we have successfully executed multiple actions from a single line. Nice!
By the way, interested in learning more about the print() function? We have an article on the ins and outs of the print() function .
Writing a Full Python if/elif/else Block Using Single Lines
You may have seen this coming, but we can even write elif and else statements each in a single line. To do so, we use the same syntax as writing an if statement in a single line.
Here’s the general structure:
Looks simple, right? Depending on the content of your expressions and actions, you may find this structure easier to read and understand compared to the indented blocks.
Here’s our previous example of a full if/elif/else block, rewritten as single lines:
Using Python Conditional Expressions to Write an if/else Block in one Line
There’s still a final trick to writing a Python if in one line. Conditional expressions in Python (also known as Python ternary operators) can run an if/else block in a single line.
A conditional expression is even more compact! Remember it took at least two lines to write a block containing both if and else statements in our last example.
In contrast, here’s how a conditional expression is structured:
The syntax is somewhat harder to follow at first, but the basic idea is that <expression> is a test. If the test evaluates to True , then <value_if_true> is the result. Otherwise, the expression results in <value_if_false> .
As you can see, conditional expressions always evaluate to a single value in the end. They are not complete replacements for an if/elif/else block. In fact, we cannot have elif statements in them at all. However, they’re most helpful when determining a single value depending on a single condition.
Take a look at the code below, which determines the value of is_baby depending on whether or not the age is below five:
This is the exact use case for a conditional expression! Here’s how we rewrite this if/else block in a single line:
Much simpler!
Go Even Further With Python!
We hope you now know many ways to write a Python if in one line. We’ve reached the end of the article, but don’t stop practicing now!
If you do not know where to go next, read this post on how to get beyond the basics in Python . If you’d rather get technical, we have a post on the best code editors and IDEs for Python . Remember to keep improving!
You may also like
How Do You Write a SELECT Statement in SQL?
What Is a Foreign Key in SQL?
Enumerate and Explain All the Basic Elements of an SQL Query
Python One Line Conditional Assignment
Problem : How to perform one-line if conditional assignments in Python?
Example : Say, you start with the following code.
You want to set the value of x to 42 if boo is True , and do nothing otherwise.
Let’s dive into the different ways to accomplish this in Python. We start with an overview:
Exercise : Run the code. Are all outputs the same?
Next, you’ll dive into each of those methods and boost your one-liner superpower !
Method 1: Ternary Operator
The most basic ternary operator x if c else y returns expression x if the Boolean expression c evaluates to True . Otherwise, if the expression c evaluates to False , the ternary operator returns the alternative expression y .
Let’s go back to our example problem! You want to set the value of x to 42 if boo is True , and do nothing otherwise. Here’s how to do this in a single line:
While using the ternary operator works, you may wonder whether it’s possible to avoid the ...else x part for clarity of the code? In the next method, you’ll learn how!
If you need to improve your understanding of the ternary operator, watch the following video:
You can also read the related article:
- Python One Line Ternary
Method 2: Single-Line If Statement
Like in the previous method, you want to set the value of x to 42 if boo is True , and do nothing otherwise. But you don’t want to have a redundant else branch. How to do this in Python?
The solution to skip the else part of the ternary operator is surprisingly simple— use a standard if statement without else branch and write it into a single line of code :
To learn more about what you can pack into a single line, watch my tutorial video “If-Then-Else in One Line Python” :
Method 3: Ternary Tuple Syntax Hack
A shorthand form of the ternary operator is the following tuple syntax .
Syntax : You can use the tuple syntax (x, y)[c] consisting of a tuple (x, y) and a condition c enclosed in a square bracket. Here’s a more intuitive way to represent this tuple syntax.
In fact, the order of the <OnFalse> and <OnTrue> operands is just flipped when compared to the basic ternary operator. First, you have the branch that’s returned if the condition does NOT hold. Second, you run the branch that’s returned if the condition holds.
Clever! The condition boo holds so the return value passed into the x variable is the <OnTrue> branch 42 .
Don’t worry if this confuses you—you’re not alone. You can clarify the tuple syntax once and for all by studying my detailed blog article.
Related Article : Python Ternary — Tuple Syntax Hack
Python One-Liners Book: Master the Single Line First!
Python programmers will improve their computer science skills with these useful one-liners.
Python One-Liners will teach you how to read and write “one-liners”: concise statements of useful functionality packed into a single line of code. You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.
The book’s five chapters cover (1) tips and tricks, (2) regular expressions, (3) machine learning, (4) core data science topics, and (5) useful algorithms.
Detailed explanations of one-liners introduce key computer science concepts and boost your coding and analytical skills . You’ll learn about advanced Python features such as list comprehension , slicing , lambda functions , regular expressions , map and reduce functions, and slice assignments .
You’ll also learn how to:
- Leverage data structures to solve real-world problems , like using Boolean indexing to find cities with above-average pollution
- Use NumPy basics such as array , shape , axis , type , broadcasting , advanced indexing , slicing , sorting , searching , aggregating , and statistics
- Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning
- Create more advanced regular expressions using grouping and named groups , negative lookaheads , escaped characters , whitespaces, character sets (and negative characters sets ), and greedy/nongreedy operators
- Understand a wide range of computer science topics , including anagrams , palindromes , supersets , permutations , factorials , prime numbers , Fibonacci numbers, obfuscation , searching , and algorithmic sorting
By the end of the book, you’ll know how to write Python at its most refined , and create concise, beautiful pieces of “Python art” in merely a single line.
Get your Python One-Liners on Amazon!!
IMAGES
VIDEO