How do I write a simple python if else in one line? What are ternary operator in Python? Can we use one liner for complex if and else statements?
In this tutorial I will share different examples to help you understand and learn about usage of ternary operator in one liner if and else condition with Python. Conditional expressions (sometimes called a “ternary operator”) have the lowest priority of all Python operations. Programmers coming to Python from C, C++, or Perl sometimes miss the so-called ternary operator ?:. It’s most often used for avoiding a few lines of code and a temporary variable for simple decisions.
I will not go into details of generic ternary operator as this is used across Python for loops and control flow statements. Here we will concentrate on learning python if else in one line using ternary operator
Python if else in one line
Syntax
The general syntax of single if and else statement in Python is:
if condition: value_when_true else: value_when_false
Now if we wish to write this in one line using ternary operator, the syntax would be:
value_when_true if condition else value_when_false
In this syntax, first of all the else condition
is evaluated.
- If condition returns
True
thenvalue_when_true
is returned - If condition returns
False
thenvalue_when_false
is returned
Similarly if you had a variable assigned in the general if else block
based on the condition
if condition: value = true-expr else: value = false-expr
The same can be written in single line:
value = true-expr if condition else false-expr
Here as well, first of all the condition is evaluated.
- if condition returns
True
thentrue-expr
is assigned to value object - if condition returns
False
thenfalse-expr
is assigned to value object
For simple cases like this, I find it very nice to be able to express that logic in one line instead of four. Remember, as a coder, you spend much more time reading code than writing it, so Python's conciseness is invaluable.
Some important points to remember:
- You can use a ternary expression in Python, but only for expressions, not for statements
- You cannot use Python
if..elif..else
block in one line. - The name "ternary" means there are just 3 parts to the operator:
condition
,then
, andelse
. - Although there are hacks to modify
if..elif..else block
intoif..else block
and then use it in single line but that can be complex depending upon conditions and should be avoided - With
if-else blocks
, only one of the expressions will be executed. - While it may be tempting to always use ternary expressions to condense your code, realise that you may sacrifice readability if the condition as well as the true and false expressions are very complex.
Python Script Example
This is a simple script where we use comparison operator in our if condition
- First collect user input in the form of integer and store this value into
b
- If
b
is greater than or equal to0
then return "positive
" which will beTrue
condition - If
b
returnsFalse
i.e. above condition was not success then return "negative
" - The final returned value i.e. either "
positive
" or "negative
" is stored in objecta
- Lastly print the value of value
a
#!/usr/bin/env python3 b = int(input("Enter value for b: ")) a = "positive" if b >= 0 else "negative" print(a)
The multi-line form of this code would be:
#!/usr/bin/env python3 b = int(input("Enter value for b: ")) if b >= 0: a = "positive" else: a = "negative" print(a)
Output:
# python3 /tmp/if_else_one_line.py Enter value for b: 10 positive # python3 /tmp/if_else_one_line.py Enter value for b: -10 negative
Python if..elif..else in one line
Now as I told this earlier, it is not possible to use if..elif..else block
in one line using ternary expressions. Although we can hack our way into this but make sure the maximum allowed length of a line in Python is 79 as per PEP-8 Guidelines
Syntax
We have this if..elif..else block
where we return expression based on the condition check:
if condition1: expr1 elif condition2: expr2 else: expr
We can write this if..elif..else block
in one-line using this syntax:
expr1 if condition1 else expr2 if condition2 else expr
In this syntax,
- First of all
condition2
is evaluated, if returnTrue
thenexpr2
is returned - If
condition2
returnsFalse
thencondition1
is evaluated, if returnTrue
thenexpr1
is returned - If
condition1
also returnsFalse
then else is executed andexpr
is returned
As you see, it was easier if we read this in multi-line if..elif..else block
while the same becomes hard to understand for beginners.
We can add multiple if else block
in this syntax, but we must also adhere to PEP-8 guidelines
expr1 if condition1 else expr2 if condition2 else expr-n if condition-n else expr
Python Script Example-1
In this sample script we collect an integer value from end user and store it in "b
". The order of execution would be:
- If the value of
b
is less than0
then "neg
" is returned - If the value of
b
is greater than0
then "pos
" is returned. - If both the condition return
False
, then "zero
" is returned
#!/usr/bin/env python3 b = int(input("Enter value for b: ")) a = "neg" if b < 0 else "pos" if b > 0 else "zero" print(a)
The multi-line form of the code would be:
#!/usr/bin/env python3 b = int(input("Enter value for b: ")) if b < 0: a = "neg" elif b > 0: a = "pos" else: zero print(a)
Output(when if
condition is True
)
# python3 /tmp/if_else_one_line.py
Enter value for b: -5
neg
Output(when if
condition is False
and elif
condition is True
)
# python3 /tmp/if_else_one_line.py
Enter value for b: 5
pos
Output(when both if
and elif
condition are False
)
# python3 /tmp/if_else_one_line.py
Enter value for b: 0
zero
Python script Example-2
We will add some more else blocks in this sample script, the order of the check would be in below sequence:
- Collect user input for value
b
which will be converted to integer type - If value of
b
is equal to 100 then return "equal to 100
", If this returnsFalse
then nextif else
condition would be executed - If value of
b
is equal to 50 then return "equal to 50
", If this returnsFalse
then nextif else
condition would be executed - If value of
b
is equal to 40 then return "equal to 40
", If this returnsFalse
then nextif else
condition would be executed - If value of
b
is greater than 100 then return "greater than 100
", If this returnsFalse
then next go toelse
block - Lastly if all the condition return
False
then return "less than hundred
"
#!/usr/bin/env python3 b = int(input("Enter value for b: ")) a = "equal to 100" if b == 100 else "equal to 50" if b == 50 else "equal to 40" if b == 40 else "greater than 100" if b > 100 else "less than 100" print(a)
The multi-line form of this example would be:
#!/usr/bin/env python3 b = int(input("Enter value for b: ")) if b == 100: a = "equal to 100" elif b == 50: a = "equal to 50" elif b == 40: a = "equal to 40" elif b > 100: a = "greater than 100" else: a = "less than 100" print(a)
Output:
# python3 /tmp/if_else_one_line.py Enter value for b: 50 equal to 50 # python3 /tmp/if_else_one_line.py Enter value for b: 110 greater than 100 # python3 /tmp/if_else_one_line.py Enter value for b: -12 less than 100 # python3 /tmp/if_else_one_line.py Enter value for b: 40 equal to 40
Python nested if..else in one line
We can also use ternary expression to define nested if..else block
on one line with Python.
Syntax
If you have a multi-line code using nested if else block
, something like this:
if condition1: expr1 elif condition-m: expr-m else: if condition3: expr3 elif condition-n: expr-n else: expr5
The one line syntax to use this nested if else block
in Python would be:
expr1 if condition1 else expr2 if condition 2 else (expr3 if condition3 else expr4 if condition 4 else expr5)
Here, we have added nested if..elif..else
inside the else block
using ternary expression. The sequence of the check in the following order
- If
condition1
returnsTrue
thenexpr1
is returned, if it returnsFalse
then next condition is checked - If
condition-m
returnsTrue
thenexpr-m
is returned, if it returnsFalse
thenelse block
withnested if..elif..else
is checked - If
condition3
returnsTrue
thenexpr3
is returned, if it returnsFalse
then next condition inside thenested block
is returned - If
condition-n
returnsTrue
thenexpr-n
is returned, if it returnsFalse
thenexpr5
is returned from theelse
condition
Python Script Example
In this example I am using nested if else
inside the else block
of our one liner. The order of execution will be in the provided sequence:
- First of all collect integer value of
b
from the end user - If the value of
b
is equal to 100 then theif
condition returnsTrue
and "equal to 100
" is returned - If the value of
b
is equal to 50 then theelif
condition returnsTrue
and "equal to 50
" is returned - If both
if
andelif
condition returnsFalse
then theelse block
is executed where we havenested if and else
condition - Inside the
else block
, ifb
is greater than 100 then it returns "greater than 100
" and if it returnsFalse
then "less than 100
" is returned
#!/usr/bin/env python3 b = int(input("Enter value for b: ")) a = "equal to 100" if b == 100 else "equal to 50" if b == 50 else ("greater than 100" if b > 100 else "less than 100") print(a)
The multi-line form of this code would be:
#!/usr/bin/env python3 b = int(input("Enter value for b: ")) if b == 100: a = "equal to 100" elif b == 50: a = "equal to 50" else: if b > 100: a = "greater than 100" else: a = "less than 100" print(a)
Output:
# python3 /tmp/if_else_one_line.py Enter value for b: 10 less than 100 # python3 /tmp/if_else_one_line.py Enter value for b: 100 equal to 100 # python3 /tmp/if_else_one_line.py Enter value for b: 50 equal to 50 # python3 /tmp/if_else_one_line.py Enter value for b: 110 greater than 100
Conclusion
In this tutorial we learned about usage of ternary operator in if else statement
to be able to use it in one line. Although Python does not allow if..elif..else statement
in one line but we can still break it into if else
and then use it in single line form. Similarly we can also use nested if
with ternary operator in single line. I shared multiple examples to help you understand the concept of ternary operator with if and else statement of Python programming language
Lastly I hope this tutorial guide on python if else one line was helpful. So, let me know your suggestions and feedback using the comment section.