Conditional statements & Control Loops

Conditional Statements

Its a set of rules performed if a certain condition is met. Its used to direct the program so that if a certain condition is valid only then the program works, else it checks if there’s another set of conditions to meet if it still doesn’t meet those conditions then the code exits. There are : if,else, elif condition statements in python now lets see what these are

If

If is a conditional statement which checks if the given data matches the certain conditions set by if. If the conditions satisfy then a certain set of codes gets executed. If they don’t match then it will just exit the code.
Syntax:
if(condition):
Statements
(Ps: indentations matter)

Flow Chart:

Example:

Else

An else statement contains the block of code that executes if the conditional expression in the if statement has a false value. Usually if and else are used together.
Syntax:
if (condition):
Statements
else:
Statements

Flow chart:

Example:

Elif

The elif statement are used to check for multiple expressions for TRUE value and execute a block of code as soon as one of the conditions is TRUE.
Syntax:
if(condition):
statements
elif(condition):
statements
elif(condition):
statements
else:
statements

Flow chart:

Example

Loops

Sometimes we want some part of our code to be executed more than once. A loop statement allows us to execute a statement or group of statements multiple times.

While loop:

Repeats a statement or group of statements while a given condition is TRUE. It tests the condition before executing the loop body.
Syntax:
while(condition):
statements

Flow Chart:

Example:

For loop:

Executes a sequence of statements multiple times and abbreviates the code that manages the loop variable.
Syntax:
for ( iterating_variable in sequence):
statements

Flow chart:

Loop Control Statements

Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed.
Types are:Break,Continue,Pass

Break:

Terminates the loop statement and transfers execution to the statement immediately following the loop.

Python break statement
Continue:

Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.

Python continue statement

Pass:

The pass statement in Python is used when a statement is required syntactically but you do not want any command or code to execute.

Author: Nivedita.M
Edited by: Arcot Gautham

Leave a comment