In my earlier post I have shown how we use conditional statements on Python and now just to extend the topic with else if conditions . Now we will see how we can use else if condition in python.
To demonstrate this we will take a very simple condition of if statement and making it false to use else and else if conditions.
Lets say we have one variable called “X” and assign one value called “a” to it . To validate if the value is true or false we will use else and else if conditions.
Here is one simple script to test the else condition :
x='a' if x=='b': print 'X is not a' else: print 'X is a'
The final output of the script if we run it will be as below :
Python 2.7.8 (default, Jun 30 2014, 16:08:48) [MSC v.1500 64 bit (AMD64)] on win32 Type "copyright", "credits" or "license()" for more information. >>> X is a >>>
Now if we look at the script it initially assigned with value “a” and as the condition on else part is true for which it is displaying as the result as “X is a” because the if part is not true.
Now if we want to use multiple condition to check or validate the value of X we can write multiple conditions.
Here is another example where we are trying to use multiple conditions to check what is the actual value if ‘X’ :
x='a' if x=='b': print 'X is not a' elif x=='c': print 'X is not a but c' elif x=='a': print 'X is assigned with value a' else: print 'not assigned with a '
From the above statement we can see that we have used multiple conditions but the condition which is true is a part of else part, in python we use “ELIF” for else if conditions. When we run the script we will see the below result:
Python 2.7.8 (default, Jun 30 2014, 16:08:48) [MSC v.1500 64 bit (AMD64)] on win32 Type "copyright", "credits" or "license()" for more information. >>> X is assigned with value a >>>
In similar way we can use “elif” conditions in python.
Thank you for reading my blog . Please feel free to leave me some feedback or to suggest any future topics.