Table of Contents
Have you ever wondered if you can write if else statements in the same line like a ternary operator: x=a>10?"greater":"not greater"
in Python?
In this article, we will see how to write Shorthands for if else statements in Python.
Simple if condition
We can write a simple if condition in Python as shown below:
1x = 102if x > 5:3 print("greater than 5")
There are no shorthands for simple if statements.
If else statements
Consider the following if else statement:
1x = 102if x%2 == 0:3 print("Even")4else:5 print("Odd")
We can shorten it as shown below:
1x = 102print("Even") if x%2 == 0 else print("Odd")
The syntax here is
action_if_true if condition else action_if_false
You can assign the result to a variable as well:
1age = 202status = "adult" if age >= 18 else "minor"3print(status)
Else if ladder
In Python you can write an else-if ladder as shown below:
1x = 102if x > 5:3 print("greater than 5")4elif x==5:5 print("equal to 5")6else:7 print("less than 5")
The shorthand for the else-if ladder would be:
1x=42print("greater than 5") if x > 5 else print("equal to 5") if x==5 else print("less than 5")
Using tuples as a ternary operator
Python has the following syntax to assign the boolean value of the result. However, this is a confusing syntax and is not used widely.
1x = 52is_five = (False, True)[x == 5]3print(is_five)
Do follow me on twitter where I post developer insights more often!