Loops and Strings
In this lesson, we will look at iterating over text using loops in Python. As we mentioned in the lesson on arrays, text in Python is an array of characters, which means we can iterate through each character in the text using a for
or while
loop.
Example: We want to iterate over each character in the word 'Python' and print it:
word = 'Python'
for character in word:
print(character)
# This will print:
# P
# y
# t
# h
# o
# n
In this example, we go through each character in the string word
and print it. The for
loop iterates through each character in the string.
We could also use a while
loop to achieve the same result, but you will agree that the for
loop is much simpler:
word = 'Python'
index = 0
while index < len(word):
print(word[index])
index = index + 1
In this example, we use the variable index
to iterate through each character in the string word
and print it. The while
loop continues as long as the variable index
is less than the length of the string word
.
Instructions
Choose a loop to iterate through the variable text
and print each character on a new line.
Start programming for free
6/8