DEV Community

Cover image for Python If Else shorthand with examples
collegewap
collegewap

Posted on • Originally published at codingdeft.com

2

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:

x = 10
if x > 5:
  print("greater than 5")
Enter fullscreen mode Exit fullscreen mode

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")
Enter fullscreen mode Exit fullscreen mode

We can shorten it as shown below:

x = 10
print("Even") if x%2 == 0 else print("Odd")
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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")

Enter fullscreen mode Exit fullscreen mode

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")
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay