In this Python post, we’ll learn what Python if else statement is and how to properly use it in our Python code.
We’ll be explaining it step by step by using multiple practical code examples.
After reading this article, you’ll have a detailed understanding on how to use Python if else statement.
What is Python If Else?
They are used for decision making in Python. For instance, if a certain condition is satisfied, only then run some specific piece of code, else run something else.
We’ll first understand the syntax of if else statement. After that, we’ll implement it practically using Python code examples.
Syntax of If Else Statement
if condition: // run if the condition is true else: // run if the (if condition is false)
In Python if else, we first we have an if keyword, then a condition is checked and is closed by a colon(:). Body of if statement is specified using an indentation.
Then comes the else block having no condition. It also has a colon(:). Same indentation is applied to else block as well.
Implementing Python If Else Statement (Multiple Examples)
See below examples to understand how Python if else works.
Example 1: Simple If Else
val=5; if val<=5: print('It is 5') // this block will run because the condition is satisfied else: print('It is not 5')
In the above code, first we have initialized an integer variable. Then we have applied condition on it.
If the integer is less than or equal to the value which is 5, then run the if block. If not, then run the else block.
You can try using strings as well. See below code:
val='blue'; if val=='green': print('It is green') else: print('It is not green') // it will be printed as the condition will return false
Do try it with other conditions as well.
Example 2: Using If Statement Only
We can use only if as well. See below code:
val='green'; if val=='green': print('It is green') print('It will run anyways')
Output
It is green It will run anyways
You can see that the condition is true but still the next block is printed as well. Reason is that its not in if or else block. Its in the normal code flow. The body of if or else is specified using indentation.
So this is how you can easily use Python if else statement in your code as well.
Do let me know in the comment section if you still have any questions regarding the implementation of Python if else statement. I’d be very happy to answer all.
Conclusion
As conclusion of this post, hope you now have a complete idea of how to use Python if else in your own code. Your feedback would be well appreciated. Thank you for reading this post.