Day #41 - Short hand if else

Day #41 - Short hand if else

ยท

3 min read

Introduction

Welcome to my 41st blog post. We have already learned about the if...else statement in Python, but there is an alternative way to write the if...else block in a short-form method. In today's blog, I am going to share my learnings from Day #41 of my Python coding journey. On day 41, I learned about the short way to write the if-else block. Let's dive into more details.

So let's get started......

If....Else in One line

To write the if-else statement there is a shorthand syntax that can be used to write the same

Example -

a = 2
b = 330
print("A") if a > b else print("B")

Note - You can also have multiple else statements on the same line

Example -

Using multiple else statements -

a = 330
b = 330
print("A") if a > b else print("=") if a == b else print("B")

Example -

a = 330000
b = 3303
print("A") if a > b else print("=") if a == b else print("B")

c = 9 if a>b else 0
print(c)

Output -

A
9

If..else breakdown

result = value_if_true if condition else value_if_false

Above Syntax is equivalent to the below if-else statement

if condition:
    result = value_if_true
else:
    result = value_if_false

Pros and Cons Shorthand Syntax

Pros -

  • The shorthand syntax is a convenient way to write simple if-else statements, especially when you want to assign a value to a variable based on a condition.

  • It can be useful when the programs are short and easy to understand.

Cons -

  • Shorthand syntax is not suitable for more complex situations where you need to execute multiple statements or perform more complex logic.

  • In those cases, it's better to go with the full if-else syntax.

Resources Used

You can watch the video of Day#41 by clicking on the below link ๐Ÿ‘‡๐Ÿ‘‡๐Ÿ‘‡๐Ÿ‘‡๐Ÿ‘‡

Conclusion

Thanks, guys for going through this blog post. Through this Blog post, we learned about a Shorthand way to write an if-else statement. We also understood the pros and cons of using the shorthand syntax and when to use them.

Thank you if you read this post and have found this post useful. I hope you have joined me and are enjoying my magical journey of Python coding. This is it for Day #41

See you in the next one.....


About Me

Hey Guys, I am Chintan Jain from CodeWithJain. I am a trader and content creator. I am also passionate about tech and hence wanted to explore the field of tech. I always wanted to learn to code so I watched many tutorials but procrastinated practicing coding. To get into the habit of coding consistently I am starting to BLOG with HASHNODE on daily basis.

I will document my coding journey from scratch and share my daily learnings in a blog post on HASHNODE. I hope you all will enjoy my content and my coding journey.

So what are you waiting for, smash the FOLLOW and LIKE buttons and follow along my coding journey, a step to create more beautiful digital products and empower people.


ย