Control Flow In Python: If, For and While

Control flow is required in any programming language, cause you required to write statements based on conditions. If condition is true then execute some statements else execute another statements.
Python programming language provides decision making statements to control flow.

If Statement

Syntax:

if condition:
   statement(s)

#if else condition
if condition:
   statement(s)
else:
   statement(s)


#multiple else if
if condition1:
   statement(s)
elif condition2:
   statement(s)
.
.
.
else:
   statement(s)

Looping

Instead of sequential execution, there may be situations when you need to execute same or same groups of statements multiple times, looping provide us to execute statement(s) multiple times.

For

For statement in python is differ than traditional programming languages like C, instead of arithmetic operation and condition, user can access for to iterate.
The for statement is used to iterate over the elements of a sequence (such as a string, tuple or list) or other iterable object:
Syntax:


for value in condition:
    statement(s)

else:
   statement(s)

While

The while statement is used for repeated execution as long as an expression is true
Syntax:

while condition:
    statement(s)
else:
    statement(s)

Else is an optional part for both.

Official documentation of python control flow is here.

Leave a Reply

Your email address will not be published. Required fields are marked *