Show Menu
Cheatography

Python For Loops Cheat Sheet (DRAFT) by

This is a draft cheat sheet. It is a work in progress and is not finished yet.

For Loop

A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictio­nary, a set, or a string).

For Loop - String

For i in "­Col­or": 
 ­ ­ ­  print(i)
>>> C
>>> o
>>> l
>>> o
>>> r

For Loop - Dictionary

Car =	{  
      "­bra­nd": "­For­d",
      "­mod­el": "­Foc­us",
      "­yea­r": 2013
}
for i in Car:
 ­ ­ ­ ­  print(i)
>>> brand
>>> model
>>> year
In this example we only print the keys of the dictio­nary, 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 = ("Re­d","Y­ell­ow",­"­Blu­e") 
for i in RYB_color:
 ­ ­ ­  print(i)
>>> Red
>>> Yellow
>>> Blue

For Loop - List

RYB_color = ["Re­d","Y­ell­ow",­"­Blu­e"] 
for i in RYB_color:
 ­ ­ ­  print(i)
>>> Red
>>> Yellow
>>> Blue

The break Statement

for i in RYB_color: 
 ­ ­ ­  if(i == "­Yel­low­"):
 ­ ­ ­ ­ ­ ­ ­  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 "­Yel­low­"

The continue Statement

for i in RYB_color: 
 ­ ­ ­  if(i == "­Yel­low­"):
 ­ ­ ­ ­ ­ ­ ­  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 increm­ented by 1 (by default), and ends at
(n - 1)
.
for i in range(­2,1­0,3): 
 ­ ­ ­ ­  print(i)
>>> 2
>>> 5
>>> 8
In this example
range(­j,n,k)
returns a sequence of numbers, starting from
j
and increm­ented 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 = ["Da­ta" , "­Machine learni­ng"] 
list_2 = ["Sc­ien­tis­t","E­ngi­nee­r"]

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.