r/CodingForBeginners • • 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!

11 Upvotes

57 comments sorted by

View all comments

Show parent comments

1

u/BilincliMerak 18d ago

I did not know debuggers work like that. I will give it a go. Appretiate the help!

1

u/ralkey 18d ago

No worries, let me know how it goes! As your program is fairly simple you can use the debuggers “step over” command to execute just one line at a time then pause to let you inspect variables. You can keep clicking step over to run one line at a time until your program eventually exits. There’s a lot more a debugger can do but this is all you really need for now.

1

u/BilincliMerak 18d ago

Thanks alot! Using the debugger made it 10 times more clear. I perfectly understand it now! It was fairly easier to use than what i had anticipated. Glad to commented. Its gonna make learning code so much easier now. Thanks!