In this shot, we will illustrate to generate a C shape using a nested loop in Python. A nested loop means a loop added into another loop.
Let’s consider we want to return an output with a shape of ‘C’ like the one shown below:
xxxxxxx
xx
xx
xx
xxxxxxxx
We will create a C-shape using the for
loop in Python:
numbers =[7, 2, 2, 2, 7]for x_item in numbers:print('x' * x_item)
for
loop to iterate over each item in the list using a variable x_item
.7
multiplied by x
. This means we have seven x
's on the first line. On the second line, we have two x
's, which continue till the last item of the list.In Python, it’s a straightforward way to create a C shape. However, this is a cheat.
FYI: Python allows the multiplication of a number to a string to repeat the string. A lot of other programming languages do not support this feature.
Now, we will create a C-shape using a nested loop:
numbers =[7, 2, 2, 2, 7]for x_item in numbers:output=''for count in range(x_item):output += 'x'print(output)
for
loop to iterate over each item in the list using a variable x_item
.output
and initially set it as an empty string.range
function to generate a sequence of numbers starting from 0
to x_item
. So in the first iteration, x_item
is 7
, the range of 7
will generate the numbers 0
, 1
, 2
, 3
, 4
, 5
, and 6
. This inner loop will execute seven times, representing the x_item
.x
to our output
variable.For the first iteration, we print our 7
x
’s on the first row, then for the second iteration of our outer loop in line 2, here x_item
is 2
.
In line 3, since we set the output
variable to an empty string, Python goes over to our inner loop to append 2
x
’s (the value of x_item
is 2
) to the output
variable and then print.