Courses Enquiry

Python if-else

2 min 15 sec read


If you are familiar with programming languages like C, C++ or Java you might have heard about conditional statements. Conditional statements are used to take decisions in a program whether to execute the statement or not based on some target condition. Indentation is must after if block or else block else program will throw an error.

if statement

Python If statement is used to apply conditions. The following example will illustrate how to use an if statement in python

x = 5 if x==5:
print(x) 

Find the error in this program

Try to execute this program, you will see an indentation error as space after if the block is not given.

x = 5
if x==5:
 print(x) 

if else statement

Python If else statement is used to execute either of two conditions. The following example will illustrate how to use the if else statement in python

x = 10
y = 3
if x==5:
 print(x)
else:
 print(y) 

In the given python program, check whether the value of x is 5 or not, and since x does not equals to 5 else condition will be executed. So the output will be 3

elif statement

"elif python statement" philosophy is like if the first condition is wrong, check the second condition, if the second condition is wrong, check the third one and so on. Following example will illustrate how to use elif statement in python

x = 10
y = 3
if x==5:
 print(x)
elif x==9:
 print(x)
elif x==7:
 print(x)
else: print(y) 

In this python program, the first value of x is compared with 5 (x == 5) which does not satisfy the condition so next condition using elif statement (x == 9) is being executed which again dissatisfies the condition and moving to third elif block statement condition again is not satisfied so finally else block is executed printing the output 3.

Unlock learning opportunities with our expert-led coding courses.
Real-time doubt solving in a live online coding class is also available in the course
that will help you to stay connected with an experts while learning.

Browse Online Coding Classes Videos