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