Python IF ELSE & Nested IF-ELSE Control Flow Statements

Python IF ELSE and Nested IF ELSE control flow statements

In this article we are going through Python IF ELSE control flow statements. It is almost same as other programming language such as C, C++ or java etc.

The program default executes sequentially but sometimes you have to take control on program execution to get the desired output. To control the program execution, we have special utilities or statements called as “Control flow statements” 

Control
Flow IF-ELSE Statements:

               1. IF-ELSE

               2. Nested IF-ELSE

1. Python IF ELSE

IF-ELSE statement used to evaluate the condition and executes the block of statements based on results which is either YES (true) or NO (false)

General Syntax:

If (Condition)

Statement(s)

Else

Statement(s)

Syntax in Python: 

It is bit different syntax in python to write IF-ELSE conditional control flow statements. A blank spaces (indentation) is very important factor while writing code in python, especially if-else or nested if-else multiple conditional blocks. One extra blank space can kill your program!

if:

            <statement(s)>

else:

            <statement(s)>

Note: Please make a note, if-else statements are in lower case characters. In case if you write it in upper case, then you will get syntax error which is most common mistake people are doing. Python is very case sensitive language! 

Example:

Python IF ELSE Statement code

Output:

Python IF ELSE Statement code output

2. Nested IF ELSE

Simple IF-ELSE works fine but if you have multiple conditions and each one of them depends on another condition then Nested If-ELSE is very useful and effective.

It gives you flexibility to write multiple conditions and control your set of commands. It also helps to minimize the execution time as if one condition is true then it will skip further conditions and saves the time.

Syntax:

if :

            <statement(s)>

elif :

            <statement(s)>

elif :

            <statement(s)>

else:

            <statement(s)>

Be careful with if-elif-else statements, they must appear as-is in lower case and ELSE IF should be elif only. In case if you write any character in uppercase or elseif instead of elif, then you will defintely gets syntax error. Python is very case sensitive language and doesn’t allow any syntax violation.

Example:

Python Nested IF ELSE Statement code
Python Nested IF ELSE Statement output

Read More: Python For Loop and While Loop

Leave a Comment