It is the way of programming in which either one or a set of statements are executed based on a condition. Every programming language has its own way of handling decisions. Python provides the following ways for decisional programming:
‘if’ statement allows a block of statements to be executed if the condition is true. If the condition is false, it does nothing.
Syntax:
Example:
‘if – else’ statement allows a block of statements to be executed if the condition is true and another block of statements to be executed if the condition is false.
Syntax:
Example:
The basic ‘if’ statement works in a way that conditions are tested only with the ‘if’ statement and not with the ‘else’ statement hence in order to work with more conditions all along, we use ‘if – elif – else’ statement.
Syntax:
Example:
Apart from general use of ‘if’ statements, there may be a case when an ‘if’ block needs to be packed inside of another ‘if’ or ‘elif’ or ‘else’ statement. In that case what we do is called nesting of if statements. Check the syntax below:
Syntax:
As we know the ‘if’ statement checks a condition whether it’s TRUE or it FALSE. If we see, relational operators also do the same. So, it’s better to store a complete relational expression in a variable and then checking the variable through ‘if’ statement. Consider the example below:
Syntax: