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
16
u/Fermter Almost OK Oct 09 '20
OK, this is more a function of what "range" is doing that what the "for" loop is doing.
Here, the for"loop is just setting
vto be every value returned byrange(3, 10, 3), and then printing that value.Range, on the other hand, is doing something special. The 3 values you're passing to range are, respectively, the start, stop, and step. Range starts at the start, stops before the stop, and increments by the step every time.
In this case, the start is 3, the stop is 10, and the step is 3. Therefore, the range returns 3, 6, and 9, in that order (because it starts at 3, 3+3 = 6, 6+3 = 9, and 9+3 = 12, which is bigger than 10, so it stops and doesn't do anything with that value).
From the perspective of the for loop,
vis set to 3 first, then printed inprint(v). Then, it is set to 6 and printed, and then set to 9 and printed.