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:
x = 10
if x > 5:
print("greater than 5")
There are no shorthands for simple if statements.
If else statements
Consider the following if else statement:
x = 10
if x%2 == 0:
print("Even")
else:
print("Odd")
We can shorten it as shown below:
x = 10
print("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:
age = 20
status = "adult" if age >= 18 else "minor"
print(status)
Else if ladder
In Python you can write an else-if ladder as shown below:
x = 10
if x > 5:
print("greater than 5")
elif x==5:
print("equal to 5")
else:
print("less than 5")
The shorthand for the else-if ladder would be:
x=4
print("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.
x = 5
is_five = (False, True)[x == 5]
print(is_five)
Top comments (0)