Table of Contents[Hide][Show]
In the last tutorial, we learned about while loops and how to execute a block of code multiple times.
In Python, we have other kinds of loops like “for loop” and “nested loop”. Let’s see how they are used.
For Loops
We use “for loop” to iterate over items of a collection, such as a string. As the string is a sequence of characters, it looks like a collection. Therefore, we can use a for loop to iterate over each character in a string and then do something with it.
Here’s an example.
We type “for” followed by a variable and then a string.
for item in 'Python':
Here the “item” means the characters of the word Python. In the first iteration of the loop “item” means ‘P’, the second iteration means ‘y’ and so on. Let’s execute this
You can see each character in this string is printed on a new line.
Let’s look at another example. In Python, we can define lists using square brackets. So let me define a list using square brackets.
for item in ['Shahbaz', 'Aayush', 'Jay']:
print(item)
Now it will list the three names on separate lines.
We can also use a list of numbers in this setting. Instead of typing all the numbers from 0 to 9, I am going to use the function “Range” to simplify things. Let’s see how it’s done.
for item in range(10):
print(item)
We can also program it to start not with 0.
for item in range(5, 10):
It will print numbers 5 to 9 on the terminal.
The “Range” function can also take the steps as input. So if we write it like this:
for item in range(5, 10, 2):
It will print 5, 7 and 9 which means it goes two steps forward after every iteration.
Exercise
Now here’s an exercise for you. I want you to write a program to calculate the total cost of all the items in a shopping cart. So let’s say we have a list of prices like 10, 20, and 30, I want you to use a for loop to calculate the total cost of all the items in our imaginary shopping cart.
Put your brain to work and see if you can do it. No cheating.
Solution
You can start by listing the prices like this.
prices = [10, 20, 30]
Now add a variable for a total price which will start from 0 for the first iteration.
total = 0
Here’s our for loop.
for price in prices:
total = total + price
// It can be simplified as total += price
print(f"Total: {total}")
Nested Loops
In Python, using a nested loop basically means adding one loop inside of another loop, and with this technique, we can do some amazing things. For example, we can easily generate a list of coordinates.
A coordinate, as you know is a combination of ‘x’ and ‘y’ values. Let’s say 0 and 0. Now let’s say you want to generate a list of coordinates like this. We have 0 and 0, then we’ll have 0 and 1, then 0 and 2.
Next, we’re going to change ‘x’. We’re going to use 1 for ‘x’, and once again we’re going to use these 3 values for the ‘y’ coordinates.
We can easily generate these coordinates using nested loops.
Let me show you.
for x in range(4):
for y in range(3):
print(f'({x}, {y}')
Let’s check the output:
So let me explain exactly how this program gets executed. In the first iteration of our outer loop, ‘x’ is 0. Now we are on line 2, here we have a new loop which we call an inner loop. In this inner loop, in the first iteration, ‘y’ is going to be 0, so 0 and 0 are printed on the terminal.
Now the control goes back to line 2 or our inner loop. In this second iteration, ‘y’ will be set to 1, but we are still in the first iteration of our outer loop. So ‘x’ is still 0, but now ‘y’ is incremented to 1.
That is why we see 0 and 1 on the terminal. This will continue until our inner loop is executed and then the interpreter will go again to the outer loop and this process continues until the outer loop is completed.
Challenge
Here’s an exercise for you, but this one is a little bit more challenging than the exercises you have done so far.
Using nested loops, write a code to draw this ‘F’ shape:
Solution
numbers = [5, 2, 5, 2, 2]
for x_count in numbers:
output = ''
//We are going to reset the output variable to an empty string.
for count in range(x_count):
output += 'x'
print(output)
There is a much simpler way to execute this without using nested loops. I leave it for you to figure out.
Wrap Up
Are you guys also feeling the heat going up with every lecture?
I definitely feel like that. I have made it much simpler for you to understand.
Let’s bring things up with our next lecture.
Leave a Reply