0
for x in range(0,len(b)):
    if x+1 < len(b):
        if b[x][1] == 'B' and b[x+1][1] == 'B':
            a.append([b[x][0], b[x][2]])
        elif b[x][1] == 'B'and b[x+1][1] == 'I':
            kata = b[x][0]
            a = 1
            while True:
                if x+a < len(b):
                    if b[x+a][1] == 'I':
                        kata += ' ' + b[x+a][0]
                        a += 1
                    elif b[x+a][1] == 'B':
                        break
                else:
                    break
            a.append([kata, b[x][2]])
    else:
        if b[x][1] == 'B':
            a.append([b[x][0], b[x][2]])

Can someone help me to convert the for-loop become while-loop? and the while-loop stay while-loop?

2
  • Do you have a particular reason to want to do that? A while loop offers no advantages here. If this is purely for exercise, see my answer below.
    – Zinki
    May 14, 2018 at 8:11
  • Maybe you should convert the while loop into a for loop: for y in range(x+1, len(b)): where y = x+a...
    – jferard
    May 14, 2018 at 9:50

1 Answer 1

0

a for loop of the form

for x in y:
    #code 

can always be turned into a while loop of the form

i=0
while i < len(y):
    x = y[i]        
    #code
    i += 1

since x in your case is just iterating through values 0 to len(b) you can further reduce it down to:

x=0
while x < len(b):       
    #code
    x += 1
1
  • This isn't strictly true – it won't work for generators, for instance. For that you would need to get an iterator over y via it = y.__iter__(), then do try: x = it.next() and catch StopIteration, per the iterator protocol.
    – ash
    May 14, 2018 at 8:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.