In python there are two types of statement IF or ELSE. It can be explained by the example “A father told his son to go to his room and search for his glasses, if he finds his glasses than bring those glasses to him otherwise go to mom and asked her about the glasses”. Same is the property of if else in python the basic syntax of if else statement is following:
The above defined syntax is compulsory for if else statement. There must be 4 tabs indentation after the condition and there must be colon after if and else.
Some of the example codes are following which make it clearer.
In the above case string is actually equal to pooh so if condition will be printed
In case 2 string is not matched so else statement will be printed.
Finding word in string:
suppose we have a long string and we want to know that particular word is present in a string or not for that we can use if statements. If that word is present in that string than it will say I found else not found.
The in keyword search that particular argument in a string or maybe in a list.
We can negate by using not keyword before in keyword as following:
Statements with bool opeartors:
We can also verify the conditions by using bool operator in a condition section. Following is the example which clarify the concept:
We can use multiple if statements by using elif keyword for this:
Following is the example of using elif keyword:
As we see the condition of elif statement is true so the output will be “Elif statement run”.
We can represent the flow diagram of if else statement as following:
As we can see the code starts it enter into the condition where it have to make decision. If condition is true than “if” block is executed otherwise “else” code will be executed.