-2

not working while-loop

i=0

l1=["rohan","sachin","sam","raj"]

while i<len(l1):

    if l1[i].startswith('s'):  #if i comment out  this line it is working 

        print("GREET "+l1[i])

        i=i+1
Mike Scotty
  • 10,530
  • 5
  • 38
  • 50

3 Answers3

1

That is because incrementing of i is done inside if condition instead of while loop. As first word in your list did not start with "S" it wont go inside if hence i is not incremented and while loop executes forever. it is just a logic issue

Venkat
  • 115
  • 1
  • 2
  • 8
0

Indentation is important in Python.

You must increment your counter i every time, not just when you print, otherwise it's an endless loop.

i=0

l1=["rohan","sachin","sam","raj"]

while i<len(l1):

    if l1[i].startswith('s'): 

        print("GREET "+l1[i])

    i=i+1 # <- increment counter outside of if-block!
Mike Scotty
  • 10,530
  • 5
  • 38
  • 50
0

yes ,after shifting counter to left it is working. counter should be placed out side of if block.

  • Welcome to stackoverflow! Use an code example with references when you provide an answer to help illustrate the answer best. – lys Dec 30 '21 at 07:10
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Dec 30 '21 at 07:10