# Control Flow With Decisions And Loops In Python

## Compound Statement (Conditional or Loop Statement)

A compound statement is defined as a group of statements that affect or control the execution of other statements in some way. Python programming language provides different ways to construct or write compound statements. These are mainly defined as:

## if Statement

This statement is used for conditional execution. The syntax of the statement is as follows,
1. if expression: suite
2. elif expression: suite
3. else: suite
if statement evaluates the expressions (condition) one by one until one is found to be true then executes the following suite (a group of statements) for example
1. a, b = 1020
2. if a > b:
3.     print("a is greater than b")
4. elif a < b:
5.     print("b is greater than a")
6. else:
7.     print("Both a and b are equal"

Python programming language allows us to use one if statement inside other if statement, for example:
1. a, b = 1020
2.
3. if a != b:
4.     if a > b:
5.         print("a is greater than b")
6.     else:
7.         print("b is greater than a")
8. else:
9.     print("Both a and b are equal")

## while Statement

while statement is used to execute a block of statements repeatedly until a given condition is fulfilled. Syntax of the statement is as follows
1. while expression:
2.     statement(s)
As we know that Python uses indentation as its method of grouping statements, statements after while expression: must be indented by the same number of character spaces otherwise they will not be considered as part of a single block of code. While statement executes repeatedly until a given condition is fulfilled and executes the statement immediately after the loop when the condition becomes false for example,
1. i = 1
2. while i < 6:
3.   print('inside while loop - printing value of i -', i)
4.   i += 1
5.   print('after while loop finished')

Else statement can also be used to execute a statement when the while condition becomes false
1. i = 1
2. while i < 6:
3.   print('inside while loop - printing value of i -', i);
4. i += 1
5. else :
6.   print('after while loop finished')

Please note that it is not recommended to use a while loop for iterators as mentioned in the above example instead of using for-in (or for each) loop method in Python.

## for statement

for statement is used to traverse a list or string or array in a sequential manner for example
1. print("List Iteration")
2. l = ["python""for""programmers"]
3. for i in l:
4.    print(i)

There are few in-built Python functions available that take input as list or string or array etc. and iterate through elements of list or string or array and return index, data or both.

## Range() method

Which returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number. Please refer to the example for more detail
1. print("List Iteration")
2. l = ["python""for""programmers"]
3. for i in range(len(l)):
4.     print(l[i])

We can use for-in loop inside another for-in loop. we can even use any type of control statement condition inside of any other type of loop. Please refer to the example for more detail
1. print("List Iteration")
2. carMake = ["Maruti""Fiat""Honda"]
3. carModel = {'Maruti':'Alto''Fiat':'Punto''Honda':'Jazz'}
4. for i in range(len(carMake)):
5.     for x in carModel:
6.         if(x==carMake[i]):
7.             print("%s  %s" %(x, carModel[x]))

## Enumerate

Another built-in Python function that takes input as iterator, list etc. and returns a tuple containing index and data at that index in the iterator sequence. For example, enumerate (carMake), returns a iterator that will return (0, carMake[0]), (1, carMake[1]), (2, carMake[2]), and so on.
1. print("List Iteration")
2. carMake = ["Maruti""Fiat""Honda"]
3. for i, x in enumerate(carMake):  print("%s  %s" %(i, x))

## zip

Another in-built python function which is helpful to combine similar types of  iterators (list-list or dictionary- dictionary etc.) data items at ith position. It uses the shortest length of these input iterators. Other items of larger length iterators are skipped.
1. carMake = ["Maruti""Fiat""Honda"]
2. carModel = ['Alto''Punto''Jazz']
3. for m,mo in zip(carMake, carModel):
4.    print("car %s is a product of %s" %(mo, m))

## try statement

The try statement specifies exception handlers and/or cleanup code for a group of statements.

except clause or statement is a place that contains code to handle the exception or error raised in try block and multiple except clauses while a single try statement clause can be added into the code. In the below example, print command will raise a ‘TypeError’ because %d is expecting integer value
1. print("List Iteration")
2. carMake = ["Maruti""Fiat""Honda"]
3. carModel = {'Maruti':'Alto''Fiat':'Punto''Honda':'Jazz'}
4. try:
5.     for i in range(len(carMake)):
6.         for x in carModel:
7.             if(x==carMake[i]):
8.                 print("%s  %d" %(x, carModel[x]))
9. except TypeError:
10.     print('oops! Type error -- ', t)
• You can include try-except statements within other try-except statements
• finally: clause can be added to clean up the resources or objects
• finally: block is a place to put any code that must execute, whether the try-block raised an exception or not
Please refer to the example for better understanding or implementation
1. print("List Iteration")
2. carMake = ["Maruti""Fiat""Honda"]
3. carModel = {'Maruti':'Alto''Fiat':'Punto''Honda':'Jazz'}
4. try:
5.     for i in range(len(carMake)):
6.         for x in carModel:
7.             if(x==carMake[i]):
8.                 print("%s  %d" %(x, carModel[x]))
9. except TypeError as t:
10.     print('oops! Type error -- ', t)
11. except ValueError:
12.     print('oops! incorrect value')
13. finally:
14.  print('Finally Code Execution - done');

## with statement

The with statement is used to wrap the execution of a block with methods defined by a context manager where a context manager is an object that defines the runtime context to be established. In the below example, accessing a file by using the open() function returns a file object that is being used for further execution.
1. with open("c:\welcome.txt") as file: # Use file to refer to the file object
3.     print(data)

## Loop Control Statements

The Loop control statement is meant to be used when you want to change the execution flow from its normal sequence, which means it either terminates the execution in between or transfers control to execute or skip the remaining code block. Python programming language supports the following loop control statements:

## break

This statement terminates the loop statement and transfers execution to the statement immediately following the loop. In the below example it terminates the execution as soon as the first even number present in the list is found and printed
1. List = [153475]
2. print('find and print first even number present in the list %s' %List)
3. for number in List:
4.     if(number % 2 == 0):
5.         print('%d is first even number present in the list' %number)
6.  break;

## Continue

This statement causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating. In the below example it skips the execution the moment an odd number is found and continues iterating next items to find and print all the even numbers present in the list
1. List = [15316924475]
2. evenNumbers = []
3. print('find and print all even number present in the list %s' %List)
4. for number in List:
5.     if(number % 2 != 0):
6.         continue;
7.     else:
8.         evenNumbers.append(number)
9.
10. print('even numbers %s present in the list ' %evenNumbers)

## pass

This statement causes the loop to pass the control to execute any additional code on a specific condition, then proceeds to execute the remainder of its body. In the below example pass is the execution control to double the number when an odd number is found then continue printing the numbers.
1. List = [15316924475]
2. EvenNumbers = []
3. print('double the number when odd number is found in the list %s' %List)
4. for number in List:
5.     x = number
6.     if(x % 2 != 0):
7.         pass
8.         print('odd number %s found- double the number' %x)
9.         x=x+x
10.     else:
11.         print('even number %s found- do nothing' %x)
12.     print(x)

## Conclusion

In this article, we learned about different compound statements including if condition, loop (while, for) statement, and loop control ( continue, break, pass) statement.