Introduction to for-loops in Python
Learn the principles of for-loops in Python, understanding how to repeatedly execute a specific task and iterate over sequences of data.
We'll start with the following code:
That's a lot of code just to perform nearly the same task five times, right?
If we were to use a loop, we could make this code much cleaner and shorter.
Here is the loop version of the code above:
So, how does this work?
A for loop iterates over a sequence of elements.
Let's explore the syntax step by step.
A for loop begins with the keyword for
followed by a variable representing each item in an iterable. This variable can have any name.
Then there's the keyword in
followed by the sequence to loop over and a colon.
Finally, there's an indented code block to be executed for each line. The code block has access to the current item of the sequence.
The sequence over which the loop iterates can be a list, tuple, string, or a range.
Here, we loop over a list of fruits:
However, since we don't modify the elements within the list, a tuple would be more suitable.
Here's the same sequence of elements, but this time we're looping over a tuple:
Here, our sequence is a string. When using a string the loop iterates over each character within the string:
Finally, a loop can iterate over a range generated by the range()
method.
The range()
method is used to generate a sequence of numbers.
You can define the starting value of the range, the end value, and the step size:
Only a single argument can be passed to range()
which will be used as the end value. The range will stop one step before this end value.
If you do so, the start value defaults to 0, and the step value defaults to 1.
Here, we loop over a range from 2 (included) to 10 (not included) with a step of 2:
Of course you can do more than just printing the loop variable.
For example, here we sum all the numbers from 1 to 10:
What will be the output?
What will be the output?
What will be the output?
What will be the output?
What will be the output?
What will be the output?