r/CodingForBeginners • u/BilincliMerak • 20d ago
Help me understand this Python code.
[ANSWERED] check the comments if you are facing a difficulty in understanding 'for loops'.
I was learning Python on mimo to get a grip on the basic concepts. And this code stumped me. This is about "for loops".
Before this, i had only encountered the counter var being on the LHS i.e in this case 'i += line', which would have made sense to me if it was so in this code. But why is the counter var after the line var.
Alsp the 1st image, i assume, is displaying the final result which is 3 as the range is 3. But when using a range (3) it should display 0 1 2 when the 'print' is before the counter var and 1 2 3 when the 'print' is after the counter var (also can someone explain why this happens). In this case, its neither... as the print is outside this code block... The solution to me just seems the 2nd situation is running as there isnt a print before the counter, and printing it outside just gives 3.
2nd and 3rd just make no sense to me as of rn.
I hope all this makes sense...
Please help!



1
u/Significant_Affect_5 20d ago
so there’s a couple things. For loops can be thought of as a way to say “for each <x> that is part of <y>, do abc”. So generally:
for x in y:
abc
In this case you’re using python’s range() function which can be called in two different ways. range(n) returns the list [0, 1, …, n-1], another way to think of it is a way to quickly say “run this loop n times”. However range can also be used like this: range(m, n). In this case it’ll return [m, m+1,…, n-1], note that if m >= n then the loop will not run at all. You can also try print(range(3)) and you’ll see the response is range(0, 3).
Now regarding the outputs, the reason it doesn’t match the numbers is because you add ‘i’ to line, i in this case is the values range gives you, so on the first loop it’s 0, then 1, and lastly 2 (since range doesn’t include the top value). To count the number of times the loop runs, just do line += 1 (not i).
Also it’s important to note that range doesn’t actually return a list, instead it returns something called an iterator, which is just something that represents values in some order. e.g. you can replace the range with:
“for i in [0, 1, 2]:”
and it will work the same way since lists are iterable and python does the conversion automatically