Python Loops

Generally, the code executes in order, first line, second line, and so on. However, sometimes we might need to execute a block of code multiple times. This problem is solved by loops. Loops help us to execute a block of code multiple times or traverse through a sequence item. There are two types of loops in python

  1. For loop
  2. While loop 

Syntax For loop:

for item in sequence:
    body_of_for

syntax While loop:

while test_expression:
    body_of_while

Here for loop is generally used to traverse through a sequence and while loop is used to executed a block of code (inside body of while), when a TestExpression   is True. 

For- loop statement:

 Forloop is used to traverse( move through item) through sequence element like list, tuple, dictionary, range, etc. 

Syntax of for loop:

for item in sequence:
    body_of_for

Let take an example of traversing through a list of items.

fruit_basket = ['mango', 'apple', 'orange', 'grape']

for item in fruit_basket:
    print(item)

Output:

mango
apple
orange
grape

While-loop statement

The while loop tests an expression if it evaluates to True it runs the body of while loop. It tests again and it True runs again and so on until the test expression becomes False.

Syntax for while loop:

while test_expression:
    body_of_while

Example:

x = 0
while x <= 5:
    print(x)

    x += 1

Output:

0
1
2
3
4
5

For loop with enumerate() function

Sometime we want to loop through a sequence of items but want to also know which index we are in. In languages like c, for loops use to be like this:

for(int i=0 ; i <= n; i++){
 body_of_for_loop
} 

here for loop use to move based on index. 

However, in python we loop through sequence of items without being aware of the index value. If we ever want to loop through item and also know index value we need to use enumerate() function.

enumerate() function- it helps to loop through item and combines the individual item with an index value. This function returns a tuple value with first item as index and second item as the element of sequence.

syntax of enumerate() function:

enumerate(iterable [, start=starting_index_number])

Lets see an example of the same for loop with fruits this time with index.

Example:

fruit_basket = ['mango', 'apple', 'orange', 'grape']
for index, item in enumerate(fruit_basket):
    print(index, item)

Output:

0 mango
1 apple
2 orange
3 grape

 enumerate() function by default starts from 0. If we want to start enumerate() from index value other than 0 (zero), then we need to pass starts parameter, for example: Example2 – enumerate with different start index: 

fruit_basket = ['mango', 'apple', 'orange', 'grape']
for index, item in enumerate(fruit_basket, start=10):
    print(index, item)

Output:

10 mango
11 apple
12 orange
13 grape

Leave a Reply

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