We can use while
loops for any task that involves looking for something, but it's a bit wordy. Working with while
, you specify a stop condition and a counter. If there are few loops, that's fine, but in real-life coding, loops occur at every step. It gets boring to manage the conditions, especially with the explicit stop condition.
For example, the computer can figure out when the string ends if we want to iterate over the string characters. Python has for
loops for this. We do not have to stop it because it only works on collections — sets of things you want to go through.
A string is a collection consisting of a set of characters. We will study the other collection types in detail in another course.
Here we see an example:
text = 'code'
for symbol in text:
print(symbol)
# => c
# => o
# => d
# => e
In the code above, for
goes through each character in the string, writes it to the symbol
variable, and calls the internal code block where we use that variable. This variable can have any name you want to give it. The general structure of a for
loop looks like this: for <variable> in <collection>
.
Let's see how to implement the string reversal function using a for
loop:
def reverse_string(text):
# Iit is the initial value
result = ''
# The `char' is the variable to which we write the current character
for char in text:
# Combined in reverse order
result = char + result
# The loop ends when we pass the entire string
return result
reverse_string('go!') # => '!og'
Now let's calculate the number of times the character is found in the string (not case-sensitive):
# The `text`` is whatever text you like
# The `char` is the character we look at
def chars_count(text, char):
# Since we're looking for the sum, the initial value is 0
result = 0
for current_char in text:
# We bring everything to lowercase,
# so we don't need to worry about it
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