Python is the programming language that is efficient and readable while writing operators. It has multiple operators which are used to perform different tasks, such as comparing and combining two different strings, and integer values, or checking any provided condition. Moreover, Python doesn’t have a ternary operator. Therefore, the “inline if-else” condition can be used for checking multiple conditions at once in a single line.
In this post, we will discuss the usage of the inline if-else in Python.
What is Inline If-Else in Python?
In Python, an inline if-else statement is a logical statement that offers a compact version of the “if-else” condition in a single line. It preserves the code quality by replacing the number of lines of “if-else” code. Additionally, an inline statement is restricted and includes several “if-else”, if they are carefully cascaded. It must include the else clauses, otherwise, it won’t give results. Moreover, the “inline if-else” statement can be used while assigning values or other functions to increase the code readability and makes it more concise.
Here is the syntax of the “inline if-else” statement:
In the above-given code block:
- “<first_expr>” expression is executed if the provided condition becomes true.
- <second_expr> expression is executed if the provided condition is not satisfied.
- Both conditions are executed from the left to right side.
How to Use Inline If-Else in Python?
To better understand the working of the inline if-else statement, let’s have a look at the below provided multiple examples.
Example 1: Using Inline If-Else Statement With Boolean Values
In this example, we will check the color of the fruit “mango” by utilizing the “inline if-else” statement. First, declare a string variable and initialize with the “green”:
Next, the “n” variable is specified with an “if-else” condition that returned “Yes” if the string variable has the “yellow”, else it will return “No”
Now, call the “print()” function and pass the “n” variable that holds the conditions checking result:
According to the below-given output, the specified condition has not satisfied and returned “No”:
Example 2: Using Inline If-Else With Integer Values
Let’s take one more example, create “m” variable and initialize with the integer value “20”:
We have declared “n” variable that is equal to “1”, and check the specified condition:
Use the “print()” function to get the filtered result:
That’s all about the usage of the if-else condition in Python.
The inline if-else statement is a logical statement that offers a compact version of the “if-else” condition in a single line. It preserves the code quality by replacing the number of lines of “if-else” code. In Python, there is no ternary operator., therefore the “if-else” can be used in a single line that has the same effects as ternary operators. This post illustrated about the usage of the inline if-else in Python.