The “if” statement in Python only executes a code block if it is “True”, otherwise the execution jumps to the “else” statement and executes it. However, while executing the program the code efficiency, time complexity, readability scale, and length of the program matter to the successful execution of the project. In such scenarios, the one-line approach gives flexible access to programmers to write a code in single line, in a concise, more readable way that fulfills the requirements needed to launch the project. 

How to Write a Simple If-Then-Else Statement on One Line in Python?

The one-line in Python provides flexibility to programmers and interpreters to comprehend the program in a more readable way. However, the multiline code squeezes in one line, hence, making the code computation speedy, within a few milliseconds you will get the desired output. 

The If-else statement execution will be performed on only one expression. The ternary expression is used for expression which means “three” parts are needed to complete the execution. However, to write a simple if-then-else statement on one line in Python, you need to specify three things:

  • if” keyword 
  • Then, condition 
  • Else” statement 

The syntax of the expression will look like as: 

a if <condition> else b

One Line Approach in Python

To perform the above code on one line in Python, utilize them if…in a statement. Performing the one-liner operation will make the code more interpretable and concise. However, one practice that followed to understand the one-liner command is to read from left to right. While reading you will understand the operation of the entire code in a single line:

if 50 in range(150): print("50==> falls in the range of 150")

Output

Now let’s do the above example by the if-then-else statement on one line in Python.

To write a simple if-then-else statement on one line in Python use the “if…in” structure or provide the condition in the if expression. 

However, the following command will return the “SyntaxError: invalid syntax” because there is ambiguity and an uncertain situation in the one-liner statement:

if 50 in range(150): print("50==> falls in the range of 150") else print("out of range")

Output

Python has flexible access to gracefully handle this “SyntaxError” within a one-line program. To fix and resolve the “SyntaxError: invalid syntax”  utilize the “ternary operator”. The “ternary operator” has three operands to “evaluate “true” if, <condition satisfied>, else evaluates “false”.

By utilizing these conditions, you can write a simple if-then-else statement on one line in Python. Below is the comparison of writing a simple if-then-else statement on one line with the multiline code in Python. 

In this example, the fixed real value is checked within the range using the range() function in the if condition. The “if…in” structure will check whether the value is present in the particular range. If so, print the associated message. If the condition isn’t met, the execution jumps to the else statement and executes the statement provided within its scope: 

input_value = 170
if 170 in range(150):
    print(input_value, "==> falls in the range of 150")
else:
    print(input_value, "out of range")

Output

The following program is the one-liner code representation of the above example. From left to right the code is readable, understandable, and concise:

print(130, "in range") if 130 in range(150) else print("out of range")

Output

Write a Simple Nested If-Then-Else Statement on One Line in Python

If you have multiple conditions then you can implement them using the if-then-elif-else statement. Here is how you can operate:

  • Define a variable.
  • Write a simple “if” statement provide the condition and end the syntax with the “:” colon. 
  • Utilize the “elif” to handle other possible conditions. Since it’s another if statement its syntax will also end at colon “:”.
  • Then complete the if-statement with the else statement and write a required program in its code block.
rain = True
if rain ==False:
    print("will play in ground")
elif rain == True:
    print("wouldn't play in ground")
else:
    print("maybe they'll go for playing")

Output

You can implement the above multi-line code in a simple if-then-else statement on one line in Python. The message associated with the “if” statement comes first, then write an if statement with the condition using the comparison “==” operator. After that, write else with its conditional message. Then write another “if-then-else” statement on the same one line another conditional message.

Example 1:

rain =True
print("wouldn't play in ground") if rain==True else print("will play in ground") if rain == False else print("maybe they'll go for playing")

Output

Example 2: 

Another example of doing the same operation: 

employee = 'D'

a = "Employee A Check-in" if employee == "A" else "Employee B Check-in" if employee == "B" else "Employee C Check-in" if employee == 'C' else "Employee D Check-in" if employee=='D' else "not-emplyee"
print(a)

Output

Comprehension One-Liner in Python Using “if-then-else” Statement 

Using comprehension in Python makes the code more concise and readable. In Python, the one-line if-then-else operation is utilized to handle the comprehension operation. Following are the use cases to utilize the if-then-else statement on one line in Python:  

Use Case 1: List Comprehension Using the “if-the-else” Statement 

The list comprehension gives the flexibility to write the if-then-else statement on one line in Python. The list comprehension makes the program as concise, readable, and simple as it can be. Here’s how you can utilize the list comprehension to write a simple if-ten-else statement on one line in Python:

  • Define data in a list using the square brackets “[ ]”. 
  • Within the list square brackets ([ ]), write the if then else statement. The if then else statement provides a condition and statement on the left of the bracket and the right of the list write the for…in structure to iterate the operation over each list element. 
list = [2,4,6,8,13]

print("\n One-liner List comprehensions:",  [i if i % 2 == 0 else "invalid operation" for i in list])

Output

Use Case 2: Dict comprehension Using the “if-the-else” Statement 

The same list comprehension one-line approach can be implemented for the dictionaries. However, to deal with the dictionary data in one line in Python, the dict comprehension approach is utilized. The dict comprehension will use the “for…in” structure to iterate over the dictionary values and sort them by value. Which key has the associative value, will print first:

# considering dictionary
dict = {'city': 15, 'ranking': 5, 'population': 12}
#sort dict by value
#alphabetically sorting
print("\n sorting Dictionary by Values:\n", {i if sorted(dict.values()) else "invalid operation" for i in dict})

Output

Use Case 3: Set Comprehension Using the “if-the-else” Statement 

To write a simple if-then-else statement on one line in Python for set data handling, utilize the “if-else” operation on the right of “{ }” brackets and use the for..in structure on the left of the “{ }” curly brackets. 

However, the dominant difference between the set and the list is that the list is represented as “[ ]” square brackets and the set is in “{ }” brackets:

set = {3, 6, 9, 4, 15}
setcomp= {i if i % 3 == 0 else "invalid operation" for i in set}
print("\n One-liner Set comprehensions:", setcomp)

Output

Use Case 4: Tuple Comprehension Using the “if-the-else” Statement  

Tuple comprehension is not utilized in regular practice so doesn’t dedicate special syntax for this purpose. Another reason is that if you write the if-then-else statement on one line in Python for the tuple it returns the output in the list format. However, by writing the entire if-then-else statement on one line for tuple data, you can utilize the “tuple()” function that wraps around the “if-else-then” one-liner statement:

tupl = (3, 6, 9, 4, 15)
print("\n One-liner Set comprehensions:",  tuple([i if i % 3 == 0 else "invalid operation" for i in tupl]))

Output

That is all about writing a simple if-then-else statement on one line in Python.

Conclusion

To write a simple if-then-else statement on one line in Python, use the “if” keyword, a conditional statement, and then the “else” code block. Writing the “if-then-else” statement on a single line can be achieved for the multiple “if” statements following the basic ternary operation expression “if, <condition>, else”. However, the if-then-else statement on one line is beneficial for performing the comprehension operations on any data in Python. This article has demonstrated writing a simple if-then-else statement on one line in Python.