Python – Conditional Statements

One of the most important thing which you need to learn in Python is the use of conditional statement.
These are small code snippets which will help you solve multiple problems in a project or any hackathon.

Conditional statements help us to apply a particular constraint on the data set. Suppose you want to pull the data only for a particular employee or user; or you want to filter the data for a particular date; or you want to count how many male and female are there in the given data set, every where you will be using these conditional statements.

Every programming language have almost the same conditional statement and Python is not an anomaly.

We will try to keep it crisp in this post but it will keep on haunting you in the upcoming posts, so, try to learn the basics here before proceeding.

There are three types of conditional statement used in Python:
1. if
2. else
3. elif

Python, like other programming languages, supports the usual logical conditions:

1. Equals: x == y
2. Not Equals : x != y
3. Greater than : x>y
4. Greater than or equal to : x >= y
5. Less than : x < y
6. Less than or equal to : x <= y

1. if is simple conditional operator where you put a condition and filter the data set or mould the data set in a particular manner.

P.S. – Python follows indentation religiously, so be very careful in writing codes

A simple example of if operator

2. else operator compliments the if operator. Suppose, the if condition is not satisfied, then the control will move to else

A simple if and else combo

3. elif helps in putting as many conditions in your program as you like. Look at the example below

A simple example of all the three conditional statements

Let’s try some more examples
1. Applying more than one condition using “and” keyword

2. Applying more than one condition using “or” operator

3. Applying condition on a list

4. Apply condition on a string

5. Multiple if statement

6. If the first “if” condition is true, then the conditional statements will break and even if the “else” condition is true, the control will not go to it. See the example below where both, if and else statements are true

7. if True condition

Summary of the day
1. You learned the basics of if, else and elif conditional statements
2. You can run multiple conditional statements in a nested query
3. You have practiced a few examples of using the conditional statement in different ways

If you have time, make a small calculator using everything you have learnt today

A very simple calculator using if statement

Keep practicing 🙂




Author: TheDataMonk

I am the Co-Founder of The Data Monk. I have a total of 6+ years of analytics experience 3+ years at Mu Sigma 2 years at OYO 1 year and counting at The Data Monk I am an active trader and a logically sarcastic idiot :)