How to create a C-shape using nested loop in Python
Overview
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:
Code
numbers =[7, 2, 2, 2, 7]for x_item in numbers:print('x' * x_item)
Explanation
- Line 1: We create a list of numbers.
- Line 2: We create a
forloop to iterate over each item in the list using a variablex_item. - Line 3: We print the output: each item in the list starting with the first item
7multiplied byx. This means we have sevenx's on the first line. On the second line, we have twox'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.
Using a nested loop
Now, we will create a C-shape using a nested loop:
Code
numbers =[7, 2, 2, 2, 7]for x_item in numbers:output=''for count in range(x_item):output += 'x'print(output)
Explanation
- Line 1: We create a list of numbers
- Line 2: We create a
forloop to iterate over each item in the list using a variablex_item. - Line 3: We define a variable
outputand initially set it as an empty string. - Line 4: We create an inner loop using the
rangefunction to generate a sequence of numbers starting from0tox_item. So in the first iteration,x_itemis7, the range of7will generate the numbers0,1,2,3,4,5, and6. This inner loop will execute seven times, representing thex_item. - Lines 4 and 5: We append an
xto ouroutputvariable. - Line 6: We print the output.
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.