Home > Mobile >  while loop that is equivalent to for loop
while loop that is equivalent to for loop

Time:10-26

I am trying to experiment how the while loop works.

docs = ['123867', '256789', '3aa', '4gg', '5yy', '6abc']
for i in range(0,len(docs)):
  for j in range(i,len(docs[i])):
    print(i, j)

My output for the above code is

0 0
0 1
0 2
0 3
0 4
0 5
1 1
1 2
1 3
1 4
1 5
2 2


I attempt to play with the while loop with

docs = ['123867', '256789', '3aa', '4gg', '5yy', '6abc']
i = 0
j = i
while i < len(docs):
  while j < len(docs[i]):
    print(i, j)
    j  = 1
  i  = 1


but the output is

0 0
0 1
0 2
0 3
0 4
0 5

How can I fix my while loop to match the for loop? Thanks!

CodePudding user response:

docs = ['123867', '256789', '3aa', '4gg', '5yy', '6abc']
i = 0
while i < len(docs):
    j = i  # should be moved here
    while j < len(docs[i]):
        print(i, j)
        j  = 1
    i  = 1
  • Related