Python if-else

2 min 15 sec read Basic

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 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 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. Following example will illustrate how to use 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.

How was the tutorial? Nice. Right?

Deep Concept videos to crack the highly-piad interviews.

Chekout out our Youtube Channel to get detailed video content on important topics in interviews.

What is your Interview Score?

Test your skillset with the curated questions created by experts around the globe.

Book a free test slot. Now !.

It usually takes 30 mins for an online test and this test will be MCQ based. Get detailed analytics based on your test and recommedations with personalised roadmaps.

Book a test slot. Now!

Have questions about the trial coding class?

Chat with our experts to discuss

Connect on WhatsApp

Recommended tutorials

#online compiler for c     #python for programming    

#dfs and bfs algorithm     #programming with c language

#storageclass in C    #listcomprehension in python