Level III
Play with loops inside loops
As previously mentioned, it is important that you read in your mind what you’re typing. Let’s read together the following example of a loop inside another loop (nested).
What are the initials of our project?
#First iteration of loop 1
- Line 1: We declare our variable project with a list containing 4 strings.
- Line 2: “For each word inside the list called project”. Now word = “Code”.
#First iteration of loop 2
- Line 3: and “for each letter in “Code”[0]. This means this second loop won’t iterate through the other letters “ode”, as I specified to focus only on the first element [0] of “Code”. Now letter = “C”. It goes to line 4.
- Line 4: print “C”. It goes to line 2.
#Second iteration of loop 1
- Line 2: Now word = “For”.
#Second iteration of loop 2
- Line3: for each letter in “For”[0]. Now letter = “F”.
- print “F”.
and so on.
What would happen if instead of printing initials, we want to print the first two letters?
Play with other examples by adding a second loop as you like. We recommend you to read it out loud, or even drawing in a paper:
Example 1
Example 2
Example 3
Example 4
Previous level
Play with loops
Next lesson
Play with dictionaries