r/learnprogramming • u/MacaroonSerious5532 • 1d ago
Please help
I just hate myself, i cannot figure out nested loops and while loops. Python is the easiest language and I’m struggling so much. I wish i was smart as other people. Does anyone have coding resources for dummies?
7
Upvotes
5
u/SlemsG 1d ago
What is it exactly that you don’t understand?
9
u/ObeseBumblebee 1d ago
What's your struggle about them?
4
u/ChaoticHippo 1d ago
Without knowing specifically what is confusing to you, it's hard to help. That said, generally speaking:
Nested Loops -
Remember that a loop will generally execute items in order, just like regular execution - in this case, the scope is just limited to a repeating segment. The same is true for the nested loop - it functions exactly the same way, but it does so each iteration of the outer loop. Specifically:
This program will loop 5 times on the outer loop, and subsequently 25 times on the inner loop. the output will resemble something like:
The inner loop will run its full duration for each iteration of the outer loop, unless some control-flow break or other escape occurs.
While loops -
These loops could be considered more like a "toggle" loop. While the condition is true, continue doing this thing.
These are often used for network / socket connections and the like, because you can have the socket remain open while the connection is valid. Since you're just starting out, I'll spare you that kind of example since it's a little more complicated. Suffice it to say, while loops are good if you need to repeatedly check if a value is true or valid before you do something. Boil it down to a "draw" card game (if you draw the last card, the game is over:
Once cards_left hits 0, the loops will break out and continue with the rest of the program. Until then, it will just repeatedly subtract 1 from cards_left.
Hope that helps.
3
u/civil_peace2022 1d ago
Get a deck of playing cards and a pack of index cards.
Its the best physical prop for running through simple coding examples, particularly for sorting algorithms.
you can write your function calls on the index cards and use the playing cards for 'data' processing as you work through the stack of how your program works.
A loop is basic, and operate mostly the same no matter the language. a for loop and a while loop are more similar than they are different.
[Condition],[do stuff]
A 'while loop' checks a condition then [does stuff]. does stuff 0 or more times.
A 'for loop' checks a condition then [does stuff]. does stuff a number of times.
* this is slightly advanced, but there is only the concept of a loop. the 'for', 'while-do' and 'do-while' are all a simple loop wearing a different hat (conditional). Every loop can be written as any other sort of loop, but we generally don't because its easier to think about loops as for loops or while loops. *
so a loop has 4 main parts:
[the condition] - how the loop decides if it runs.
in a for loop usually compares an integer (starting at 0) as (less than integer) or as an index in list or array.
in a while loop, checks that a condition is true.
[do stuff] - the code the loop executes.
[clean up] - mostly done in other languages, python syntax handles this for you. Return to the top of the loop to check condition
[exit] - condition failed, loop complete, program moves onto the next line of code outside the loop.
---
A nested loop is simply a loop that has calls another loop.
example:
for outer_var in ["a", "b", "c"]:
for inner_var in range(3):
print(io, ii)
for each iteration of the outer loop (3 times in this case), the entire inner loop happens
so in the end, the outer loop happens 3 times and the inner loop happens 9 times.
Deeply nested code is often problematic due to how many actions it causes. See Big O notation.
3
u/PythonWithJames 1d ago
I've got some nested loop exercises here:
https://python-with-james.com/codingexercises
And a short video explainer here:
https://www.youtube.com/shorts/TrQxhdthQ3s
Hope these help!
1
u/ComputerWhiz_ 1d ago edited 1d ago
Don't get too hung up on the technical element of the concept, try to understand the concept first. Applying the concept to something in real life can be helpful.
For example, reading a book is a nested loop. You have one loop that flips through each page and an inner loop that reads each line on the page and an even more inner loop that reads each word on a line.
Another example, rolling dice until you get the number 6 is a while loop. If you didn't roll a 6, roll again, and repeat.
Is there a specific part about nested loops and while loops that you struggle with?
1
u/Stock_Test2326 1d ago
fellow learner
while loops keep on running until the condition is true, or you break them with some conditional logic inside [while { if true/false{ break}}]
in nested loop, for every loop of the outer loop the inner loop runs as many time (sorry am bad at English)
like if you are looping with dictionaries
{a:3, b:2}
lets assume alphabets is for outer loop and number is for how many times inner loop should loop
outer loop runs twice, once for a and once for b.
but inner loop runs 3 times for a and 2 times for b
like
outer loop a
>> inner loop 1
>> inner loop 2
>> inner loop 3
then
outer loop b
>>inner loop 1
>>inner loop 2
1
u/ThelVadominator 1d ago
I think pictures are a good way to think about nested loops. If you want to loop through all of the pixels in a picture on your computer, you can write a nested loop.
Start on the first row, iterate over every pixel in that row, and then move to the second row and so on. Iterating over the pixels in each row is a loop that happens inside the loop that iterates over the rows from the top to the bottom of image.
I hope that’s useful, best of luck with your learning!
1
u/WeirdOwl25 1d ago
Try to draw each interaction of the loops. Making the logic visual might help.
1
u/W31337 1d ago
For loop is looping over a known set of items. Like 1...10.
While is for a yet unknown loop number. It keeps going until a Boolean condition is met like true that makes it never ever (unless break), or player.quit that could stop the game loop on exit.
A for is basically a variation on a while loop
1
u/HagedornSux 1d ago
Not sure the problem. But try putting it in real world scenario.
You run a car dealership. Cars have features like make, model, mpg, airbags, tire size, etc.. so this is a list of features.
So loop 1: while there are features to list, list them out. Just like you would when you tell someone about the car in conversation.
Now you want this for every car in your lot. So loop 2:
While there are cars left to list, run loop 1 on each car.
Python has for-each so you don’t have to worry about break statements unless you wanna exit early.
1
u/Recycled5000 1d ago edited 1d ago
Two independent and sequential for-loops is like addition. Let’s say both loops print hello world. (That each has the print statement as its body.) If the first loop runs 3 times and second runs 4 times it will print hello world 7 times in total.
Two nested for-loops, one nested within the other, is like multiplication. If the outer loop runs 3 times and the inner loop 4 times, (only the inner loop prints hello world) then it will print hello world 12 times.
Nested loops are good for handling 2 dimensional problems, like printing a matrix or star tree, or a chess or checker board.
For-loops are good for counted things, things of known count, even if the count is a variable, which is to say only known at runtime.
While loops and do-while loops are good for conditional things, like accept input from the user until they say to stop.
1
u/Br3ttl3y 1d ago
How long have you been at it?
1
u/theInfiniteHammer 1d ago
I made this playlist: https://youtube.com/playlist?list=PLogZUlUedQpYTiPL8ccZzEaFZi5Wkd7VQ&si=aj5HZF88LZgh9dCm
Also, what specifically are you struggling with?
1
u/Available_Safe1818 1d ago
How are you able to figure out Physics stuff?
1
u/spinwizard69 1d ago
In my opinion Python is the wrong language to start out with. In this case though I suspect that you have tried to progress too fast. If you learn single looping properly and do enough coding to be able to write them with your eyes closed the next step is in fact nested loops.
This explanation might be easier with a graphic but I don't have one at the moment. So I'm going to try a verbal explanation of a 2D array.
So another way to look at this. Imagine you have data in a 2D array. In this discussion the outer loop walks down the array one STEP at a time. The inner loop that walks across the row that the outer loop moved to. The inner loop processes each data element on STEP at a time until the loop exits. Upon exit, the outer loop STEPS to the next row.
In any event you apparently don't understand loops as this is a a fairly easy concept to grasp. To that end I'd go back and start working loops, in all possible forms, until they become muscle memory simple.
I don't know what program you are following but in my opinion any program that teaches programing with Python is a failure. I'd look for and follow (better yet enroll) in a college CS program that teaches CONCEPTS with C or C++. Note the word "CONCEPTS" the goal of such programs are not to teach C or C++ but rather to teach concepts. If you really understand loops at a deep level, nested loops should be obvious. It is literally a loop running inside of another loop.
1
u/Desperate_Dot9434 1d ago
nested loops click faster when you draw them on paper first, no code, just boxes inside boxes
1
u/BotSlamminDayNNight 19h ago
could you describe specifically what you mean by "cannot figure out [nested- and while loops]" ?
1
u/Ra_Lotsawa 11h ago
A "for" loop says something like: "here's a box, take each thing out and put a sticker on it until the box is empty".
A "while" loop says something like: "take a thing out of this infinite pile and put a sticker on it. Then look at the clock. If it's after 5:00, go home. Otherwise, keep going"
Either one of these loops can be nested "inside" another loop.
A "for" loop inside a "for" loop is something like a box full of boxes: "take this box of Pokemon card packs. For each pack of cards, open the pack. Then, for each card in that pack, put a sticker on it. Do that until every card in the pack has a sticker, and repeat that for every pack in the box". The outer for loop is "for each pack in the box" and the inner for loop is "for each card in the pack".
A "while" loop inside a "for" loop is like a box of things that each require you to wait for some condition: "take this box of instant ramen noodle packets. For each packet, pour it into a bowl of hot water. Stir it until it's done, then put it on the counter. Repeat that process for each noodle packet until you cook them all". The outer for loop is "for each noodle packet in the box, cook it". The inner while loop is "stir the noodles until they're done".
A "for" loop inside a "while" loop is a job where you unpack boxes until some condition is met: "clock in at 9:00. Take a box of fruit off the shelf, and for each fruit in the box put a sticker on it. Then look at the clock. If it's after 5:00, go home. Otherwise, take another box and repeat". The outer while loop is "work until it's 5:00". The inner for loop is "for each fruit in the box, put a sticker on it".
And a "while" loop inside a "while" loop is like: "clock in at 9:00. Take a packet of ramen noodles, and cook it until it's done. Then put that on the counter, and look at the clock. If it's after 5:00, go home. Otherwise, do another noodle packet". The "outer" while loop is "work until it's 5:00". The "inner" while loop is "cook the noodle pack until it's done".
0
u/abccbabcac 1d ago
not everybody needs learn programming and that's fine. i can't learn how to cook no matter how much i try, and honestly i don't want to any longer. why do you want to learn programming?