r/learnprogramming • u/MacaroonSerious5532 • 20h 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 20h ago
What is it exactly that you don’t understand?
8
u/ObeseBumblebee 20h ago
What's your struggle about them?
4
u/ChaoticHippo 20h 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 18h 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.
1
u/ComputerWhiz_ 20h ago edited 20h 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?
2
u/PythonWithJames 4h 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/Stock_Test2326 20h 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 20h 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 20h ago
Try to draw each interaction of the loops. Making the logic visual might help.
1
u/W31337 20h 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 19h 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 19h ago edited 19h 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 18h ago
How long have you been at it?
1
u/theInfiniteHammer 17h ago
I made this playlist: https://youtube.com/playlist?list=PLogZUlUedQpYTiPL8ccZzEaFZi5Wkd7VQ&si=aj5HZF88LZgh9dCm
Also, what specifically are you struggling with?
1
u/Available_Safe1818 9h ago
How are you able to figure out Physics stuff?
1
u/spinwizard69 8h 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 3h ago
nested loops click faster when you draw them on paper first, no code, just boxes inside boxes
0
u/abccbabcac 19h 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?