Python lesson 6
For Loops
Loop through every letter or item. Let Python do the stepping!
Loop Through a String
You can use a for loop to visit every character in a string, one at a time. Python steps through each letter automatically. You just write what to do with each one!
for char in "hello":
print(char) → h e l l o (one per line)
for char in "hello":
print(char)
One Letter At A Time
for letter in "cat":
print(letter)
Loop Through Letters
Click Run to see Python print each letter in "Python" one at a time!
Hint: Click Run! The loop visits every letter in the word "Python" one at a time.
for char in "Python":
print(char)
Loop Through Your Name
Change "Alex" to YOUR name and run. See each letter printed on its own line!
Hint: Change "Alex" to your own name, then click Run to see your letters one by one!
name = "Alex"
for char in name:
print(char)
Loop with If
You have used in to walk through things: for char in word. It has a second job. Between two things, char in "aeiouAEIOU" asks a question: is this character one of those? Run this to see only the vowels in a word, then try changing "Python" to another word.
Hint: The if asks whether the character is inside the string of vowels. That is what in means here, which is a different job from the in that walks through a word. Change "Python" to another word.
word = "Python"
for char in word:
if char in "aeiouAEIOU":
print(char, "is a vowel")
What you can do on CodeIt
Run the example, change one part, and use the result to check your understanding before moving to the next lesson.