Python is a human-friendly programming language which provides different and easy to read structures for applications development. The if..then..else is one of the most popular statements in Python and other programming languages. The if..then..else statement is generally implemented for multiple conditions in multiple lines.
Normal if..then..else Statement
Let's take a look at the regular or normal if..then..else statement. In the following example, we will check the age variable if it is less or higher than 18. As we can see the if..then..else is implemented in multiple lines.
age = 24 if age < 18: print("Under 18") else: print("Over 18")
One Line if..then..else Statement Syntax
The one line or oneliner if..then..else statement is actually a ternary operator where a condition is provided and if the provided condition is true first provided value is returned and if not true the second provided value is returned.
RETURN_WHEN_TRUE if CONDITION else RETURN_WHEN_FALSE
- RETURN_WHEN_TRUE will be evaluated and returned if the provided CONDITION is True.
- RETURN_WHEN_FALSE will be evaluated and returned if the provided CONDITION is False.
One Line if..then..else Statement Example
Let's implement the multi-line if..then.else statement example in a one-line version. We will use the previously defined syntax and provide the age < 18 as the CONDITION.
print("Under 18") if age < 18 else print("Over 18")
As you can see this one-liner if..then..else syntax is very similar List comprehension where they use the same philosophy.