Learn Python #3 - Conditional Statements - if, if elif, and if elif else

Learn Python #3 - Conditional Statements - if, if elif, and if elif else

python

ยท

2 min read

Hello everyone, Today we are going to talk about the if, if elif, and if elif else conditional statement in Python and try to understand the different use cases and different ways of writing the same conditional statement.

What the hell if, if elif, and if elif else is?

In Python to execute the statement based on certain conditions being satisfied, we use the if statement. Let's look at a few of the examples:-

Example 1:-

going_to_office = True #variable that stores the boolean value
if going_to_office == True: print("Work from office")

Here instead of checking the values of going_to_office against True, we can directly write it as

if going_to_office: print("Work from office")

So if the condition is evaluated to True then the print statement is executed else not.

Example 2:-

Let us say we have

going_to_office = True
if going_to_office: 
     print("Work from office")
else:
     print("Enjoy work from home")

So if the condition on line#1 is not satisfied then the control moves to else and the statement under the else condition is executed.

Example 3:-

Let us say we have the if elif else condition

going_to_office = False
be_at_home = True
if going_to_office: #condition1
    print("Work from office")
elif be_at_home:    #condition2
    print("Enjoy work from home")
else:
    print("Work from Starbucks")

So if the condition1 and condition2 are not satisfied then the statement under the else condition is executed.

index.png

Conclusion

The basic conditional statements like if, if elif and if elif else is easy to understand, so do let me know what you guys think of this article๐Ÿ’ก.

Thanks in advance for reading this article...๐Ÿš€

More than happy to connect with you on @twitter, LinkedIn