Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
communitycreator

How to create an L-shape using the nested loop in Python

Onyejiaku Theophilus Chidalu

Overview

The nested loops in Python refer to when a loop is added into another loop.

In this shot, we’ll illustrate how to generate an L shape, using a nested loop in Python. We’ll be returning an output with a shape of L, like the one shown below:

xx
xx
xx
xx
xxxxxxxx

We can generate an L shape in Python with a few lines of code, as shown below:

Code

numbers =[2, 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 for loop to iterate over each of the items in the list, using the variable x_item.
  • Line 3: We print the output, which contains each of the items in the list, starting with the first item 2 multiplied by x.

This simply means that we will have two x's on the first line. On the second line we will have two x's. This continues till the last item of the list. This is a simple way to create an L shape in Python.

Python allows the multiplication of a number to a string in order to repeat the string. Many of other programming languages do not support this feature.

Using a nested loop

Now, we’re going to use a nested loop to create the same output we had in the previous code.

Code

numbers =[2, 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 for loop to iterate over each of the items in the list, using the 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. In the first iteration, x_item is 7, so the range of 2 will generate the numbers 0 and 1. This means that this inner loop will be executed two times and that is exactly what x_item represents.
  • Line 5: From the iteration in line 4, we append an x to our output variable.
  • Line 6: We print the output. This means, that for the first iteration, we simply print our two x’s on the first row, then we go to the second iteration of our outer loop in line 2. Here x_item is 2. Now, we go back to line 3, since the ouput variable was set to an empty string. Python goes over to our inner loop, where it will append two x’s (the value of x_item is 2) to the output variable, and then print.

RELATED TAGS

python
communitycreator

CONTRIBUTOR

Onyejiaku Theophilus Chidalu
RELATED COURSES

View all Courses

Keep Exploring