position: fixed; top: auto !important; margin-left: 112px;

Python if else

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.


Previous Next Article







codzify.com


Largest collection of up-to-date tutorials to learn programming languages. We are focused on easy learning. Massive collection of interview questions one may need for preparation.

Social Profile


Linkedin
Twitter
Facebook

Copyright 2018. All rights reserved.