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

228

u/[deleted] Oct 09 '20

range() generates numbers.

If you only pass 1 argument range(5) it will start from 0 and keep going up, and stop before hitting 5. I know sounds strange but that's how it works. So range(5) gives you 0 1 2 3 4

If you pass 2 arguments, range(1,5), same as above except this time it starts from your first argument, 1. So you get 1 2 3 4

The 3rd argument is how each steps increases. By default it's 1. Let's pass a 2 and see what happens?

range(1, 10, 2) --> 1 3 5 7 9. Starts from 1, goes up 2 each time, stops before 10.

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)

1

u/[deleted] Oct 09 '20

Hmm, that is right. thank you u/gatherinfer for explaining this better