if elif else Statements in Python

 


if, elif, else Statements in python

In this article, we are going to discuss if, else, else statements in python what are they syntax

if Statements in Python allows us to tell the computer to perform alternative actions based on a certain set of results.

Verbally, we can imagine we are telling the computer:

"Hey if this case happens, perform some action"

We can then expand the idea further with elif and else statements, which allow us to tell the computer:

"Hey if this case happens, perform some action. Else, if another case happens, perform some other action. Else, if none of the above cases happen, perform this action."

Let's go ahead and look at the syntax format for if statements to get a better idea of this:


if case 1:
    perform case 1
if case 2:
    perform case 2
if case 3:
    perform case 3

Let's see a quick example of this:

1st Example:

if True:

Read Also

    print("It was true")

OUTPUT

It was true

Let's add some else logic:

2nd Example:

X = True
if X:
    print("X was True")
else:
    It will be printed when X is not True

OUTPUT

It will be printed when X is not True

Multiple Branches

Let's get a fuller picture of how far if, elif, and else can take us!

We write this out in a nested structure. Take note of how the if, elif, and else line up in the code. This can help you see what if is related to what elif or else statements.

We'll reintroduce a comparison syntax for Python.


loc = "Bank"
if loc == "Car Showroom":
    print("Welcome to the car showroom")
elif loc == "Bank":
    print("Welcome to the Bank")
else:
    print("Where are you?")

OUTPUT

Welcome to the Bank

Note: How the nested if statements are each checked until a True boolean causes the nested code below it to run. You should also note that you can put in as many elif statements as you want before you close off with an else.

Let's create two more simple examples for the if, elif, and else statements:


person = "Ram"
if person == "Ram":
    print("Welcome Ram")
else:
    print("What is your name?")

OUTPUT

Welcome Ram

person == "George"
if person == "Ram":
    print("welcome Ram")
elif person == "George":
    print("welcome George")
else:
    print("welcome, what is your name?")

OUTPUT

Welcome George

Indentation

It is important to keep a good understanding of how the indentation works in Python to maintain the structure and order of your code. We will touch on this topic again when we start building out functions!

Post a Comment