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

Show parent comments

5

u/[deleted] Oct 09 '20

The stopping before 5 is actually very logical. It stops after 5 numbers have been counted, and as we start from 0, it ends at 4

1

u/learnorenjoy Tabs Oct 09 '20

But what of the example above range(1,5) it still has the argument 5 but doesn't include it when printed out. So in such a case, it may not be so intuitive or 'logical'.

3

u/[deleted] Oct 09 '20

[removed] — view removed comment

2

u/El_Dumfuco Dunning-Kruger sufferer Oct 09 '20

With this design philosophy, it also has a concatenative property: range(a,b) + range(b,c) = range(a,c)