Can you have two for loops in python?

You may not need the nested for-loop Solution.
A Single Loop with List Comprehension [as shown below] would suffice:

r_list  = list[range[2, 11]]   
output  = []
for m in r_list:
    tmp = [m*z for z in r_list]
    output.append[tmp]

print[output]

Or Simpler:

output  = []
for m in list[range[2, 11]]:
    tmp = [m*z for z in list[range[2, 11]]]
    output.append[tmp]

print[output]

Prints:

    [
        [4, 6, 8, 10, 12, 14, 16, 18, 20], 
        [6, 9, 12, 15, 18, 21, 24, 27, 30], 
        [8, 12, 16, 20, 24, 28, 32, 36, 40], 
        [10, 15, 20, 25, 30, 35, 40, 45, 50], 
        [12, 18, 24, 30, 36, 42, 48, 54, 60], 
        [14, 21, 28, 35, 42, 49, 56, 63, 70], 
        [16, 24, 32, 40, 48, 56, 64, 72, 80], 
        [18, 27, 36, 45, 54, 63, 72, 81, 90], 
        [20, 30, 40, 50, 60, 70, 80, 90, 100]
    ]

Their many ways used to Two for loops in Python. Like combine 2 lists or addition or filter out by conditions or print any pattern.

Example 1

Multiplication of numbers using 2 loops.

for i in range[1, 5]:
    for j in range[1, 5]:
        print[i * j, end=' ']

Output:

Two for loops in Python

Example 2

Nested while loop Python.

i = 1
j = 5

while i < 4:
    while j < 8:
        print[i, ",", j]

        j = j + 1
        i = i + 1

Output:

1 , 5
2 , 6
3 , 7

Example 3

Nested for loop example

color = ["Red", "Green"]
num = [1, 2, 3]

for x in color:
    for y in num:
        print[x, y]

Output:

Red 1
Red 2
Red 3
Green 1
Green 2
Green 3

How to break out of two for loops in Python?

breaker = False
i = 1
while True:
    while True:
        print[i]
        if i == 0:
            print["Zero"]
            breaker = True
            break
        i = i - 1
    if breaker:  # the interesting part!
        break  # 

Chủ Đề