+ 2
python while loop question
I am having the hardest time wrapping my head around how this works? my understanding is that a while loop iterates while whatever argument you give it is true? This loop below for example is the one I'm trying to understand, can anyone please explain in plain English how this works?! Please , please , please :) words =["hello", "world", "spam", "eggs"] iterator=0 print (words[0]) while iterator < len(words): variable = words[iterator] print (variable + "!") iterator += 1
4 Answers
+ 3
First iteration:
i = 0 //base state of increment
variable = words[i] = words[0] = hello
i += 1 //incrementing by one
Second iteration
i = 1 //keeps its value from prev. iteration
variable = words[1] = world
i += 1 //inctementing again
Third iteration:
i = 2
variable = words[2] = spam
i += 1//incrementing again
Fourth iteration:
i = 3
variable = words[3] = eggs
i += 1
Fifth iteration won't happen, because increment is equal to the length of array (4 < 4 == false, so the condition of while loop is no longer true)
At the end you get
hello!world!spam!eggs!
Questions?
+ 1
Yes it did! I wish I had asked earlier :)
0
OMG, I actually get it now! thank you @Freezemage ! So, to make sure I have it right, I re-did it a little and put in my own comments, sorry if it seems like there's an echo in here :)
words =["hello", "world", "spam", "eggs"]
x=0
while x < len(words):
y = words[x]
print (y + "!")
x += 1
# first iteration, y=words[0], so y=hello!
# second iteration, y=words[1] because of the "x += 1", so y=world!
# third iteration, y=words[2] because of the "x += 1" from previous iteration (1+1=2), so y=spam!
# fourth iteration, y=words[3] because of the "x += 1" from previous iteration (2+1=3), so y=eggs!
# fifth iteration, WON'T HAPPEN because next increment = length of list which is 4, (4 < 4 == false, so the condition of while loop is no longer true)
0
@Pete Smiddy, yes, you're absolutely right. Did my answer help?