In this tutorial, we would learn about conditional statements in Python. We use conditional statements to control the flow of execution of our program. That’s why conditional statements are also known as control flow. Here I would like to explain conditional statements with an example. “Suppose you have a list with 10 integer elements and you want to separate all the elements with the value under 50 in another list in this kind of situation you can use a conditional statement”. We have several conditional statements in Python like if statement, if-else statement, elif statement. We will about all these statements one by one.

If statement in Python:

We use if statement in case we want to run a specific piece of code only if the certain condition would true. To add if statement in our code we have if keyword then we add a condition in parenthesis and then the body of if in curly brackets {}. Here is the syntax of if statement in Python.

if( # condition Here ):
   # body of if statement

For example, a person can only code if his/her age is above 18 years. Check this example.

age=19
if(age>=18):
   print('you are eligible for vote')

If-else statement in Python:

In the last example, we learned about if statement and we learned that if statement only works if a certain condition will true. It means, if statement will not have a control in case condition will false. But in the case of the if-else statement, we can run a piece of code in case condition would true and can run a different piece of code in case condition would false. Here is the syntax of the if-else statement.

if( # condition Here ):
   # piece of code (in case condition would true)
else:
   # piece of code (in case condition would false)

Here to understand the if-else statement in Python we would see a simple example to find if a given number is even or odd.

number=10

if(number%2==0):
   print('number id even')
else:
   print('number id odd')

elif statement in Python:

We use elif(short form of else if) statement. In case we have multiple conditions. for example you want to assign Grades to students according to their marks. It means we have multiple conditions like students who got marks between 100 to 80 will in A Grade and those who got 80 to 60 will in B Grade like this. Let’s follow this example in Python code.

marks=85

if(marks<=100 and marks>80):
   print('Grade A')
elif(marks<=80 and marks>60):
   print('Grade B')
elif(marks<=60 and marks>40):
   print('Grade C')
else:
   print('Fail')