Home > Back-end >  while loop got stuck
while loop got stuck

Time:02-28

I was told to convert this 'For' Loop into 'while' :

 sequence = [1, 2, None, 4, None, 5]
total = 0
for value in sequence:
    if value is None:
        continue
    total  = value
print (total)

This is the while loop

sequence = [1, 2, None, 4, None, 5]
total = 0
i=0
while i < len(sequence):
    if sequence[i] is None:
        print('None')
        continue
    else :
        total  = sequence[i] 
    i= 1
print (total)

the 'For' loop gives as a result 12

But it got stuck in the while loop

CodePudding user response:

You can convert any for loop into a while loop without regard for the type of sequence being iterated.

seq_iter = iter(sequence)
total = 0
while True:
    try:
        value = next(seq_iter)
    except StopIteration:
        break
    if value is None:
        continue
    total  = value
print(total)

This depends only on sequence supporting the iterator protocol (which is a requirement of the for loop), not on the sequence having indices that you can increment.

CodePudding user response:

This is how you can convert your for loop into a while loop:

sequence = [1, 2, None, 4, None, 5]
total = 0
j = 0
while j < len(sequence):
    if sequence[j] is not None:
        total  = sequence[j]
    j  = 1
print(total)

The error was that you used = instead of =

CodePudding user response:

Variation on a theme:

sequence = [1, 2, None, 4, None, 5]
total = 0
seq = iter(sequence)
while True:
    try:
        if (nv := next(seq)) is not None:
            total  = nv
    except StopIteration:
        break
print(total)

Output:

12

Note:

Requires Python 3.8

  • Related