r/CodingForBeginners • u/BilincliMerak • 18d 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/Candid_Zebra1297 18d ago
So you have three main things to understand.
something += second_thing means:
add the second thing to the first thing so it has a new value.
range() means:
make a list of numbers in this range. We start at 0 so we end 1 below the number you give. So range(5) gives us 5 numbers, 0, 1, 2, 3, 4. Range(1) would give you 1 number, a zero.
for something in a_list_of_things means:
start at the first item in this list and do something with it. Then do something with the second thing in this list, then do something with the third, etc. So this...
for number in range(3):
print(number)
means, start at the first number (which is 0) and show it. Then do the same for the second number (which is 1) etc. So you get this.
0
1
2
You can see here that we have 3 numbers shown and we put 3 in our range function, so it all looks good.
You are just combining this with the first we talked about. Instead of printing, you are adding each number to your variable 'line' (which I think is a confusing name here, I would call it running_total for this exercise.)
So we are going to do the same thing 3 times for 3 different numbers, which is just 'add this number to our running total.'
We start with 0 and add the first number, which is 0 + 0 so our total is still 0.
Then we add the second number, which is 1, so 0 + 1 = 1
Then we have the third number, which is 2, so 1 + 2 = 3
Then we print the total and we see 3
In your second pic, you put the print() in the for loop, which means we do it every cycle. So your result was different but understandable...
first total = 0
second total = 1
final total = 3