Conditional Statements

Conditional statements are often used to control the flow of the program as we desire. 

If Statement

It’s represented in the following syntax:

if expression:
    statement


The statement block will only be executed if the expression is evaluated to be true. 

Example:

frst = 2
scnd = 2
if frst == scnd:
    frst += 1
print(frst)

 

Output: 3


The program above will only increment a by one if frst and scnd have the same value.

 

If-Else Statement

It’s represented in the following syntax:


if expression:
    statement1
else:
    statement2

The statement1 block will only be executed if the expression is evaluated to true, if not then it will execute the statement2.

Example:

frst = 2
scnd = 1
if frst == scnd:
    frst += 1
else:
    frst -= 1
print(frst)

 

Output: 1


The program above would increment frst by one if frst and scnd had the same value, but since they don’t it will instead execute the else block and decrement a by 1.

 

If-Elif Statements

Elif is short for else if and unlike else that is tested if all other conditions fail, elif will be tested as an else but gives us the chance to specify what is the condition we want.

Here is an example:


frst = 3
scnd = 2
if frst == scnd:
   frst += 1
elif frst == 3:
   print("Elif statement ..")
    frst += 1
print(frst)

 

Output: Elif statement .. , 4


In this case, first condition not satisfied it moves to second condition elif and it meets

 

Nested Statements

Python also has the capability of nesting conditional statements inside one another. Following the syntax:

if expression1:
    if expression2:
        statement1
    else:
            statement2
        . . .
else:
    if expression3:
        statement3
. . .


This can go on and on as you desire the code to work.

Example:

frst = 2
scnd = 2
thrd = 1
if frst == scnd:
    if scnd == (thrd + 1):
        frst -= 1
    else:
        frst += 1
else:
    if frst == thrd:
        frst = thrd + scnd
print(frst)

 

Output: 1


In the portion of the code above, the first if statement will evaluate to true because frst indeed equals scnd and therefore it will execute that block. Inside that, if there is another one that evaluates if scnd is equal to thrd + 1 it evaluates to true to executing a -= 1.


 

Related Tutorials