For Loop
A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string). |
For Loop - String
For i in "Color": print(i) >>> C >>> o >>> l >>> o >>> r
|
For Loop - Dictionary
Car = { "brand": "Ford", "model": "Focus", "year": 2013 } for i in Car: print(i) >>> brand >>> model >>> year
|
In this example we only print the keys of the dictionary, in the next example we will print the value of each key. |
for i in Car: print(Car[i]) >>> Ford >>> Focus >>> 2013
|
|
|
For Loop - Tuple
RYB_color = ("Red","Yellow","Blue") for i in RYB_color: print(i) >>> Red >>> Yellow >>> Blue
|
For Loop - List
RYB_color = ["Red","Yellow","Blue"] for i in RYB_color: print(i) >>> Red >>> Yellow >>> Blue
|
The break Statement
for i in RYB_color: if(i == "Yellow"): break print(i) >>> Red
|
With the break
statement we can stop the loop before it has looped through all the items. In this example the loop stopped when the item is equal to "Yellow" |
The continue Statement
for i in RYB_color: if(i == "Yellow"): continue print(i) >>> Red >>> Blue
|
With the continue
statement we can stop the current iteration of the loop, and continue with the next. |
|
|
The range() Function
for i in range(3): print(i) >>> 0 >>> 1 >>> 2
|
The range(n)
is a function that returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at (n -1)
. |
for i in range(2,5): print(i) >>> 2 >>> 3 >>> 4
|
In this example range(j,n)
returns a sequence of numbers, starting from j
and incremented by 1 (by default), and ends at (n - 1)
. |
for i in range(2,10,3): print(i) >>> 2 >>> 5 >>> 8
|
In this example range(j,n,k)
returns a sequence of numbers, starting from j
and incremented by k
and ends at (n - 1)
. |
|
|
Else in For Loop
for i in range(3): print(i) else: print("finally finished !") >>> 0 >>> 1 >>> 2 >>> finally finished !
|
Nested Loops
list_1 = ["Data" , "Machine learning"] list_2 = ["Scientist","Engineer"] for i in list_1: for j in list_2: print(i,j) >>> Data Scientist >>> Data Engineer >>> Machine Learning Scientist >>> Machine Learning Engineer
|
The pass Statement
for i in RYB_color: pass
|
for loops cannot be empty, but if we for some reason have a for loop with no content, we can put in the pass statement to avoid getting an error. |
|