To create an inline if statement in Python, you can use the Python ternary operator.
a = 1
b = 2 if a == 1
print(b)
#Output:
2
You can also write inline if else statements with the ternary operator in Python.
a = 1
b = 2 if a > 2 else 3
print(b)
#Output:
3
When working in Python, the ability to create one-line expressions can be valuable to save space and simplify your code.
One such expression is the inline if statement.
You can create inline if statements with the Python ternary operator.
The Python ternary operator has the following form.
result = value X if condition else value Y
With the ternary operator, we can create an inline if statement.
Below is a simple example which shows you how to create an inline if statement in your Python code.
a = 1
b = 2 if a == 1
print(b)
#Output:
2
The above is equivalent to the following if statement in Python.
a = 1
if a == 1:
b = 2
print(b)
#Output
2
How to Create Inline If Else Statement in Python
You can also create inline if else statements with the ternary operator.
To write an inline if else statement, you just add else after the condition to check.
Below shows you an example of an inline if else statement in Python.
a = 1
b = 2 if a > 2 else 3
print(b)
#Output:
3
The above is equivalent to the following if statement in Python.
a = 1
if a > 2:
b = 2
else:
b = 3
print(b)
#Output
3
How to Create Inline If Elif Else Statement in Python
One final example is how you can combine multiple ternary operators into one to create an inline if elif else statement in your Python code.
To add an elif case to your conditional expression, in the else statement, simply add another ternary operator.
With this, you can create more complex conditional expressions in one line.
Below shows you how to create an inline if elif else statement in your Python code.
a = 1
b = 2 if a > 2 else (3 if a > 5 else 4)
print(b)
#Output:
4
The above is equivalent to the following if statement in Python.
a = 1
if a > 2:
b = 2
elif a > 5:
b = 3
else:
b = 4
print(b)
#Output
4
Hopefully this article has been useful for you to learn how to create inline if statements in your Python code.