loop in loop for print text in python

To print text using nested loops in python, we can use two for loops.

Example:

main.py
# A nested loop to print a string multiple times
for i in range(3):
    for j in range(4):
        print("Hello World")
120 chars
5 lines

This will print "Hello World" 12 times as the outer loop will run 3 times, and the inner loop will run 4 times for each iteration of the outer loop.

We can further customize the output by using string formatting to insert values into the string, and the end parameter of the print() function to control the line breaks.

Example:

main.py
# A nested loop to print a string with values
for i in range(1, 4):
    for j in range(1, 6):
        print(f"i = {i}, j = {j}", end='\t')
    print('\n')
155 chars
6 lines

This will print:

main.py
i = 1, j = 1	i = 1, j = 2	i = 1, j = 3	i = 1, j = 4	i = 1, j = 5	

i = 2, j = 1	i = 2, j = 2	i = 2, j = 3	i = 2, j = 4	i = 2, j = 5	

i = 3, j = 1	i = 3, j = 2	i = 3, j = 3	i = 3, j = 4	i = 3, j = 5	
200 chars
6 lines

Here we are using the f format specifier to insert the values of i and j into the string. We are also using \t to insert a tab character between the values, and \n to insert a newline character at the end of each inner loop.

gistlibby LogSnag