Control Flow

If Statement in Python

The if else block controls decision making by checking true/false statements resulting in different executions of code, depending on if the result is true and if the result is false.

There are three parts to the if-else block: if, elif, and else.


Syntax
if boolean_expression1:
   #code to execute if boolean_expression1 is true
elif boolean_expression2:
   #code to execute if boolean_expression1 is false, and booleanExpression2 is true
else:
   #code to execute if none of above expressions are true
     

Notes

boolean_expression(s) are those that result in either a true or false output.

There can also be multiple Boolean expressions within the parentheses (boolean_expression). The Boolean expressions are connected through logical operators.

Elif statements allow for another Boolean expression check within the overall if structure. This is optional.

Else statements result in the execution of code if the if statement (and if applicable, the subsequent else if statement(s)) do not hold true. This is also optional.

Nested if (else) statements are also possible and are the inclusion of another (or multiple) if statements within an if statement block.


Example
if counter > 30:
    print ('Counter is greater than 30')
elif (counter > 20 and counter <= 30):
    print ('Counter is between 20 and 30')
    counter++
else:
    print ('Counter is below 20')
    counter++

< Sets   |   For Loop >

© 2019 SyntaxDB. All Rights Reserved.