Python 3x Pandas Django

For Loops


"for loops" are called iterators

Just like while loop, "For Loop" is also used to repeat the program

For Loop in range

For Loop iterates with number declared in the range

Note: range() is a in-built python function. We will discuss each python functions in detail in upcoming chapters

for x in range (2,7):
    print (x)

Output

 2
 3
 4
 5
 6

for anything in range (2,7,2):
    print (anything)

Output

  2
  4
  6

For loop in string

For Loop iterates with characters declared in the string

name = 'Michael'
for x in name:
    print(x)

Output:

M
i
c
h
a
e
l

For loop in lists\tuple\set

For Loop iterates with items declared in the lists

months = ['jan','feb','mar','apr','may','jun']
for x in months:
    print(x)

Output:

jan
feb
mar
apr
may
jun

For loop in dict

For Loop iterates with items declared in the lists

months = {1:'Jan',
          2:'Feb',
          3:'Mar',
          4:'Apr',
          5:'May',
          6:'Jun'}
for key, value in months.items():
    print(key, value)

Output:

1 Jan
2 Feb
3 Mar
4 Apr
5 May
6 Jun

Try it yourself

for key in months.keys():
    print(key)

for value in months.values():
    print(value)

for anystring in months.items(): #anystring is in tuple format
    key, value  = anystring
    print(key, value)

For loop in enumerate function

Enumerate function is used for the numbering or indexing the members in the list

Enumerate index starts from 0

Months = ["Jan","Feb","Mar","April","May","June"]
for i, m in enumerate(Months):
		print(i,m)

Output:

0 Jan
1 Feb
2 Mar
3 April
4 May
5 June

for i, m in enumerate("Helloooo"):
		print(i,m)

Output:

  0 H
  1 e
  2 l
  3 l
  4 o
  5 o
  6 o
  7 o

break keyword

It terminates the current loop and resumes execution at the next statement.

In the below example, break statement terminates the loop when an item is a string and it resumes execution outside the for loop.

myLists = [1, 2, 4, 3, 'any', 4, 5, 6]
for eachitem in myLists:
    if type(eachitem) == str:
        break
    print(eachitem)
print("for loop completed")

Output:

1
2
4
3
for loop completed

continue keyword

It is used to end the current iteration in a while\for loop, and continues to the next iteration.

myLists = [1, 2, 4, 3, 'any', 4, 5, 6]
for eachitem in myLists:
    if type(eachitem) == str:
        continue
    print(eachitem)
print("for loop completed")

In the above example, continue keyword used to end the loop when an item is a string in the given list and continues with the remaining loops.

If you have any doubts or queries related to this chapter, get them clarified from our Python Team experts on ibmmainframer Community!