Fall 2024 - P4
Big Idea 3 | .1 | .2 | .3 | .4 | .5 | .6 | .7 | .8 | .10 |
3.8.3 for loops
Basic concept for for loops
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
–>