One-Line if..else Statement In Python

Python is a human-friendly programming language that provides different and easy-to-read structures for application 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. The one-line “if-else” is also named as condensing “if-else” as it takes less space and line.

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")
   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 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..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 to List comprehension where they use the same philosophy.

In the following example we check the count variable and if the count is over 10 the one line “if..else” returns 1 and if the count is less then 10 it returns 0.

count = 11

i=1 if count>10 else i=0

Leave a Comment