How to Write Python inline if statement
The if-else statement in Python is logical. Python does not use the ternary operator for inline if statement as other language uses. Instead, it offers a one-line code to evaluate the first expression if the condition is true. Otherwise, it evaluates the second expression.
Python inline if
The inline if-else expression in Python contains two statements and executes one of them based on the evaluation of the condition. There two types of if statements in Python.
- Simple if statement
- if-else expression statement
In a simple, if statement, we writing a condition, and based on that condition, the if block will be executed.
if condition: statement if condition: block
Let’s write an inline if statement in which if the condition is True, the expression will be executed.
Let’s see an example.
data = 21 if data < 22: print("It's cool")
You can see that we have written an inline if statement. But this statement does not contain else part.
Python inline if-else statement
The inline if-else expression in Python must contain an else clause.
x = 1 if y else 0
If you want to leave your ‘x’ variable value unchanged – assing old ‘x’ value.
Let’s see another example where we can write both if and else condition in inline.
data = 21 info = 19 print(data if info else 0)
If the info is 0 then it will output in 0.
data = 21 info = 0 print(data if info else 0)
That is it for Python inline if-else statement.