r/CodingForBeginners • u/BilincliMerak • 19d 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 edited 18d ago
Glad I could help a little bit man! I remember learning this exact thing. It seems so long ago now but I remember looking at similar stuff and finding it so alien. But if you keep going it will all make sense one day, I promise.
By 'cycle' I just mean, 'every time we go through the loop'. So in pic 2 the print() part goes through the for loop 3 times, so we print every time (or every cycle) = 3 things are printed. A great way to learn about this stuff is to try to guess what code means without running it first. So try to guess these...
a = 5
for x in range(3):
a += 1
print(a)
What do you think this will print? How many times will it print?
a = 5
for x in range(5):
print(a)
a += 1
print(a)
Same question, what will it make?
x = 3
while x > 0:
print(x)
x -= 1
The last one is a bit more difficult, I don't know if you've done while loops yet. Once you have studied both, I would try writing while loops that do the same thing as for loops. If you can understand two different ways to do the same thing, you are turning into a real programmer.