Related Tags

loop
python
communitycreator

How to create an F-shape using nested loop in Python

Onyejiaku Theophilus Chidalu

Overview

Nested loops in python simply means a loop added into another loop.

In this shot, we want to briefly illustrate how we can easily generate an F shape using a Nested loop in python. Now imagine you want to return an output with a shape of ‘F’ like the one shown below:

xxxxxxx
xx
xxxxxxx
xx
xx


Normally, this is a simple thing to do in python with few line of code like the one below:

Code

numbers =[7, 2, 7, 2, 2]
for x_item in numbers:
print('x' * x_item)


Explanation

• Line 1: we created a list of numbers
• Line 2: we created a for loop to iterate over each item in the list using a variable x_item.
• Line 3: we printed the output which contains each of the items in the list starting with the first item 7 multiplied by 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 F shape in python, however, this is a cheat.

Interestingly python allows the multiplication of a number to a string in order to repeat the string. A lot of other programming languages do not support this feature.

Using a nested loop

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.

Code

numbers =[7, 2, 7, 2, 2]
for x_item in numbers:
output=''
for count in range(x_item):
output += 'x'
print(output)


Explanation

• Line 1: we created a list of numbers
• Line 2: we created a for loop to iterate over each items in the list using a variable x_item.
• Line 3: we defined a variable output and initially we set it as an empty string
• Line 4: we created 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, so the range of 7 will generate the numbers 0, 1, 2, 3, 4, 5, and 6; meaning that this inner loop will be executed seven times and that is exactly what x_item  represents.
• Line 5: from the iteration in line 4, we need to append an x to our output  variable.
• Line 6: we printed the output. Meaning that for the first iteration, we simply print our 7 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 back to line 3, since we set the ouput variable to an empty string, python goes over to our inner loop where it will 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

Learn in-demand tech skills in half the time