If-Elif-Else statement on one line in Python

avatar

Borislav Hadzhiev

Last updated: Aug 30, 2022

banner

Photo from Unsplash

If-Elif-Else statement on one line in Python #

Use a nested ternary operator to implement an if-elif-else statement on one line. The first ternary should check for a condition and if the condition is not met, it should return another ternary that does the job of an elif/else statement.

main.py
my_str = 'bob' result = "Anonymous" if not my_str else my_str.upper() if len( my_str) > 2 else my_str.capitalize() print(result) # 👉️ 'BOB' # ------------------------------------------ my_num = 50 result = 10 if my_num > 100 else 20 if my_num < 100 else 0 print(result) # 👉️ 20

We used a nested ternary operator to implement an if-elif-else statement on one line.

The ternary operator is very similar to an if/else statement.

main.py
name = 'Bob' result = 'James Doe' if not name else name print(result) # 👉️ 'Bob'

The example checks if the name variable is falsy and if it is, the string "James Doe" is returned, otherwise the name variable is returned.

To have an inline if-elif-else statement, we have to use a nested ternary.
main.py
my_num = 50 result = 10 if my_num > 100 else 20 if my_num < 100 else 0 print(result) # 👉️ 20

The first ternary in the example checks if the variable stores a value greater than 100.

If the condition is met, the number 10 gets returned.

If the condition is not met, the else statement runs and the nested ternary operator gets returned.

You can use parentheses to wrap the nested ternary operator to make your code a little easier to read.

main.py
my_num = 50 result = 'a' if my_num > 100 else ('b' if my_num < 100 else 'c') print(result) # 👉️ 'b'

If the condition is not met, the else statement runs and the nested ternary checks for another condition.

The role of the nested ternary is very similar to the role of an elif/else statement.

The nested ternary checks if the variable stores a value less than 100 and if the condition is met, the string b gets returned. This is the elif statement.

If the condition is not met, the else statement runs and the string c gets returned.

Here is how we would implement the ternary operator of the example using if/elif/else statements.

main.py
result = '' if my_num > 100: result = 'a' elif my_num < 100: result = 'b' else: result = 'c' print(result) # 👉️ 'b'

Using if/elif/else statements is a bit more readable, but it is also a bit more verbose.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.