Hello friends, just like any other programming language, Python also supports conditions. And the keywords for adding conditions to code are if, elif and else. These conditions can contain single or multiple statements separated by ‘and’ and ‘or’ keywords.
if and else keywords
Just like practical like we have condition in programming as well and Python is no different.
Lets start by looking at the syntax with code example for the if conditions. Please have a look at the below code for the same.
First of all have a look at the syntax of the if-else conditions. Both if and else conditions end with colon(:)
if(condition): statement else: statement
The above method checks if I need a car to go outside. And it depends on a single global variable defined at the file level. If the weather is pleasant I don’t need a car to go outside.
What if my need to take car depends on multiple factors. In that case I need to change my condition to include multiple variables. The variable can be separated by ‘and’ and ‘or’ keywords depending on the situations.
In the above code you can see a new keyword which is equivalent of ‘else-if’ used in other programming languages. The above code logic says if the first condition is not met check the condition in elif block . If none of these are met go to the else block.
The conditions in real world code examples can be even more complicated.
Leave a Reply