Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

loop
python
communitycreator

How to create a C-shape using nested loop in Python

Onyejiaku Theophilus Chidalu

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)
Making a C-shape using for loop

Explanation

  • Line 1: We create a list of numbers.
  • Line 2: We create a for loop to iterate over each item in the list using a variable x_item.
  • Line 3: We print the output: each item in the list starting with the first 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.

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)
Making a C-shape using nested for loop

Explanation

  • Line 1: We create a list of numbers
  • Line 2: We create a for loop to iterate over each item in the list using a variable x_item.
  • Line 3: We define a variable output and initially set it as an empty string.
  • Line 4: We create an inner loop using the 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.
  • Lines 4 and 5: We append an x to our output variable.
  • 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.

RELATED TAGS

loop
python
communitycreator

CONTRIBUTOR

Onyejiaku Theophilus Chidalu
RELATED COURSES

View all Courses

Keep Exploring