user
user

Reputation: 1331

How to use a double while loop in python?

Does a python double while loop work differently than a java double loop? When I run this code:

i = 0
j = 1
while i < 10:
    while j < 11:
        print i, j
        j+=1
    i+=1

I get the following output:

0 1
0 2
0 3
0 4
0 5
0 6
0 7
0 8
0 9
0 10

I want it to keep looping to print 1 0, 1 1, 1 2, ... 2 0, 2 1, 2 3... etc. Why does it stop after only one iteration?

Upvotes: 4

Views: 25473

Answers (4)

Alternative:

list1=list(range(0,10))
list2=list(range(0,11))
l = [(x,y) for x in list1 for y in list2]
for a in l:
    for b in a:
        print b,
    print ""

Explanation:

Step 1: Storing 2 lists list1=list(range(0,10)) and list2=list(range(0,11)) so that we know what values to expect in left and right values.

Step 2: Getting a list of all combinations of the list of pairs generated by taking values from list1 and list2 and storign it in l using the command l = [(x,y) for x in list1 for y in list2]

Step 3: Get each element of the list l. Since we want a pair to be printed in the same line use print b,

Step 4: To print next line (\n) character between each successive element, use the print "" command that is shown in the last line.

Upvotes: 1

deadcode
deadcode

Reputation: 2296

A more pythonic approach:

for i in range( 10 ):
    for j in range( 1, 11 ):
        print i, j

Upvotes: 0

Marcin
Marcin

Reputation: 238299

Because your j gets 11 after first iteration. Need to reset it:

i = 0
j = 1
while i < 10:
    j= 1 #<-- here
    while j < 11:
        print i, j
        j+=1
    i+=1

Upvotes: 5

mgilson
mgilson

Reputation: 309949

You probably want to move the j "initialization" inside the first loop.

i = 0
while i < 10:
    j = 1
    while j < 11:
        print i, j
        j+=1
    i+=1

In your code, as soon as j gets to 11, then the inner loop stops executing (with the print statement). In my code, I reset j each time i changes so the inner loop will execute again.

Upvotes: 6

Related Questions