Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a double while loop in python?

Tags:

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?

like image 984
user Avatar asked Oct 28 '25 06:10

user


2 Answers

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.

like image 145
mgilson Avatar answered Oct 29 '25 21:10

mgilson


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
like image 44
Marcin Avatar answered Oct 29 '25 21:10

Marcin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!