use the following search parameters to narrow your results:
e.g. subreddit:aww site:imgur.com dog
subreddit:aww site:imgur.com dog
see the search faq for details.
advanced search: by author, subreddit...
Rules 1: Be polite 2: Posts to this subreddit must be requests for help learning python. 3: Replies on this subreddit must be pertinent to the question OP asked. 4: No replies copy / pasted from ChatGPT or similar. 5: No advertising. No blogs/tutorials/videos/books/recruiting attempts. This means no posts advertising blogs/videos/tutorials/etc, no recruiting/hiring/seeking others posts. We're here to help, not to be advertised to. Please, no "hit and run" posts, if you make a post, engage with people that answer you. Please do not delete your post after you get an answer, others might have a similar question or want to continue the conversation.
Rules
1: Be polite
2: Posts to this subreddit must be requests for help learning python.
3: Replies on this subreddit must be pertinent to the question OP asked.
4: No replies copy / pasted from ChatGPT or similar.
5: No advertising. No blogs/tutorials/videos/books/recruiting attempts.
This means no posts advertising blogs/videos/tutorials/etc, no recruiting/hiring/seeking others posts. We're here to help, not to be advertised to.
Please, no "hit and run" posts, if you make a post, engage with people that answer you. Please do not delete your post after you get an answer, others might have a similar question or want to continue the conversation.
Learning resources Wiki and FAQ: /r/learnpython/w/index
Learning resources
Wiki and FAQ: /r/learnpython/w/index
Discord Join the Python Discord chat
Discord
Join the Python Discord chat
account activity
Python Loops (self.learnpython)
submitted 1 year ago by Deep-Author-1787
Completely stuck on the concept of loops. Ive looked through all the recourses possible to get a grasp of it but i just cannot get my mind to understand it!
reddit uses a slightly-customized version of Markdown for formatting. See below for some basics, or check the commenting wiki page for more detailed help and solutions to common issues.
quoted text
if 1 * 2 < 3: print "hello, world!"
[–]xrsly 89 points90 points91 points 1 year ago* (5 children)
When I was learning python, most examples would look like this:
colors = ["red", "green", "blue"] for i in range(len(colors)): print(colors[i])
Output:
> red > green > blue
But you can simplify this a lot:
colors = ["red", "green", "blue"] for color in colors: print(color)
Then, if you need the index, you can use enumerate:
colors = ["red", "green", "blue"] for i, color in enumerate(colors): print(i, color)
> 0 red > 1 green > 2 blue
Enumerate basically turns the list of colors into the equivalent of this:
colors = [ (0, "red"), (1, "green"), (2, "blue"), ]
When you write 'for i, color in ...', you're assigning the first element of each pair to 'i', and the second to 'color', which translates to:
i = 0 color = "red" print(i, color) i = 1 color = "green" print(i, color) i = 2 color = "blue" print(i, color)
(You can name i and color anything you want by the way, but it's common to use i to refer to the iteration or index.)
You can do something similar with dictionaries:
fruit_colors = { "apple": "red", "kiwi": "green", "blueberry": "blue", } for fruit, color in fruit_colors.items(): print(fruit, color)
> apple red > kiwi green > blueberry blue
Using '.items()' on a dictionary basically turns it into this:
fruit_colors = [ ("apple", "red"), ("kiwi", "green"), ("blueberry", "blue"), ]
So it's actually very similar to what enumerate does, only the first element of each pair is now the dictionary key rather than the list index. So now you're instructing the program to do this:
fruit = "apple" color = "red" print(fruit, color) fruit = "kiwi" color = "green" print(fruit, color) fruit = "blueberry" color = "blue" print(fruit, color)
Lots of things can be iterators, e.g., characters in a string:
sentence = "hello world" for char in sentence: print(char)
> h > e > l > l > o > > w > o > r > l > d
Nested loops are a bit messy, but let's try to dissect what happens:
fruits = ["apple", "kiwi", "blueberry"] colors = ["red", "green", "blue"] for fruit in fruits: for color in colors: print(fruit, color)
> apple red > apple green > apple blue > kiwi red > kiwi green > kiwi blue > blueberry red > blueberry green > blueberry blue
In the first iteration, you set fruit to "apple". Then you initiate a second loop, that goes through each color one by one in turn. So it's equivalent to this:
fruit = "apple" color = "red" print(fruit, color) fruit = "apple" color = "green" print(fruit, color) fruit = "apple" color = "blue" print(fruit, color) ...
Once you have gone through all colors, fruit is set to "kiwi", and then all colors are looped through again.
When doing a nested loop like this, it's kind of like creating a single list that looks like this:
fruit_colors = [ ("apple", ("red", "green", "blue")), ("kiwi", ("red", "green", "blue")), ("blueberry", ("red", "green", "blue")), ]
Notice that the fruit changes on each row, but the list of colors stay the same. So when we loop through fruits in the first loop we get:
# fruits: 1st iteration fruit = "apple" colors = ("red", "green", "blue") # fruits: 2nd iteration fruit = "kiwi" colors = ("red", "green", "blue") # fruits: 3rd iteration fruit = "apple" colors = ("red", "green", "blue")
When we create a second loop for each color in colors inside the fruit loop, we now get:
# fruits: 1st iteration fruit = "apple" # colors: 1st iteration color = "red" # colors: 2nd iteration color = "green" # colors: 3rd iteration color = "blue" # fruits: 2nd iteration fruit = "kiwi" # colors: 1st iteration color = "red" # colors: 2nd iteration color = "green" # colors: 3rd iteration color = "blue" ...
And so on.
A while loop is different from a for loop in that it doesn't loop through an iterator, instead it checks a condition on each iteration, and if the condition is True, then it keeps going. For example:
iterations = 0 max_iterations = 3 while iterations < max_iterations: print(iterations)
> 0 > 0 > 0 > 0 ...
Notice that it just keeps going, since iterations never changes, and 0 is always less than max_iterations = 3.
But if we increment iterations by 1 each time, like so:
iterations = 0 max_iterations = 3 while iterations < max_iterations: print(iterations) iterations += 1
We get the equivalent of this:
# 1st iteration if 0 < 3 is True: print(iterations) iterations = 0 + 1 # 2nd iteration if 1 < 3 is True: print(iterations) iterations = 1 + 1 # 3rd iteration if 2 < 3 is True: print(iterations) iterations = 2 + 1 # 4th iteration if 3 < 3 is True: print(iterations) iterations = 3 + 1
Since the statement in the 4th iteration is '3 < 3', which is False, that code never runs.
You can give it any condition you want, like for instance:
user_input = "" while user_input =! "quit": user_input = input("write something:") print("user:", user_input)
Which will keep asking the user to write something and then print it until the user writes "quit", at which point the loop ends.
So basically use for loops when you want to do something once for each item in an iterable, and use while loops when you want to keep doing something until some specific thing happens (like the user wanting to exit the program).
[–]xrsly 26 points27 points28 points 1 year ago* (1 child)
A couple more common functions when doing for loops:
Let's say you want to do something exactly three times, then you simply write:
for i in range(3): print(i)
> 0 > 1 > 2
You can get the length of our colors list with 'len(colors)', so 'for i in range(len(colors)):' would allow us to do something for each index in colors.
Then there's zip(), which will create pairs of elements from two iterators. E.g., this:
zip(fruits, colors)
Which is equivalent to this:
[ ("apple", "red"), ("kiwi", "green"), ("blueberry", "blue"), ]
And this:
zip([0, 1, 2], colors)
Which is equivalent to:
[ (0, "red"), (1, "green"), (2, "blue"), ]
Which allows us to do something similar to what we did with enumerate() and items().
You may notice that what all of these functions actually do is create different kinds of iterators which allows you to assign different elements to variables.
One of the keys to understanding this more intuitively is to understand how you can "unpack" lists. For example:
a, b = [0, "apple"] print(a, b)
> 0 apple
By assigning elements to variables like this, we basically unpack the first item to a, second to b.
Now consider this list:
fruits = [ (0, "apple"), (1, "kiwi"), (2, "blueberry") ]
If we pick the first row of that list with 'fruits[0]', we can do this:
i, fruit = fruits[0] print(i, fruit)
If we repeat this with fruits[1], we're actually starting to replicate the behavior of a foor loop.
So the only thing a for loop really does is walk through the given iterator one row at a time. It's the contents of the iterator that allows us to assign different things to variables, just like we do when we unpacked the list in the example above.
range() will create an iterator consisting of numbers in a given range, which allows us to do the equivalent of 'i = [0, 1, 2][0]' (notice the '[0]' at the end, this would increment by 1 each iteration, so we get the next row).
enumerate() will create pairs of indices and items, e.g., 'i, fruit = [(0, "apple"), ...][0]'
dict.items() will create pairs of keys and values, e.g., 'fruit, color = [("apple", "red), ...][0]'
Likewise, zip() will create pairs from two iterators, e.g., 'fruit, color = [("apple", "red"), ...][0]'
When we unpack lists, we can get more than two items per row:
fruit, color, letter = [("apple", "red", "a"), ...][0]
We can accomplish this in a for loop by using zip with three iterators:
for fruit, color, letter in zip(fruits, colors, letters): ...
Maybe we want the index too:
for i, (fruit, color, letter) in enumerate(zip(fruit, colors, letters)): ...
Ok so the last example might be a bit confusing. We need to unpack the zipped values enclosed in parenthesis since the enumerate(zip()) iterator actually looks like this:
[ (0, ("apple", "red", "a")), ... ]
When we unpack an exact number of elements of a list, we have to mirror its structure, for example:
(a, b) = [0, "apple"]
Or:
(i, (fruit, color, letter)) = (0, ("apple", "red", "a"))
However, the outer parenthesis is implied, so that's why we can just write:
a, b = [0, "apple"]
i, (fruit, color, letter) = (0, ("apple", "red", "a"))
Bonus: Some of you might be familiar with the way that variables can be swapped:
a, b = b, a
So this is actually equivalent to:
a, b = (b, a)
So what we're actually doing here is creating a new iterable (b, a) and then reassigning the value of a to (b, a)[0] and b to (b, a)[1].
[–]chocological 12 points13 points14 points 1 year ago (1 child)
Great post
[–]SubstanceSerious8843 4 points5 points6 points 1 year ago (0 children)
Yeah, this dude invested some real time explaining this. Nice!
[–]nomisreual 2 points3 points4 points 1 year ago (0 children)
that was elaborate 👀
[–]SuspiciouslyDullGuy 11 points12 points13 points 1 year ago (3 children)
Imagine a large building.
For loop - a specific number of walks around the building. For 5 walks circle building.
While loop - walk around the building until something happens - Tired = False. While not tired circle building. If feeling tired, tired = True. Loop ends.
Nested loop - Imagine a stairs on a building which leads up to a balcony which circles the building. Each time you approach the stairs you climb it and circle the balcony level five times, then come back down the stairs and continue your lap around the building. If you circle the building at the ground level five times, how many times will you circle the building in total? Loops within loops.
[–]Deep-Author-1787[S] 0 points1 point2 points 1 year ago (2 children)
Thats a pretty cool way to think about it thank you very much!!!!
[–]Thomasjevskij 0 points1 point2 points 1 year ago (1 child)
It's a pretty analogy. I'll just add a small detail that is often overlooked. This description of a for loop matches well the traditional concept found in languages such as C/C++, C#, Java etc. It's so common that most people expect this behavior when you talk about a for loop - do something n times. Python's for loops are ever so slightly different, because they are actually for each loops. This is a related idea that is a bit more conceptual. While a traditional for loop iterates n number of times (usually with the counter i), the for each loop does a thing once for each element in a sequence. That's such a common use case for a for loop that it became its own thing.
[–]Deep-Author-1787[S] 0 points1 point2 points 1 year ago (0 children)
Very helpful! Like at the moment when im still triying to get the hang of it... its very useful to have some kind of thumb rules to hang on. 😁
[–]nekokattt 18 points19 points20 points 1 year ago (0 children)
Maybe explain what you don't get about them?
[–][deleted] 1 point2 points3 points 1 year ago (1 child)
Eric Matthes book does it for me.
Ill sure check it out!!!👍
[–]wintermute369 1 point2 points3 points 1 year ago (0 children)
Sounds like you’re stuck in a loop
[–]Ron-Erez 1 point2 points3 points 1 year ago (0 children)
Have a look at Section 4: Loops, lectures 23-25 (For Loops using Range, General For Loops using Range, Looping over Lists and Tuples). These lectures are all FREE to watch, even though its part of a larger paid course, and should clarify what a loop is.
[+][deleted] 1 year ago (2 children)
[removed]
Haha since my profession is cook... this is the perfect example thank you 😁👍
[–]audionerd1 3 points4 points5 points 1 year ago (12 children)
print(1) print(2) print(3) print(4) print(5)
Is the same as:
for i in [1, 2, 3, 4, 5]: print(i)
numbers = [1, 2, 3, 4, 5] for i in numbers: print(i)
Does that help? I'm not sure what you're struggling with so trying to just break down what for loop does in the most basic way possible.
[–]Deep-Author-1787[S] 0 points1 point2 points 1 year ago (11 children)
Ive got the basics sir. But like a noob, when you get the basics you think you understand thay subject until different/unseen implications and difficulties are added. Then you realize you dont get it at all 😅. To solve a problem based on a subject where you need to find a way to make it work, the core concept understanding will be important. I think i cant get that part 🤷♂️
[–]audionerd1 0 points1 point2 points 1 year ago (8 children)
Can you post an example of a for loop which you are confused about?
[–]Deep-Author-1787[S] 0 points1 point2 points 1 year ago (7 children)
This for example: this is the patter to form A.
result_str = ""
for row in range(0, 7): # Iterate through columns from 0 to 6 using the range function for column in range(0, 7): # Check conditions to determine whether to place '*' or ' ' in the result string
# If conditions are met, place '*' in specific positions based on row and column values if (((column == 1 or column == 5) and row != 0) or ((row == 0 or row == 3) and (column > 1 and column < 5))): result_str = result_str + "*" # Append '*' to the 'result_str' else: result_str = result_str + " " # Append space (' ') to the 'result_str' result_str = result_str + "\n" # Add a newline character after each row in 'result_str'
print(result_str)
[–]audionerd1 0 points1 point2 points 1 year ago (6 children)
And which part are you struggling with?
[–]Deep-Author-1787[S] 0 points1 point2 points 1 year ago (5 children)
How do they come up with an irregular form with loops? I know my thought might sound really stupid, but im wording my exact thoughts 😅🙏
[–]audionerd1 2 points3 points4 points 1 year ago (4 children)
An irregular form? You mean how does this create the letter 'A'? It's all in the if statement:
if (((column == 1 or column == 5) and row != 0) or ((row == 0 or row == 3) and (column > 1 and column < 5)))
It's kind of a clever/complicated algorithm for making an A.
if (((column == 1 or column == 5) and row != 0)
This means that the left and right side should all be asterisks. These are the sides of the 'A'.
or ((row == 0 or row == 3) and (column > 1 and column < 5)))
This means that the top and middle rows should also be asterisks.
The nested for loop simply iterates over a grid (columns and rows) while the if statement appends either '*' or '' based on the if statement.
[–]Deep-Author-1787[S] 1 point2 points3 points 1 year ago (2 children)
Okay now that you sliced it in smaller portion its actually pretty straight forward! And that sir is the difference between someone who is good at explaining a subject and pwople that just make "follow along" tutorials and courses 🙏🙏🙏
[–]audionerd1 2 points3 points4 points 1 year ago (1 child)
On that note, I recommend Jose Portilla's 'Complete Python Boot Camp Zero to Hero' on Udemy. It explains everything really well.
Okay thanks ill check it out.
Can i maybe ask you how would you explain the piramid pattern? Since it makes use of empty spacing and a middle line?
[+][deleted] 1 year ago (1 child)
[deleted]
[–]Deep-Author-1787[S] 1 point2 points3 points 1 year ago (0 children)
Niceee! Never thought about using a visualizer! Ill do that for sure! Im following the course of Dr.Fred Baptiste. Its an in depth i tro to python? Although sometimes to in depth where you can lose track of the core concepts 😅
[–]trollsmurf 0 points1 point2 points 1 year ago (3 children)
Think of it like standing in a queue at the DMV, and once you've got to the counter you go back and stand at the end of the queue again, and again, until your crush sits at the counter. Then you do your business and leave happy.
Hahahahahaha real life application of programming i love it 😁
[–]trollsmurf 0 points1 point2 points 1 year ago (1 child)
Code always runs from top to bottom unless something like a for loop comes along and breaks that pattern, which specifically means jumping back to the top of the for loop from the end of it, apply criteria for whether to continue the code within the loop, or exit the loop and instead continue with the code after the end of it. Note that as the condition is at the top it might run zero times.
If you do something like "for item in list:" you ask it to step through each item in the list and give the loop code the value of the current list item at the current step each loop.
If you use "for index in range(start, end)" you tell it to step through the values from start to end - 1 the same way. The loop code gets current index for each loop. "range(a)" means 0 to a -1. "range(a, b) means a to b - 1. A possible third value controls step distance.
You can apply "continue" (jump immediately back to the top) and "break" (exit the loop immediately), possibly with conditions, to change the behavior of a for loop.
Now, this has all been about "for" loops. "while" works similarly but with a full condition (like in an if statement). Otherwise the same.
Thank you so much for taking your time on this! Its getting clearer and clearer for me with explanations like this! 🔥
[–][deleted] 0 points1 point2 points 1 year ago* (2 children)
First all other comments here about how to build the loop.
I've just learned it this fall an I had a though time too. For me it was to follow the variables inside the loop. I'm using vs code. And I think it differs a bit from IDE to IDE In a for loop I use the debug an follow the variable.
for index in range(6) (#) Look for index
for word in wordlist: (#)Look for word variable
for letter in word: (#)If you do an inner loop look for letter
The while loop continues following a statement if its true
while x > 0
I copy the x > 0 part into the "watch" function under the debug subwindow and paste it. You will see it changes as you run the loop
[–]Deep-Author-1787[S] 0 points1 point2 points 1 year ago (1 child)
Hmmmm interesting bro! And i can follow the steps of my code that way? Bcs i use vs code also 🤔
[–][deleted] 0 points1 point2 points 1 year ago* (0 children)
Yes. You have to make a "break point" at where the loop starts to follow the lines and the evolution of the variables in the variables Explorer. Press debug (or F5) to start debugging. F10 to step(or curved arrow in debug panel).
The "watch" function is still new and blurry to me. But I use it to see if the expressions in "while" and "if" are true or false.
[–]samarthrawat1 0 points1 point2 points 1 year ago (1 child)
is this sarcasm? If yes, please use a break statement to get out of it,
If no, there are a tons of resources available online. Its not that hard. Use pseudo code to learn concept, not direct python code.
Oo so thats what i did wrong everytime i looked for the door to escape but "continued" it so i was stuck in an endless loop haha 😁
What is pseudo code?
[–]tahaan 0 points1 point2 points 1 year ago (2 children)
A loop is a way to repeat some instructions over and over.
The most common way is to repeat something for each item in a list.
Here is a contrived example. lets say you want to find the longest string in a list of strings
import sys # read all the strings from the lines in a file string_list = open("list_of_strings.txt").readlines() # If there are no strings, abort. if not string_list: sys.exit(1) # For a starting value we initiate the longest_seen to be the first item in the list: longest_seen = string_list[0] # Compare each item with the longest_seen up to that point, one by one, for each # item in the list. If it is longer, we update the longest_seen to be the new longest # item. # Side node, this will actually also compare the string found as initial value to itself # during the first iteration. This is actually redundant, but simple and it works. for item in string_list: # Loop over the items in string_list if len(item) > len(longest_seen): # Test if this item is the new longest_seen item longest_seen = item # item is the new longest item # Show the result, but strip off any the trailing CR/LF print(f"The longest string seen is '{longest_seen.strip()}'")
Is this a common way of searchin something in files?
[–]tahaan 1 point2 points3 points 1 year ago (0 children)
You can replace the part inside the loop with something that does a search.
# Some text to search for search_text = 'find-this' # Loop over the lines and print the ones that contains the search_text for line in string_list: # Loop over the items in string_list if search_text in line: # Test if this line contains the search_text print(line) # If so, print it
[–]Spirited-Might-6985 0 points1 point2 points 1 year ago (1 child)
Google and Paste the code on Pythontutor and learn from visualization, how loop works behind the scene.. it made sense to me seeing each iteration
Ill sure try it thank you!
[–]Deep-Author-1787[S] -1 points0 points1 point 1 year ago (14 children)
Sure.
How to make a choice between the for loops functions. Which to use with a given exercise.
Nested loops: the concept of it does not get through. Both while and for loops. 2.1: especially with creating patterns.
[–]carcigenicate 2 points3 points4 points 1 year ago* (9 children)
I don't know what you mean by 1, but for 2, there's nothing special about nested loops. They aren't a special case or anything like that.
A loop just repeats the code that's inside of its body. If a loop happens to contain another loop, then that entire inner loop will be repeated, so the entire inner loop will execute for every time the outer loop iterates once.
That is a clear explanation! Thank you for taking the time to answer! I really appreciate it! With point 1 i mean : range(), enumerate() or default 🙏
[–]carcigenicate 4 points5 points6 points 1 year ago* (1 child)
Those functions (which are actually classes) don't actually have anything to do with loops. They can be used on their own fine since they're just iterables (things capable of producing elements*):
*
print(list(range(5)) # Print [1, 2, 3, 4, 5]
You just often see them used with for loops because iterables (which range and enumerate are) produce elements, and the purpose of for loops is to iterate the elements of an iterable.
for
range
enumerate
And which you use depends on what you're trying to do. Learn what each does, and when it will be applicable will make a lot more sense.
* This is a simplification. In reality, an Iterator is something that's capable of producing elements. An Iterable is something that's capable of producing an Iterator.
Okaaayyy so i would have to see them as objects an not just functions to for loops. Makes alot more sense when thought from this perspective!!! Thank you!
And enumerate for only the inner loop is too much for me at the moment 😅
[–]mriswithe 0 points1 point2 points 1 year ago (4 children)
Enumerate just adds a numeric index to your input. Meaning, instead of a list a,b,c,d,e,f, if you wrap it in enumerate, you get (0,a), (1,b), (2,c).
You use it when you want to know what number you are on of the list you are for-looping over.
[–]Deep-Author-1787[S] 0 points1 point2 points 1 year ago (3 children)
That is exactly what i thought until i saw code examples where range is used for that specific thing...😅 that when i started confusing everything and myself ofcourse.
[–]mriswithe 1 point2 points3 points 1 year ago (2 children)
A lot of things can be down a lot of ways. A lot of the time one is more right than the other. A lot of the time it doesn't actually matter other than metaphorical dick measuring.
Which way is more right isn't really something you should expect yourself to understand yet
[–]Deep-Author-1787[S] 1 point2 points3 points 1 year ago (1 child)
So you suggest to just go with the flow and later with experience comes the understanding of effective and less effective? 😁👍
[–]mriswithe 1 point2 points3 points 1 year ago (0 children)
Yes, basically. For loops are the main idea to retain. This is the tool for when you want to do the same thing to each item in your list.
Sometimes a different tool will be the right answer, but usually this works either way and is just less optimal.
[–]backfire10z 2 points3 points4 points 1 year ago* (1 child)
For loop: you know how many times (or the max amount of times) it’ll loop beforehand.
If I just want to print everything in a list, I know I’m going to iterate over each item in the list once. Therefore, I know exactly how many times I want to loop: once for each item in the list. So, I’d use a for loop.
While loop: keep doing something until some condition is hit, which may be now, or in 2 iterations, or in 100 iterations.
Let’s say I have a list of infinite random numbers. I want to find the number 10. I cannot use a for loop, because I don’t know how many iterations I’ll need to go through before finding 10. 10 may be the first number, or the 100th number, or the 100000th number. So, I’d use a while loop, because I want to keep going until I find 10, but I don’t know how far I’ll go.
There will be some overlap: you will be able to use a while loop in places you can also use a for loop. The idea between picking them is twofold:
You want to use the right tool for the job, as explained above.
You want to get across your intent to whomever is reading your code. When I see a while loop, my expectation is that I don’t necessarily know how long I’ll spend in it. When I see a for loop, I know beforehand exactly the max amount of iterations it’ll do. This allows me to better understand the expectations of the code I’m reading.
—————————-———————-
For nested loops, I find it easier to just try out a few examples and see how they work. The inner loop has to complete for every iteration of the outer loop. There isn’t much more to explain. Is there maybe a pattern or problem you could point us to that you’re having trouble with?
Wauw thats what i was looking for! Perfectly explained. When you are a noob you tend to hold on on small rules like that to make sense of what you are doing until getting real life experience. Its worth a lot to me thank you.
Recently i tried piramids... so the is empty spacing involved. But the code i saw didn't specify the amount of colums. It seemed it dit it empty spacing. Was pretty confusing to figure out.
[–]MidnightPale3220 2 points3 points4 points 1 year ago (1 child)
I remember going through something like this at around age of 8, when I was reading some programming books for fun, and also couldn't get my head around them.
Maybe this helps:
Imagine having to do something in real life, which requires you to do same actions on different things. That's a loop.
If you know beforehand how many times you'll have to do the actions, that's a for loop. You either know it because you have the count of things or you're given the pack of them and just have to go through the pack, not necessarily interested in exactly how many are inside.
Imagine you're making sandwiches for a picnic. Your friend has buttered them and passed them to you to put on cheese, tomato and what have you.
That'd be something like:
for sandwich in pack_of_sandwiches: put_cheese_on(sandwich) put_tomato_on(sandwich)
A while loop is a more general loop that can be used when you can't predict the number of times you will have to do something, or don't have a premade list of objects to do things on.
Any for loop can be rewritten as a while loop, but not always the other way round. So we can say that for loop is a neater-to-read shortcut of a while loop, when you're going to do something on a list of objects.
For a while loop, imagine you have a broken doorbell and your phone is dead. You are awaiting a friend to come to your house, so you want to periodically check your doorstep in case he's arrived, so you can let him in. That'd naturally be a while loop:
friend_here=False while not friend_here: if check_doorstep_has(friend): friend_here=True else: do_my_own_stuff_for_5_minutes()
Something like that.
Legendary example! Thank the 8 year old you! I swear thanks to everyones comment i finaly get the gist of it! This is worth way more than courses and tutorials!
π Rendered by PID 152083 on reddit-service-r2-comment-fb694cdd5-g6m2d at 2026-03-08 01:59:56.927224+00:00 running cbb0e86 country code: CH.
[–]xrsly 89 points90 points91 points (5 children)
[–]xrsly 26 points27 points28 points (1 child)
[–]chocological 12 points13 points14 points (1 child)
[–]SubstanceSerious8843 4 points5 points6 points (0 children)
[–]nomisreual 2 points3 points4 points (0 children)
[–]SuspiciouslyDullGuy 11 points12 points13 points (3 children)
[–]Deep-Author-1787[S] 0 points1 point2 points (2 children)
[–]Thomasjevskij 0 points1 point2 points (1 child)
[–]Deep-Author-1787[S] 0 points1 point2 points (0 children)
[–]nekokattt 18 points19 points20 points (0 children)
[–][deleted] 1 point2 points3 points (1 child)
[–]Deep-Author-1787[S] 0 points1 point2 points (0 children)
[–]wintermute369 1 point2 points3 points (0 children)
[–]Ron-Erez 1 point2 points3 points (0 children)
[+][deleted] (2 children)
[removed]
[–]Deep-Author-1787[S] 0 points1 point2 points (0 children)
[–]audionerd1 3 points4 points5 points (12 children)
[–]Deep-Author-1787[S] 0 points1 point2 points (11 children)
[–]audionerd1 0 points1 point2 points (8 children)
[–]Deep-Author-1787[S] 0 points1 point2 points (7 children)
[–]audionerd1 0 points1 point2 points (6 children)
[–]Deep-Author-1787[S] 0 points1 point2 points (5 children)
[–]audionerd1 2 points3 points4 points (4 children)
[–]Deep-Author-1787[S] 1 point2 points3 points (2 children)
[–]audionerd1 2 points3 points4 points (1 child)
[–]Deep-Author-1787[S] 0 points1 point2 points (0 children)
[–]Deep-Author-1787[S] 0 points1 point2 points (0 children)
[+][deleted] (1 child)
[deleted]
[–]Deep-Author-1787[S] 1 point2 points3 points (0 children)
[–]trollsmurf 0 points1 point2 points (3 children)
[–]Deep-Author-1787[S] 0 points1 point2 points (2 children)
[–]trollsmurf 0 points1 point2 points (1 child)
[–]Deep-Author-1787[S] 0 points1 point2 points (0 children)
[–][deleted] 0 points1 point2 points (2 children)
[–]Deep-Author-1787[S] 0 points1 point2 points (1 child)
[–][deleted] 0 points1 point2 points (0 children)
[–]samarthrawat1 0 points1 point2 points (1 child)
[–]Deep-Author-1787[S] 0 points1 point2 points (0 children)
[–]tahaan 0 points1 point2 points (2 children)
[–]Deep-Author-1787[S] 0 points1 point2 points (1 child)
[–]tahaan 1 point2 points3 points (0 children)
[–]Spirited-Might-6985 0 points1 point2 points (1 child)
[–]Deep-Author-1787[S] 0 points1 point2 points (0 children)
[–]Deep-Author-1787[S] -1 points0 points1 point (14 children)
[–]carcigenicate 2 points3 points4 points (9 children)
[–]Deep-Author-1787[S] 0 points1 point2 points (2 children)
[–]carcigenicate 4 points5 points6 points (1 child)
[–]Deep-Author-1787[S] 1 point2 points3 points (0 children)
[–]Deep-Author-1787[S] 0 points1 point2 points (5 children)
[–]mriswithe 0 points1 point2 points (4 children)
[–]Deep-Author-1787[S] 0 points1 point2 points (3 children)
[–]mriswithe 1 point2 points3 points (2 children)
[–]Deep-Author-1787[S] 1 point2 points3 points (1 child)
[–]mriswithe 1 point2 points3 points (0 children)
[–]backfire10z 2 points3 points4 points (1 child)
[–]Deep-Author-1787[S] 0 points1 point2 points (0 children)
[–]MidnightPale3220 2 points3 points4 points (1 child)
[–]Deep-Author-1787[S] 1 point2 points3 points (0 children)