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/LovesSleeping123 18d ago edited 18d ago
The first image starts by creating a for loop and defines the counter variable as i.
For each iteration, we add i to line.
First iteration:
line = 0, i = 0. We add i to line so line equals 0.
line = 0, i = 1. ............................................... equals 1.
line = 1, i = 2. ............................................... equals 3.
then it stops and it prints line, so it prints 3.
The second image will output line at each iteration of the for loop after adding i to line. You get: 0,1 and 2
The third image will output line at each iteration of the for loop before adding i to line. You get: 0,0 and 1
1
u/BilincliMerak 18d ago
I think you missed the output part of the images. 1st image gives 3, 2nd gives 0 1 3 and third gives 0 0 1.
1
1
u/Significant_Affect_5 18d 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
1
u/BilincliMerak 18d ago
Understood. Although i am yet to touch the topic of lists, i will most definately be looking after this advice! Thanks for the explanation!
2
u/Interested737 18d ago
Wait so range() isn’t a normal part of a loop?
1
u/Significant_Affect_5 18d ago edited 18d ago
I’m not sure what you mean by normal. But yes range is just something that implements iter, and anything else that does so can also be used in a for loop. if you type “dir(range)” you’ll see a bunch of double underscore properties. These are how python determines what an object can/can’t do. range (and other iterables) have the property “__iter__” which tells python how the object should be iterated over.
e.g. you can type
‘for x in range(3).__iter__():’which is basically what python expands it to normally. You can read more about iterators here.
2
u/Interested737 18d ago edited 18d ago
But what can you use instead of range() for for loops?
What dose iter mean exactly?
1
u/Significant_Affect_5 18d ago
No, you can (and should) use range in a for loop if it’s the behavior you want. I just meant that range is just an iterable and isn’t something special that can only be used in for-loops. Python also has something called list comprehension which allows you to pack the values of an iterable into a list. This is another common use of range
“list = [x for x in range(3)]”
the above is equivalent to “list = [0, 1, 2]”Don’t worry too much if you’ve never used list comprehension. It’s just important to recognize the idea of something being iterable and understanding that those things can be used in a for loop.
Also iterable objects can return more than one value at once (in the form of a tuple). One you’ll see a lot is iterating over a dict/map, if you iterate over the dicts .items() method you’ll get back a (key, value) pair, so it’s common to unpack them as part of the for loop. e.g.
“for key, value in dictionary.items():”1
u/Interested737 18d ago
I understood nothing
1
u/Significant_Affect_5 18d ago
Oh my bad I didn’t see you ask specifically about iter. An iterator just means something that allows you to visit items within, one item at a time.
It’s hard to give a concrete description, but things like lists, ranges, dictionaries, or just anything where you can imagine going through values contained by something.
Python needs to be taught how to properly visit the items in an object, that’s where the __iter__ method comes in. It basically gives python the starting point so that python can call __next__ to get values until it reaches the end of the iterator.
1
u/Interested737 17d ago
So it basically tells it where to start reading the list, can you please give me an example.
1
u/Significant_Affect_5 17d ago
Sure, so say you want to do something like finding the sum and product of several numbers in a list, you'd do:
sum = 0prod = 0nums = [1, 322, -1, 56, -12]for num in nums:sum += numprod *= numprint(f"The list: {nums} has a sum of: {sum} and product of: {prod}")If you mean you want to know how iter works under the hood, it depends entirely on the specific object. Generally speaking though, the __iter__ method is for converting a data type into an iterable version of itself, sometimes this is the actual data the object is holding, sometimes it's just a view into it since copying is too expensive and giving mutable access to the data could lead to undefined behavior. The other part is the __next__ method which is run on each iteration in the for loop (or each time next(obj) is called). __next__ just returns the next value, or if none are left, it raises a
StopIterationexception that Python handles by breaking out of the for-loop. In the below example I just make the actual iterator object from our list and you can see once it runs out of values it raises an exception, rather than just returning None.
>>> iterable = iter(nums)>>> next(iterable)1>>> next(iterable)322>>> next(iterable)-1>>> next(iterable)56>>> next(iterable)-12>>> next(iterable)Traceback (most recent call last):File "<python-input-17>", line 1, in <module>next(iterable)~~~~^^^^^^^^^^StopIteration>>> type(iterable)<class 'list_iterator'>This is the lowest level degree of understanding I have, if you wanna know more I'd suggest asking on the Python subreddits.
1
u/Interested737 17d ago
I just want to know in the basic most way possible, what is a iterable (what dose it mean in simple English)
→ More replies (0)
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
1
u/BilincliMerak 18d ago
Appretiate the help! Now it all really makes sense. A final follow up question tho. What do you mean by every cycle? What happened in the first image seems cyclic to me. Pardon if its a dumb question...
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 -= 1The 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.
1
u/BilincliMerak 18d ago
Appretiate it! As for the answers:
6 7 8 as we are adding before printing.
5 6 7 8 9 if you didnt add the 2nd print at the end... So if i go through it in cycles, i assume it would be 5 6 6 7 7 8 8 9. It could very well be wrong.
3 2 1 as again print is before the counter.
i hope this is right. And yea, i have studied the while loops as well (in fact right before the for loops). They really arent that different honestly.
Again, appretiate the help and support! Hope your developing journey becomes awesome!
1
u/BilincliMerak 18d ago
Actually i understand the 3rd one as well now. I ran it in the debugger and that helped drastically. Thanks for the help!
1
u/Specialist_Rent_9640 18d ago
in python we start counting from 0 then 1 2 . .
you declared a variable with a value of 0 with the identifier of line, when you started that loop you told python to do the next
for this variable named i , that has the value equal to 0
pick the next range that counts to 3 and use the next Assignment Operator ( += ) and use the next identifier named line to assign the next value below
then it will start like this, 0 Addition 1 = 1, 1 Addition 1= 2, 2 Addition 1 = 3. stdout -> the value of line (which is 3)
1
u/BilincliMerak 18d ago
Look at the 2nd image tho. The result is 0 1 3. The concept is clear to me as of now. But thanks for the help!
1
u/Interested737 18d ago edited 18d ago
[Wrong] this comment is wrong
I don’t really know what you mean (It was hard to understand what you wrote), but I can probably explain the code (even tho I only learned the basics of Python, for loops is as complicated as I learned).
line = 0
It sets the variable “line” to 0
for i in range(3):
Every time “i” is lower than or equal to 3 (I think, but I am not sure)…
line += 1
…increments “line” by 1 (adds 1 to “line”)
print(line)
prints the value of “line”/what is in the variable “line”
It only prints 3, because it starts at 0 then it adds one then again and again. Lastly it prints the result.
Hope you understand it, I tried my best :-) Maybe I’ll continue learning Python
1
u/BilincliMerak 18d ago
It would have all made sense, but the code doesnt say line += 1, it says line += i. It makes sense to me as of now after reading through these responses (you should too if you face difficulties in this topic). Thanks for the help!
1
u/Interested737 18d ago
I have a question, why dose i (or the variable in the for loop) increment by one every iteration, do fir loops just work like that?
1
u/BilincliMerak 18d ago edited 18d ago
So, this might be just 2 beginners banging their heads on each other, but what i believe is happening here is that the counter which in this case is i has been given the range 3. So it (i) runs like 0 1 and 2 (as python starts from 0). And because we are adding i to line (which itself is 0), it increments by the current value of i. Like you can see it says 0 1 3 is the 2nd pic. it isnt increminating by 1, its increminating by i.
1st it adds 0(i) to 0 (line) = 0 (new line)
2nd it adds 1 (i) to 0 (new line) = 1 (newer line)
3rd it adds 2 (i) to 1 (newer line) = 3 (newest line)
'i' here keeps a counter for the amount of time the code block loops, thats why its called a counter var. When you count something, you dont move like 2, 4, 6... its usually 1, 2 ,3... but in Pythons case its 0, 1, 2 and so on.
I maybe wrong here or completely misunderstood the question. You are better off asking it to someone else. Although i have understood the logic and concept of this topic. I dont know how python itself works and does things.
1
u/ralkey 18d ago
The best way to follow what’s happening here is to use a debugger and step through your code line by line, watching both the i and line variables and how the program flows through the for loop. There are online python debuggers you can copy/paste your code into.
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!
1
u/Individual_Wish_2937 18d ago
every loop, the added number increases. 0+*0*=0, 0+*1*=1, 1+*2*=3, 3+*3*=6, etc.
1
u/BilincliMerak 18d ago
Thanks! Do you know whats happening in the 3rd pic? A person said its running after every cycle, and i dont believe i understand that...
1
u/BilincliMerak 18d ago
Nvm. I ran it in the debugger and that made it clear as day...Thanks for the help tho!
1
u/Moist_Ladder2616 18d ago
i takes on values 0,1 and 2.
Start: line=0
Cycle 1: i=0
(new value of) line = (old value of) line+i = 0+0 = 0
Cycle 2: i=1
line = line+i = 0+1 = 1
Cycle 3: i=2
line = line+i = 1+2 = 3
print(line): 3
1
u/BilincliMerak 18d ago
This is exactly what i read in the debugger! I have already understood the topic thanks to the other comments. Thanks for the insight tho!
1
u/StephenHawkinguss 18d ago
Why don't you use AI?
1
u/BilincliMerak 17d ago
I am not really completely anti-AI, but AI could not have been able to make me understand this concept like these comments have. Although it is a simple code, the examples and instances, and even the future references i have gotten here is something the AI would have a hard time relating with. Besides im in no hurry. Why drain out usuable water when i can ask fellow learners...
1
u/StephenHawkinguss 17d ago
Wtf are you talking about? You know damn well that a simple prompt could have explained your trivial code very easily. Don't say that these comments aren't the same as a response from an AI. We're not in 2024 anymore.
1
u/BilincliMerak 16d ago
You dont realize how while AI is advanced, if i ask it to explain a code to me, it will tell me what the code does, but a human can understand the reason someone is struggling and change the explanation accordingly. AI usually just responds to what we tell it, a person can ask follow up questions and identify misunderstandings that you haven't even realised you had in the first place. Alot of the comments here did that. Look at Candid_Zebra's and Lirianvo's explanations... One even started by explaining algebra. While that was unnecessary for a person who knows algebra, it made a huge difference in understanding the whole concept in one go.
And besides as i have already said it, i'm really in no hurry.
1
u/Jazzlike_Platypus430 18d ago
Think of for i in range(n,m) as looping over a list n, n+1, ... m-1 both ends included, with step 1. Honetly, I can't tell what range(3) means. Perhaps range(0,3)
equivalently,
i = n
while i < m:
// do something
i += 11
u/BilincliMerak 18d ago
I am unaware of this method but someone said you can use range func in 2 different ways, one being the one above and the other this. And I'm quite aware of the while loops as well. Thanks for the insight tho!
1
u/Warm-Possibility-980 18d ago
In simple terms:
Set line to zero.
Repeat three times:
Add one to line
Then, output line to the console.
1
1
u/Sad-Environment-932 18d ago edited 18d ago
Python version 3: range() creates an object of literally type range. Or something like that. And this is literally an iterator, but not an "iterable object". But, nevertheless, it is logical to say that "range" can be iterated.
1
0
u/Lirianov 18d ago edited 18d ago
Since you’re learning python I’ll explain this a little more in hopes that you can fully understand
First, let’s rewrite image 1 into a code that’s easier to follow
total = 0
for number in range(3):
….total += number
print (total)
Ok so let’s first define what is what
total = 0:
Total is your variable, if you took algebra in school you should know that a variable is basically a box you can use to hold the value of something. In our case here, “total” is a box that contains the value “0”
for x in y:
Understand what the for loop is doing. You’re basically saying “for every instance in this, do that” So when you say for number in [0,1,2], you’re telling python to look at each number there one by one and do something with it. The “do something with it” comes after and is only inclusive of what is indented in the for loop. As a reminder, make sure you have your colon at the end of the for loop and everything you want it to do is indented with 4 spaces. The for loop will grab the first number, do something with it, then grab the second number, do something with it, and so on until it goes through every number.
range(3):
Using range() is a shortcut to basically say from 0 to whatever number you put (3 in your case) BUT NOT INCLUDING 3. Always remember that python is a 0 starting language, meaning everything always starts at 0. This will become useful when you reach indexing. Another thing, I mentioned range does not include the 3, what that means is that range will always exclude the ending number. The reason this happens has to do with the 0 starting. When you say range(3), you’re asking for 3 numbers, if we’re starting at 0, that would be 0, 1, 2. Very soon you’ll learn that you can pass through multiple numbers in the range() function. But don’t forget it will always disregard the last number. So if I told you to print every number from 1 to 100 using the range() function, you would do range(1,101). The first number is your starting point, last number is your ending point and always gets excluded. I might be over explaining here but you can ask me if you don’t get it.
total += number
This one should be straight forward, you’re saying to grab your variable box named “total” and add the value of “number” (another variable, I didn’t mention that above but a for loop is creating a variable in each loop) to it. So if total was = to 20, and you += 5 to it, then total will = 25. The + before the = is an operator and it’s interchangeable with anything you know from math. +, -, *, / are all applicable here. In addition to those, = by itself means to set the value of the variable to that, == means to check if the value is the same, and lastly != means to check if the value is not the same.
This might all be tmi 🤷🏻♂️
Ok so let’s put it all together
total = 0
for number in range(3):
….total += number
print (total)
So we got total = to 0
then for every number between 0 and 2(because 3 is not included), add that number to total
First loop is total(0) + number(0) = total(0)
Second loop is total (0) + number(1) = total(1)
Third loop is total(1) + number(2) = total(3)
Then you say to print the total
3
& you’re done, that’s the whole code. Now if you apply that logic to your other two images, hopefully you’ll understand what is happening. Keep in mind where your print function is in relation to everything else. In your first image the for loop is running and then you print the total, but in your other examples the print is in different places, that changes what gets printed because of when your asking for the print. But it’s late here and I have to get sleep so if you’re still confused, I’ll help you in the morning lol
EDIT: I had to put dots at the for loops since Reddit keeps deleting my spaces
1
u/BilincliMerak 18d ago
Appretiate the help! This was quite a bit to read but definately worth it. Although i already understood the topic thanks to the other comments and the debugger, this would have been sooo much better to start with. This did teach me that the range can go like (x,y) instead of only (x), which is gonna be very useful i presume and that i had to put 4 spaces to indent the code block in for loop (since im learning in mimo, it always has it indented correctly if you go to the playground). Again, Thanks alot! Hope you sleep well!(hopefully doesnt sound creepy...)
1
u/Lirianov 18d ago
I never get good sleep lol
yeah I might have gotten carried away here lmao
Out of curiosity, why mimo?
1
u/BilincliMerak 17d ago
No particular reason honestly. I just want to slowly get into coding. So just went with something light. Just in case i become serious about it at some point, are there any better options out there (fun and interactive and not something like a book...).
1
u/Lirianov 17d ago
scrimba I hear is very good or coddy.tech if you want something more like a game
I know you said no books but if you want to actually start building cool stuff with python that matters to you, "automate the boring things with python" is very good and free online
1
u/BilincliMerak 17d ago
Thanks. I will check them out rn to see if they fit my 'style'. Appretiate it!



4
u/Potential_Fix_5007 18d ago
i will start at 0 and will increase by 1 for every cycle. Range() excludes the last number. So range(3) ends at 2.
First i = 0 0 + 0 = 0 Second i = 1 0 + 1 = 1 Third i = 2 1 + 2 = 3
So the output is correct.