Overview

For loops can be used to iterate through a list or to go through a range of numbers. This can be very useful if you want to get each single element of a list or dictionary or even a string. In some cases, a for loop and a while loop can both be used.

Looping through a string with for loops

for letter in "teststring":
    print(letter)
t
e
s
t
s
t
r
i
n
g
%%js
for (let letter of "teststring") {
    console.log(letter);
}
<IPython.core.display.Javascript object>

t
e
s
t
s
t
r
i
n
g

Code breakdown

  • First, we create the for loop
  • Then, we create a temporary variable. In this case, ‘letter’
  • Finally, we create a string to iterate through, ‘teststring’
  • Then, inside the for loop, we print/console.log the variable ‘letter’ for each iteration

Popcorn Hack #3

I want you to create a for loop that iterates and prints out to the terminal the letters of your name

Example

name = "weston"

for letter in name:
    print(letter)
w
e
s
t
o
n

–>