r/learnpython • • 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

62 comments sorted by

View all comments

1

u/OnlySeesLastSentence Oct 09 '20

It translates to "let's make a changing variable called v. I want to start it at 3. So v is three. (That's what the first 3 is). Now, I want to keep doing it until we reach the second number or are forced to go higher than it, which is 10. But before I do that, let me increase it by the third number. 3+3=6. That's less than 10. So show 6. Now increase by 3, that's 9. Show it. Increase by 3... Oh no, it's more than 10. Abort without printing!"