r/learnpython • u/[deleted] • 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
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. Sorange(5)gives you 0 1 2 3 4If 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 4The 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.