Flow controls: Loops · 3 / 26 Theory

Looping over strings with for

for does not work only with numbers: it can go through any sequence, such as a text string, character by character.

for letter in "Hello":
    print(letter)
# H
# e
# l
# l
# o

Counting and searching

sentence = input()
vowels = 0

for c in sentence.lower():
    if c in "aeiou":
        vowels += 1

print(vowels)   # with "Hello world" → 3

Building a new string

word = input()
result = ""

for c in word:
    result = c + result   # adds at the front

print(result)   # the word reversed

Going through with the index

If you need the position of each character, use range(len(text)):

text = "abc"
for i in range(len(text)):
    print(i, text[i])
# 0 a
# 1 b
# 2 c

Or better, enumerate, which gives position and character together:

for i, c in enumerate("abc"):
    print(i, c)

The alphabet with characters

ord(c) gives the number of a character and chr(n) the character of a number. Since the letters are consecutive, you can go through them with range:

for n in range(ord("a"), ord("e") + 1):
    print(chr(n))   # a b c d e

Practice with Char alphabet.