- What is Python Elif Statement?
- Syntax of Elif Statement
- Implementing Python Elif Statement (Multiple Examples)
- Example 1: Single Python Elif Statement
- Example 2: Multiple Python Elif Statement
What is Python Elif Statement?
It is a condition statement For instance, if we have an integer of value 10 and we want to check it with multiple conditions like, if its less than 15 then run some code. If its greater than 5 then run a specific code.
So by using Python elif, we can easily check multiple conditions and run our code according to them.
Let’s now implement it using proper Python practical examples. But first, let’s discuss its syntax.
Syntax of Elif Statement
if condition: // run if this condition is true elif condition: // run if this condition is true else: // run if the conditions of the above statements are not satisfied
You can see that first the if statement will be executed. If the condition is not satisfied then it will come to the elif block which can also be called else if. Its the same as the if block, keyword is the only difference among them.
You can use multiple elif statements if you want. And finally, an else block will be executed if none of the above conditions are satisfied.
Click here if you want to learn simple Python if else in detail.
Implementing Python Elif Statement (Multiple Examples)
See below examples to practically understand how to use Python elif.
Example 1: Single Python Elif Statement
val='blue'; if val=='green': // the condition will be checked but its false so its body will not be executed print('It is green') elif val=='blue': // it will check again and the condition is satisfied so its body will be executed print('It is blue') // It is blue else: print('Not found')
We have checked the string using just one Python elif statement. Let’s now use multiple elif statements.
Example 2: Multiple Python Elif Statement
val='red'; if val=='white': // condition not satisfied print('It is white') elif val=='blue': // condition not satisfied print('It is blue') elif val=='purple': // condition not satisfied print('It is purple') elif val=='red': // condition is satisfied which means its body will be executed print('It is red') else: print('Not found')
It is red
You can see that we have used multiple elif statements and the last one satisfies the condition.
So this is how you can easily implement Python elif statement in your code.
I would love to answer if you still have any questions related to the implementation of Python elif.
To conclude, hope you now have a complete in-depth practical understanding of how to use Python elif statement. I would love to hear your thoughts on this post. Thank you for reading it.