Information about cookies on this page

Our website uses cookies to ensure the functionality of the website, to collect and analyze information about the performance and usage of the website. Privacy Policy

  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in
  
  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in

Loops and Text

In the lesson on lists, you saw that you can read the characters of a text by index, just like the elements of a list: word[0] is the first character. The for loop works with text too. In each iteration, the variable holds the next character:

word = "Hello"
for character in word:
    print(character)

This prints:

H
e
l
l
o

The patterns from the previous exercises work with text as well. This loop counts the letters l:

word = "Hello"
count = 0
for character in word:
    if character == "l":
        count += 1
print("Number of l:", count)
Number of l: 2

Remember that uppercase and lowercase letters are different characters: "H" == "h" is False. And a space is a character too, so for "Hi there", the loop would run 8 times.

Instructions

  1. 1

    Go through text with a loop and print each of its characters on its own line.

  2. 2

    Below that, count how many times the letter r appears in text: create a variable count with the value 0, go through the text again and increase count by 1 for every r. After the loop, print Number of r: and count. The output is Number of r: 2.

Back

9/11

  1. 1. The while Loop
  2. 2. The for Loop
  3. 3. Counting with range()
  4. 4. Sum and Average
  5. 5. Counting and Filtering
  6. 6. The Largest Value
  7. 7. The break Statement
  8. 8. The continue Statement
  9. 9. Loops and Text
  10. 10. Nested Loops
  11. 11. Summary
Next

Try it yourself

Do this exercise right here in your browser. No account needed.