Updated: Aug 21, 2020
In real life as well there are situations where we need to take decisions depending upon conditions. For example If it does not rain today we will have a cricket match else we will stay at home. For this kind of behavior , python has if,else statements.
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 happened, perform this action."
Let's go ahead and look at the syntax format for if statements to get a better idea of this:
if case1: perform action1 elif case2: perform action2 else: perform action3
Let's see a quick example of this:
if True: print('It was true!')
It was true!
Let's add in some else logic:
x = False if x: print('x was True!') else: print('I will be printed in any case where x is not true')
It will be printed in any case where x is not true
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 == 'Auto Shop': print('Welcome to the Auto Shop!') elif loc == 'Bank': print('Welcome to the bank!') else: print('Where are you?')
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 = 'Piyush' if person == 'Piyush': print('Welcome Piyush!') else: print("Welcome, what's your name?")
person = 'Mayank' if person == 'Piyush': print('Welcome Piyush!') elif person =='Mayank': print('Welcome Mayank!') else: print("Welcome, what's your name?")
num1 = 20 if num1 < 10: print("Hello") elif num1 == 20: print("value is 20") else: print("Not a valid condition")
value is 20
In situation where we care about only the true condition and we don’t have any else block, we use pass.
It will do nothing if the condition is not true.
name = "Keith" if name == "Kevin": print("Hello Kevin") else: pass
It is important to keep a good understanding of how indentation works in Python to maintain the structure and order of your code.
That is it for conditionals . Next we are going to study about iterations (loops)