r/learnpython • u/[deleted] • Oct 09 '20
Understanding the For Loop
Hey All,
I'm having the hardest time understanding for loops in Python.
Could someone explain what is happening in this example? I see we have a variable v. I somewhat understand that "range" is built into Python. I don't understand the output.
for v in range(3, 10, 3):
print(v)Output:
3
6
9
I keep seeing examples online but they lose me every time. Thank you in advance.
-------------------------------------------------
*Edit Thanks to everyone who replied. My misunderstanding was not knowing what range was fully doing.
range(start, stop, step)
366
Upvotes
1
u/rangitaaaa01 Oct 09 '20
The syntax for the range function is range(start, stop, step). And the range function returns a list of numbers for the FOR loop to iterate on.
One point to note here is that ‘start’ing value is included but ‘stop’ value is not. And step is the incremental value which will be added to ‘start’
So, going by your example range(3,10,3):
We begin iteration at start so v= 3(which is also less than the stop value) Then the second time we increment by 3, so v=6(also less than stop value) Then the third time, we increment by 3, so v=9(also less than the stop value) When it is increments to 12, its greater than 10 and hence rejected
So the range function returns [3,6,9]
Now in the for loop,
Rewriting it as pseudocode:
For v in [3,6,9]: Print(v)
So first iteration v=3, output: 3 second iteration v=6, output: 3 6 third iteration v=9, output: 3 6 9
Hope this helps! :)