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/anh86 Oct 09 '20

You're 'iterating' through some group of values, assigning each value in the group to v, running the code block, then assigning the next value to v, running the code block, until each value in that group/range is used.

In your example, the group of values is defined by the range() function and you've passed in three parameters -- range(start_value, stop_value, increment). In other words, your group is the values between 3 and up to (but not including) 10 with step increments of 3. Thus, your group of values is 3, 6, and 9.

So, on the first iteration of the loop, the value 3 is assigned to your variable v and the code block is run. In this case the code block is to simply print whatever is loaded into v. After printing 3, 6 is assigned to v and the code block is run again.

You also don't have to use the range() function to set your group. You could define your own list like for v in ['I', 'love', 'Python']: and you'd get each of those values printed. You could load some list into a variable like my_list = ['I', 'love', 'Python'] and then call for v in my_list:.

Hopefully that clears it up!