# If else statement in python

Hello Techies!!

Hope you all are doing great! 🙂

Let’s start by learning conditional statements today.

Now, you must be thinking, what are conditional statements?

A statement that controls flow of execution depending upon condition.

Example: If it rains, I can’t go out else I will.

Now, above example is a conditional statement because my going out depends on whether it rains or not ( a condition ).

How can we use it in python or programming? What is the point of having this?

Let’s learn this with an example, what if we want to find maximum of two given numbers.

def max_two(a, b):
if a>b:
print(“a is greater than b”)
elif a==b:
print(“a is equal to b”)
else:
print(“b is greater than a”)

Let’s break down the example and understand the steps.

We first declared a function with two parameters or arguments ‘a’ and ‘b’.

if a > b:
print(“a is greater than b”)

Here, we are asking compiler to check if a>b. Now, by doing that, there are few things to notice here :

1. if keyword is used to write conditions
2. a>b is a boolean logical expression which returns true or false. This means we can only write boolean expressions inside if statement.
3. That colon(:) is used to define scope of the if statement, in other words, lets compiler know that if statement starts here.
4. If expression is true then print – a is greater than b on console.

elif a == b:
print(“a is equal to b”)

elif keyword is used to write else if conditions.

Here, this statement will only get executed if first statement returns false.

First the compiler will check if a is greater than b, if it returns false, then it checks whether a is equal to b or not, if that returns false as well, it enters into else block.

else:
print(“b is greater than a”)

else block gets executed if none of the above mentioned conditions are true.

Now, let’s see what kind of mathematical logical conditions is supported by python.

1. Equals:

a == b

returns true if two expressions are equal.

2. Not Equals:

a != b

returns true if two expressions are not equal.

3. Less than:

a < b

returns true if a is less than b.

4. Less than or Equal to:

a <= b

returns true if a is less than or equal to b.

5. Greater than:

a > b

returns true if a is greater than b.

6. Greater than or Equal to:

a >= b

returns true if a is greater than or equal to b.

This site uses Akismet to reduce spam. Learn how your comment data is processed.