Python: How to Use the If-Else Statement in One Line

Python How to Use the If-Else Statement in One Line

Conditional statements in python are commands for controlling actions and decisions. These conditional constructs take action based on a condition. The given condition evaluates to true or false (if condition is true then take action).

In many cases, the executed action that is taken by a true condition is merely returning a value (assigning a new value to a target variable). Therefore, due to the simplicity of these types of if statements, many languages, including Python support inline if-else expressions.

In this article, you will learn how to use inline conditional expressions in Python.

The method of using if and else in the same line is usually referred to it as conditional expressions or ternary operations. The most common ternary conditional operator is ?: for many languages.

For example, the subsequent ternary expression: (a ? b : c), which returns b if a is true, or to c if the a condition is false. However, there is a different syntax for Python. Its ternary expression looks like the following: (a if condition else b), just as before, the expression returns a if condition is true, otherwise to b if condition is false.

In the later sections, we will explain how to use inline if-else expressions with examples.

When and How to Use Inline If-Else Expressions?

A ternary conditional expression returns a value. Unlike an if statement which executes a statement following the condition that is found to be true. Additionally, this statement may not evaluate to a value. Therefore, when dealing with a ternary conditional operation, we are actually expecting the expression to evaluate to certain value.

Inline conditional expressions can make our code compact and readable, not to mention quickly performing simple tests without writing multiple line of codes. Let’s write a simple script:

a = input('Enter a one digit number:')
b = 0

if int(a) > 9:
    b = 9
else:
    b = a
print(f'The result: {b}')

This is the output when you enter 10:

Enter a one digit number:10
The result: 9

Notice how many lines of code there are just for one program. Now, let’s follow the previously mentioned ternary expression syntax to make our code more compact and readable:

a = input('Enter a one digit number:')
b = 9 if int(a) > 9 else a
print(f'The result: {b}')

As we can see, our script is concise and direct. As well as, the results should be similar to before.

Furthermore, since the conditional expression will evaluates to a value. Then, we can make our code even smaller by using the expression within the print method:

a = input('Enter a one digit number:')
print(f'The result: {9 if int(a)>9 else a}')

Let’s break the conditional expression down to clear any confusion. As simple as the expression, if the condition is true (a is greater than 9), then the expression returns 9. Otherwise, the expression returns the value of a. In other words: the condition is in the middle. Which is the first part of the expression that Python executes. If the condition evaluates to true, then the operand at the beginning is evaluated. Otherwise, the operand that’s at the end is evaluated.

Nested Inline If-Else Expression

Just as the traditional if-else conditional construct, the ternary operations in Python support several conditions. Similarly, if one condition is true the expression will evaluates to the corresponding operand then skips the rest.

Even though testing multiple conditions is possible using one line, it is not recommended. As we have noted, using conditional expressions is meant for simplicity and readability. However, this is may not be true when testing several inline if-else expressions. In later paragraphs we will first see when it is a good idea to use ternary expression, then when it’s not.

Let’s check the following program for discount offers by a shopping site:

payment = int(input('How much did you pay? '))
discount = -1

if payment > 100:
    discount = 10
elif payment > 50:
    discount = 5
else:
    discount = 1

print(f'You\'ll pay {discount}% less')

Now let’s re-write the code by implementing conditional expressions:

payment = int(input('How much did you pay? '))
discount = 10 if payment > 100 else 5 if payment > 50 else 1

print(f'You\'ll pay {discount}% less')

Let’s check the results after passing 70 as input:

How much did you pay? 70
You'll pay 5% less

Suppose we used the conditional expression for the subsequent case:

payment = int(input('How much did you pay? '))
discount = 15 if payment > 200 else 12 if payment > 100 else 7 if payment > 50 else 1
print(f'You\'ll pay {discount}% less')

In the above code snippet, it is clear as day that we can’t keep track of the conditions as easily as before. Long inline if-else expressions are usually hard to read. Although it’s a good idea here to implement a traditional conditional statement, we can break the above inline if-else expression into multiple lines of code.

By wrapping the expression in parenthesis ( ), we will be able to break down one line of code into multiple lines without causing errors:

payment = int(input('How much did you pay? '))
discount = (15 if payment > 200 else
            12 if payment > 100 else
             7 if payment > 50 else 1)
print(f'You\'ll pay {discount}% less')

Adding new lines to the expression makes reading it more human-friendly.

Keep in mind when the expression has too many conditions, we’re better off using the traditional if-else statement.

One Line If-Else Statement with Python Tuples

Another way to use conditional expressions involves tuples.

Although this method is not widely common, it is effective.

As we know by now, Python ternary expressions follow this syntax : (a if condition else b). However, to use tuples, we must re-write the expression as the following : (b, a)[condition]. That is, the expression evaluates to a if the condition is true, otherwise to b when the condition is false.

Let’s check the following code snippet:

payment = int(input('How much did you pay? '))
discount, no_discount = ('You are eligible for a discount',
              'You are not eligible for a discount')

print((no_discount, discount)[payment > 1000])

Next, we will run the program and type 1400 as input to check the results:

How much did you pay? 1400
You are eligible for a discount

As can we observe from the code snippet and the results, the second argument of the tuple (that is: discount) corresponds to True. In contrast, the first argument (that is: no_discount) will be returned if the condition evaluates to False.

Keep in mind this method is not efficient and is generally avoided by programmers. One of the reasons (other than the confusing positions of true and false arguments); is both arguments in the tuple will be evaluated, and this is not true when it comes to using ternary expressions (where only one operand will be evaluated).

Conclusion

In this tutorial, we’ve gone over the known methods to use a conditional expression (if-else) in one line.

Furthermore, we’ve shown multiple examples and explanations to help the reader to understand the uses of Python ternary operations. Not to mention when to implement it and when to avoid it.

0 Shares:
Subscribe
Notify of
guest
Receive notifications when your comment receives a reply. (Optional)
Your username will link to your website. (Optional)

0 Comments
Inline Feedbacks
View all comments
You May Also Like