Skip to main content

Unit 4 · Loop-de-Loop · Lesson 36 of 57

Letter by Letter

Letter by letter

for loops don't just work with range. Give one a string, and it goes through it one character at a time:

for letter in "Zain":
    print(letter)
Z
a
i
n

Counting things

Here's a really common trick: make a variable that starts at 0, and add to it every time you find something.

password = "purple4life"
vowels = 0

for letter in password:
    if letter in "aeiou":
        vowels += 1

print(vowels)
4

letter in "aeiou" is the same in from the password bouncer. It asks "is this letter one of a, e, i, o or u?" If it is, vowels goes up by 1.

By the end of the loop, vowels holds the total.

Lots of websites want your password to have numbers in it.

Make a function called count_digits that takes a password and returns how many digits (0 to 9) are in it.

count_digits("amer123") should give back 3. count_digits("password") should give back 0.

Python exercise

Write the program in an editor next to the lesson, run it, and have it checked automatically. Create a free account to do this part.

Do this lesson for real

With a free account you get the terminals, challenges and checks that go with the lessons in Intro to Python, and your progress is saved as you go. CyberAcad is a 501(c)(3) nonprofit, so there is nothing to pay.