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:
print('Day 0')
print('Day 1')
print('Day 2')
print('Day 3')
print('Day 4')
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:
for day in range(5):
print('Day', day)
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.
for item
Then there's the keyword in
followed by the sequence to loop over and a colon.
for item in sequence:
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.
for item in sequence:
# Code block to be executed for each item
print(item)
The sequence over which the loop iterates can be a list, tuple, string, or a range.
Here, we loop over a list of fruits:
names = ['apple', 'banana', 'cherry']
for fruit in names:
print(fruit)
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:
names = ('apple', 'banana', 'cherry')
for fruit in names:
print(fruit)
Here, our sequence is a string. When using a string the loop iterates over each character within the string:
text = 'apple'
for char in text:
print(char)
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:
range(start, stop, step)
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.
range(3) # creates the range 0, 1, 2
range(0,3,1) # same output: 0, 1, 2
Here, we loop over a range from 2 (included) to 10 (not included) with a step of 2:
for i in range(2,10,2):
print(i)
Of course you can do more than just printing the loop variable.
For example, here we sum all the numbers from 1 to 10:
total = 0
for i in range(1,11):
total += i
print(total)
What will be the output?
for i in range(4):
print(i)
What will be the output?
for i in range(1,4):
print(i)
What will be the output?
for i in range(1,5):
print(i)
What will be the output?
for i in range(1,5,3):
print(i)
What will be the output?
for i in 'Blue':
print(i)
What will be the output?
l = ['a', 'b', 'abc']
for i in l:
print(i)