Free Python course. Sign Up for tracking progress →

Python: Cycle For

The while' loop can be used to solve any item search problem, but it is notable for being verbose. Forwhile` it is necessary to set a stopping condition and enter a counter. When there are few loops, this is fine, but in real code loops occur at every step. It is therefore tedious to manage the conditions manually, especially when the stopping condition is obvious.

For example, if we want to go through the characters in a string, the computer can figure out by itself when the string ends. For such situations, Python introduced the for loop. It knows itself when to stop, because it only works with collections - sets of elements that need to be searched.

A string is a collection because it consists of a set of characters. The other types of collections are studied in detail in another course.


text = 'code'
for symbol in text:

# => c
# => o
# => d
# => e

In the code above, for goes through each character in the string, writes it in a variable symbol and calls the internal code block where that variable is used. The name of this variable can be anything. The general structure of the for' loop looks like this:for in '.

Let's see how to implement the string flip function through the for loop:

def reverse_string(text):
    # Initial value
    result = ''
    # char - a variable in which the current character is written
    for char in text:
        # Connect in reverse order
        result = char + result
    # The cycle ends when the whole line is passed
    return result

reverse_string('go!')  # => '!og'

Now let's calculate the number of mentions of a character in the string, not case-sensitive:

# text - any text
# char - a symbol to consider
def chars_count(text, char):
    # Since we are looking for the sum, the initial value is 0
    result = 0
    for current_char in text:
        # We convert everything to lower case,
        # so as not to depend on the current register
        if current_char.lower() == char.lower():
            result += 1
    return result

chars_count('hexlet!', 'e')  # 2
chars_count('hExlet!', 'e')  # 2
chars_count('hExlet!', 'E')  # 2

chars_count('hexlet!', 'a')  # 0


In a previous lesson, we already wrote the filter_string() function. Recall that it takes a string and a character as input and returns a new string in which the passed character at all its positions is removed. This time, implement this function using the for loop. An additional condition: the case of the character to be eliminated does not matter.

An example of a call:

text = 'If I look forward I win'
filter_string(text, 'i')  # 'f  look forward  wn'
filter_string(text, 'O')  # 'If I lk frward I win'
The exercise doesn't pass checking. What to do? 😶

If you've reached a deadlock it's time to ask your question in the «Discussions». How ask a question correctly:

  • Be sure to attach the test output, without it it's almost impossible to figure out what went wrong, even if you show your code. It's complicated for developers to execute code in their heads, but having a mistake before their eyes most probably will be helpful.
In my environment the code works, but not here 🤨

Tests are designed so that they test the solution in different ways and against different data. Often the solution works with one kind of input data but doesn't work with others. Check the «Tests» tab to figure this out, you can find hints at the error output.

My code is different from the teacher's one 🤔

It's fine. 🙆 One task in programming can be solved in many different ways. If your code passed all tests, it complies with the task conditions.

In some rare cases, the solution may be adjusted to the tests, but this can be seen immediately.

I've read the lessons but nothing is clear 🙄

It's hard to make educational materials that will suit everyone. We do our best but there is always something to improve. If you see a material that is not clear to you, describe the problem in “Discussions”. It will be great if you'll write unclear points in the question form. Usually, we need a few days for corrections.

By the way, you can participate in courses improvement. There is a link below to the lessons course code which you can edit right in your browser.

If you got stuck and don't know what to do, you can ask a question in our community