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
Truethenvalue_when_trueis returned - If condition returns
Falsethenvalue_when_falseis 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
Truethentrue-expris assigned to value object - if condition returns
Falsethenfalse-expris 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..elseblock 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 blockintoif..else blockand 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
bis greater than or equal to0then return “positive” which will beTruecondition - If
breturnsFalsei.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
condition2is evaluated, if returnTruethenexpr2is returned - If
condition2returnsFalsethencondition1is evaluated, if returnTruethenexpr1is returned - If
condition1also returnsFalsethen else is executed andexpris 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
bis less than0then “neg” is returned - If the value of
bis greater than0then “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
bwhich will be converted to integer type - If value of
bis equal to 100 then return “equal to 100”, If this returnsFalsethen nextif elsecondition would be executed - If value of
bis equal to 50 then return “equal to 50”, If this returnsFalsethen nextif elsecondition would be executed - If value of
bis equal to 40 then return “equal to 40”, If this returnsFalsethen nextif elsecondition would be executed - If value of
bis greater than 100 then return “greater than 100”, If this returnsFalsethen next go toelseblock - Lastly if all the condition return
Falsethen 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
condition1returnsTruethenexpr1is returned, if it returnsFalsethen next condition is checked - If
condition-mreturnsTruethenexpr-mis returned, if it returnsFalsethenelse blockwithnested if..elif..elseis checked - If
condition3returnsTruethenexpr3is returned, if it returnsFalsethen next condition inside thenested blockis returned - If
condition-nreturnsTruethenexpr-nis returned, if it returnsFalsethenexpr5is returned from theelsecondition
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
bfrom the end user - If the value of
bis equal to 100 then theifcondition returnsTrueand “equal to 100” is returned - If the value of
bis equal to 50 then theelifcondition returnsTrueand “equal to 50” is returned - If both
ifandelifcondition returnsFalsethen theelse blockis executed where we havenested if and elsecondition - Inside the
else block, ifbis greater than 100 then it returns “greater than 100” and if it returnsFalsethen “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.


