0 added
0 removed
Original
2026-01-01
Modified
2026-02-21
1
<p>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.</p>
1
<p>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.</p>
2
<p>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<strong>collections</strong>- sets of things you want to go through.</p>
2
<p>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<strong>collections</strong>- sets of things you want to go through.</p>
3
<p>A string is a collection consisting of a set of characters. We will study the other collection types in detail in another course.</p>
3
<p>A string is a collection consisting of a set of characters. We will study the other collection types in detail in another course.</p>
4
<p>Here we see an example:</p>
4
<p>Here we see an example:</p>
5
<p>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>.</p>
5
<p>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>.</p>
6
<p>Let's see how to implement the string reversal function using a for loop:</p>
6
<p>Let's see how to implement the string reversal function using a for loop:</p>
7
<p>Now let's calculate the number of times the character is found in the string (not case-sensitive):</p>
7
<p>Now let's calculate the number of times the character is found in the string (not case-sensitive):</p>
8
8