Welcome to the sixth lecture in this series. Now we are getting deep into programming and we will learn the use of “if statements” in Python.
“if statements” are extremely important in programming as they allow us to build programs that can make decisions based on some condition.
If Statement
“If statement” is used to execute a program based on several decisions. For example, read this:
“If its hot,
It’s a hot day
Drink plenty of water
Otherwise, if it’s cold
Its a cold day
wear warm clothes
Otherwise, it’s a lovely day”
In the above statements, we are making some decisions based on some conditions. The first statement is a condition, the second one is its implication and the third one is executing a decision.
The if statements work similarly.
Let’s look at it in programming.
We are introducing a boolean variable.
is_hot = true
Now we will add an “if statement”
if is_hot:
print("It's a hot day.")
Now this expression will be executed if the above condition is true. To come out of an “if statement” you would have to press “Shift + Tab” to get your cursor in line for a new line of code.
Now, let’s run this program.
Now let’s play with this program.
See what happens if I turn the above condition to false.
It is clear that if the condition is false, the “if statement” is not executed. Now we are going to add a second condition that will be executed if the first condition is not fulfilled.
is_hot = False
if is_hot:
print("It's a hot day.")
print("Drink plenty of water")
else:
print("It's a cold day.")
print("Wear warm clothes.")
print("Enjoy your day")
The “if” condition is false thus the interpreter will go to the next set of codes under the “else” indent.
“If statement” is not necessarily limited to two conditions only. You can chuck in as many conditions as you would like. Let’s add some conditions to this program.
We are defining another condition with a boolean variable. Let it be:
if_cold = True
Now we can add a third condition to our program. It works as this
is_hot = False
if_cold = True
if is_hot:
print("It's a hot day.")
print("Drink plenty of water")
elif is_cold:
print("It's a cold day.")
print("Wear warm clothes.")
else:
print("It's a lovely day")
print("Enjoy your day")
Now if it’s neither a hot day nor a cold one, then it’s a lovely day. Here we have used a new function “elif” to define a new condition between first “if” and last “else”. You can add as many “elif” as many you like.
Exercise
Solution
Wrap Up!
I hope you guys are enjoying this series. The next lecture will be on the use of operators in Python.
Peace!
Leave a Reply