Deals Of The Week - hours only!Up to 80% off on all courses and bundles.-Close
Introduction
The for loop
6. for loop with strings
The while loop
Nested loops
break and continue
Summary

Instruction

Perfect! for loops can also be used to iterate over a sequence. There are many types of sequences that you'll learn later, but there is one you already know: strings.

Technically speaking, strings are sequences of characters. Take a look:

secret_message = 'hello from the other side'
e_count = 0

for letter in secret_message:
  if letter == 'e': 
    e_count = e_count + 1 
print(e_count)

The program above counts how many times the letter 'e' appeared in the secret_message.

In for letter in secret_message, secret_message is the string variable we want to iterate over, and letter is a temporary variable denoting the current element (character) of the string; we used letter as the identifier, but you can use any name of your choice. Inside the loop (remember about indentation), we check whether letter equals 'e'. If it does, we add one to our counter. Finally, after the loop finishes, we print the value of our counter.

Exercise

Write a program that will first ask the user to provide a password. Then, the program should count how many digits there are in the password and print: Your password contains {number} digits.

You can use letter.isnumeric() to check whether a letter is a digit.