For Loops

There are two types of loops in Python, for and while.

For Loop

For loops iterate over a given sequence. That sequence could be List or Dictionary or Range. 

Exercise 1:

Output

In the above example, we defined 2 Lists and then printed them using for loop.

Line 4, We called for loop, this loop will iterate for every element in hairs list. Which will be printed using line 5.

Line 7, We called for loop, we defined 'i' as a variable for every element in the eyes list. You can define what you want to do with an element using indent formate.

For loops can iterate over a sequence of numbers using the "range" and "xrange" functions. The difference between range and xrange is that the range function returns a new list with numbers of that specified range, whereas xrange returns an iterator, which is more efficient. (Python 3 uses the range function, which acts like xrange). Note that the range function is zero-based.

Exercise 2:

Output:

Line 1, a total of 5 elements were picked, as range is zero-based so element in list were [0,1,2,3,4]

Line 6, Range between 2 to 8 was picked. Python includes the first parameter and ignores the last parameter so elements in the list were [2,3,4,5,6,7]

Line 11, we used range between 1 to 15 with a difference of 3. So, elements in the list were [1,4,7,10,13]

About the author

akarperiwal

0 Comments

Please login to comment