Test your Programming knowledge

50% users failed to get the best score. It's your turn to test now.
Questions curated by the expert mentors at codzify.com

Start Quiz


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 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.

Recommended Articles

Did you found this article helpful?

Try to execute what you have learnt

Easy to use online data structure compiler where you can execute the programs in your favourite programming language.
(C, C++, Python)

Open Compiler

HTML, CSS and Javascript Real time Web Editor

Execute your HTML, CSS and javascript code in real time with the web editor
(HTML, CSS, Bootstrap, Javascript)

Open Web Editor