Python How To Convert This For Loop Into A While Loop
Possible Duplicate: Converting a for loop to a while loop I have this for a for loop which I made I was wondering how I would write so it would work with a while loop. def scrol
Solution 1:
Well, you are nearly there. It's like this:
defscrollList2(myList):
negativeIndices=[]
i= 0
length= len(myList)
while i != length:
if myList[i]<0:
negativeIndices.append(i)
i=i+1return negativeIndices
The problem you had is that you must increment the loop index on each iteration. You were only incrementing when you found a negative value.
But it's better as a for
loop and your for
loop is over complicated. I'd write it like this:
defscrollList(myList):
negativeIndices=[]
for index, item inenumerate(myList):
if item<0:
negativeIndices.append(index)
return negativeIndices
Solution 2:
Well, for one, your incrementer i
should always be updated, instead of just when you meet the condition. Only doing it in the if
statement means you're only ever advancing when you see a returnable element, so if your first element doesn't meet your condition, your function will hang. Oops. This would work better:
defscrollList2(myList):
negativeIndices=[]
i= 0
length= len(myList)
while i != length:
if myList[i]<0:
negativeIndices.append(i)
i=i+1return negativeIndices
Post a Comment for "Python How To Convert This For Loop Into A While Loop"