Skip to content

Python If Else shorthand with examples

Apr 8, 2023Abhishek EH2 Min Read
Python If Else shorthand with examples

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 = 10
2if 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 = 10
2if x%2 == 0:
3 print("Even")
5 print("Odd")

We can shorten it as shown below:

1x = 10
2print("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 = 20
2status = "adult" if age >= 18 else "minor"

Else if ladder

In Python you can write an else-if ladder as shown below:

1x = 10
2if x > 5:
3 print("greater than 5")
4elif x==5:
5 print("equal to 5")
7 print("less than 5")

The shorthand for the else-if ladder would be:

2print("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 = 5
2is_five = (False, True)[x == 5]

If you have liked article, stay in touch with me by following me on twitter.

Leave a Comment

© 2023 CodingDeft.Com