# Introduction to Loops

Often there is a need to execute a certain block of code again and again for certain number of times. For example a class has 30 students and you want to calculate the percentage of marks for every child and then print the result. In this case you may first define the method for calculating and printing the percentage and then repeat the procedure for every child. This can be achieved with the help of loops

In this tutorial you will learn about three types of loops:
1. while loop
2. for loop
3. nested loops

## for loops

The syntax for ‘for ’ loop is:

```for item in sequence:
repeat these steps
```

Let’s have a look at an example to understand loops:

```var1 = ['a','b','c','d','e','f']
var2 = ['apple','ball','cat','dog','elephant','fan']
index_num = 0;
for item in var1:
print(item  +  ' for ' + var2[index_num])
index_num = index_num + 1
```

## While Loop

The function of the while loop depends on a condition. As long as a condition is true the while loop will work but once the condition changes to false state the loop will stop working. The syntax for while loop in Python is given below:

```while (condition_is_true):
execute_these_statements
```

example

```var1 = ['a','b','c','d','e','f']
var2 = ['apple','ball','cat','dog','elephant','fan']
index_num = 0;
while(index_num < 6):
print(var1[index_num] + ' for ' + var2[index_num])
index_num = index_num + 1
```

In the code given above, you see a variable index_num which is defined as 0 initially. The job of this variable is to work as a counter. Both var1 and var2 have six elements, the index of first element is 0 and the index of the last element is 5. So, we want the loop to stop working after we have dealt with the last element. The value of index_num is increased by 1 after a statement is printed for the element under consideration, so that we can move on to the element.

## Nested Loops

Can we embed a ‘for’ loop inside another for loop or for that matter can we have a loop inside a loop? The answer is ‘yes’. The following code has a for loop inside another for loop. Look at the code given below. You have now studied about if statement and also about for loops. Can you imagine what would be the outcome if the ‘if ’ statement is removed from the code. It is an interesting exercise and I would like to encourage you to play with the code given below to understand how it works.

```var1 = ['a','b','c','d','e','f']
var2 = ['apple','ball','cat','dog','elephant','fan']
var3 = ['fruit','toy','animal','animal','animal','house hold item']
index_num = 0
for item in var1:
for element in var2:
if(var1.index(item)== var2.index(element)):
print(item + ' for '+ element + ' which is a '+ var3[index_num])
index_num = index_num + 1
```
<<< Conditions in PythonFunctions in Python >>>
Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .