Nested loops in python simply mean a loop added into another loop.
In this shot, we want to briefly illustrate how we can easily generate an E shape using a nested loop in python. Now imagine you want to return an output with a shape of ‘E’ like the one shown below:
xxxxxxx xx xxxxxxx xx xxxxxxx
Normally, this is a simple thing to do in python with few line of code like the one below:
numbers =[7, 2, 7, 2, 7] for x_item in numbers: print('x' * x_item)
x. This simply means that we will have seven
x's on the first line. On the second line we will have two
x's and this continues till the last item of the list. This is a very simple way to create an E shape in python, however, this is a cheat.
Python allows the multiplication of a number to a string in order to repeat the string. A lot of other programming languages does not support this feature.
What we want to achieve here is to use a nested loop to create exactly what we had as an output in the previous code.
numbers =[7, 2, 7, 2, 7] for x_item in numbers: output='' for count in range(x_item): output += 'x' print(output)
outputand initially we set it as an empty string.
range()function to generate a sequence of numbers starting from
x_item. So in the first iteration,
7, so the range of
7will generate the numbers
6; meaning that this inner loop will be executed seven times and that is exactly what
4, we need to append an
x’s on the first row, then we go to the second iteration of our outer loop in line
2. Now back to line
3, since we set the
ouputvariable to an empty string, python goes over to our inner loop where it will append two
x’s (the value of
2) to the
outputvariable and then print.
View all Courses