Python if else shorthand

Introduction

Do you want to write efficient and concise Python code? If so, then learning how to use Python’s if else shorthand is a great place to start. This blog post will explore three different ways to use if else shorthand in Python.

ternary operator

The ternary operator is a condensed version of an if else statement. It is written as a single line of code and evaluates a condition to return one of two values. The syntax for using the ternary operator looks like this:

[on_true] if [expression] else [on_false]


For example, if we wanted to print “positive” if the number x is greater than 0, and “negative” if it is not, we could use this ternary operator:

print("positive") if x > 0 else print("negative")


if expressions

If expressions are another concise way to write an if else statement. This form of the if else statement can be used as a value. It is written in this format:

[expression] if [condition] else [expression]


For example, if we wanted to set the variable y to a value of 10 if the number x is greater than 0, and a value of -10 if it is not, we could use this if expression:

y = 10 if x > 0 else -10


if else lambdas

If else lambdas are a way to write a single line of code that returns a value based on a condition. This form of the if else statement is written like this:

(lambda: [on_true], lambda: [on_false])[test]()


For example, if we wanted to return the string “positive” if the number x is greater than 0, and the string “negative” if it is not, we could use this if else lambda:

(lambda: "positive", lambda: "negative")[x > 0]()


Conclusion

If else shorthand is a great way to write efficient and concise Python code. By learning different types of if else shorthand, such as the ternary operator, if expressions, and if else lambdas, you can save time and reduce the amount of code you write.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s