Khalsa Labs
range_python

How Python For Loop Works

How python loop works with use of range function. Lets introduce with some features of Iteration in python. Working of for condition in python is explained here:

Python uses for in statement for looping/Iterating. It also use while statement but here we are going to put a brief look on for statement’s working.

Basic Syntax for Iterate 5 times ,e.g 0-4..

Python is equal to C++
for i in range(0,5):
print i
===   for(i=0;i<5;i++)
{
cout<<i<<endl;
}

 

output:

0
1
2
3
4

 

HOW IT WORKS :
for i in range(0,5):
print i

Explained:

for _ in traverse the sequence given in expression. But whats it!! we don’t gave sequence here in above example , we wrote range(0,5)

range() : Its a function which takes integer arguments t create a sequence. e.g

range(5)  =  [0,1,2,3,4]      (generate sequence from 0 to 5)

range(1,5) = [1,2,3,4]        – from 1 to 5

range(0,6,2) = [0,2,4]      – from 0 to 6 with difference of 2

That is how we generate sequence in python , with different parameters.

What if we write direct sequence instead of range() function in For loop ??

for a in [0,1,2,3,4,5,6]:
  print a

Above code is fine and executed 7 times , from 0 to 6.

 

Some Crazy For Loops In Python

for i in range(10,0, -1):

print i

 

count = 0

for i in range “khalsalabs”:

count += 1

 

Try Yourself for Better Understanding

The following two tabs change content below.
Python Developer and DIY lover.

want to comment ??

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