Home > Software design >  Using a while loop to iterate trough a list but i cant get the item after "150"
Using a while loop to iterate trough a list but i cant get the item after "150"

Time:08-05

The while loop need to iterate trough the list and get the number thats divisible by five, If the number is greater than 150, then skip it and move to the next, If the number is greater than 500, then stop the loop.

list = [12, 75, 150, 180, 145, 525, 50]
i = 0
length = len(list)

while i < length:
    if list[i] > 500:
        break
    
    elif list[i] > 150:
        continue
    
    elif list[i] % 5 == 0:
        print(list[i])
    
    i =1

CodePudding user response:

you dont increment i when item > 150, so

modify

elif list[i] > 150:
    continue

by

elif list[i] > 150:
    i = 1
    continue

or

elif list[i] > 150:
    pass

CodePudding user response:

list = [12, 75, 150, 180, 145, 525, 50]
i = 0
length = len(list)

while i < length:
    if list[i] > 500:
        pass
    
    elif list[i] > 150:
        pass
    
    elif list[i] % 5 == 0:
        print(list[i])
    
    i =1

Output:

75 150 145 50

Or if you want it to exit when 525 comes up then change pass to break in the if statement.

if list[i] > 500:
    break

Output:

75 150 145

  • Related