Python for loop

In this article you will learn about python for loop which is control flow statement used to iterate over a sequence of element repeatedly.

What is for loop in Python?

The for loop in python is used for traversal over the object like list, tuple, strings. Traversal over the sequence is know as iteration.

Syntax: Python for loop

for value in sequence:
   body of for

Here value is used as variables that takes the value in each iteration.

Loop will continue we reach the end in sequence. The body of for loop is separate by rest of code using indentation.

Examples: Python for loop

number=[5,3,9,2,4]
sum=0
for value in number:
   sum=sum+value
print("The sum is", sum)

When you run the program, the output will be

The sum is 23

range() function

The range() function in python is used for creating a sequence of number. If we want to create a number from 0 to 9 that is 10 numbers than we will use range() function with parameter 10 as range(10).

We can also define start, stop and step size of range function as

range(Start, Stop, Step_size)

If we not provide step size than python range function take it default as 1.

The range() function does not store all the value in memory just it remember start, stop and step size and using this generate the next number, due to this memory is saved.

To force range function to print all value we use list function.

see the following examples.

print(range(10))
print(list(range(10)))
print(list(range(2,8)))
print(list(range(2,20,3)))

Output

range(0, 10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[2, 3, 4, 5, 6, 7]
[2, 5, 8, 11, 14, 17]

We are using range() function with for loop for iteration in sequence of numbers. It uses len() function to iterate through sequence using indexing.

fruits=["mango", "apple", "grapes"]
for i in range(len(fruits)):
   print("I like ", fruits(i))

For loop with else

A for loop can also use else block as optional block. It executes when the for block complete it’s execution.

We can used break keyword to stop for loop. In such case else part is ignored.

Following example will explain this

digits=[5, 4, 2]
for i in digits:
   print(i)
else:
   print("no item left") 

Output:

5
4
2
no item left

In the above code the for loop print item of list until the loop exhaust, When for loop complete it’s execution the block of else cod is executed and print no of item left.

We can also use for.. else statement with break keyword.

Example:

student_name= "monu"
marks={'rahul':60, 'monu':65}
for student in marks:
   if student==student_name:
      print(marks[student])
      break
else:
   print("no entry with that name found")

This Post Has 2 Comments

  1. Robert

    Nice tutorial

  2. Robert

    Nice way of explained.

Leave a Reply