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.

63

u/[deleted] Oct 09 '20

Great explaination! I didn't know I could use one or two arguments thanks for taking the time to write this.

55

u/[deleted] Oct 09 '20

Np. You can also go backwards range(10, 1, -1)

6

u/iwhonixx Oct 09 '20

Isn't this community awesome?!

1

u/DrFodwazle Oct 09 '20

It probably has the greatest range of any sub. Some people are incredibly helpful and explain stuff better than anyone else could. But I've also come across some assholes who call you an idiot for not understanding something

3

u/coder155ml Oct 09 '20

In a for loop you can use 1 2 or 3 arguments as shown above

7

u/Morkai Oct 09 '20

Legend. Such a clear explanation. Many thanks.

6

u/[deleted] Oct 09 '20

Range generates numbers, unless you pass an object, range behaves in some ways that not so intuitive.

5

u/Cheese-whiz-kalifa Oct 09 '20

Yeah just try to remember range(start point,end point(not include in output), increment range by)

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

1

u/rawrtherapy Oct 09 '20

This is awesome