Python Basics
Theory: The for cycle
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:
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:
Now let's calculate the number of times the character is found in the string (not case-sensitive):
Completed
0 / 43