r/learnprogramming • • 22h 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

34 comments sorted by

5

u/SlemsG 21h ago

What is it exactly that you don’t understand?

-9

u/MacaroonSerious5532 21h ago

Mostly everything i misunderstand except print()🤣

8

u/TheTomato2 18h ago

You aren't even trying, that is your problem.

3

u/snaidamast 20h ago

All a nested-loop is multiple "for' statements or "while" statements nested within each other.

Example (pseudo code)...

...for x = 0; x++; x<10

......for y=0; y++;y<10

......next y

...next x

2

u/SlemsG 10h ago

This has to be engagement bait lol

1

u/gm310509 4h ago

What happens if you set up a for loop that say counts from one to ten using the variable "i" as the counter.

In the loop, print the value of "i".

Now put that for loop (the one with i) inside another loop that also counts from 1 to 10 using "j" as the counter. Print j alongside of i in your print statement.

Study the output looking to see if you can see any patterns.

8

u/ObeseBumblebee 22h ago

What's your struggle about them?

4

u/ChaoticHippo 21h 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:

values = ["a", "b", "c", "d", "e"]
res = ""
for i in range(5): # This runs 5 iterations, with i = 0, 1, 2, 3, 4
  print(i) # Prints the value of i.
  for j in range(5): # Also runs 5 iterations, with j = 0, 1, 2, 3, 4
    res = res + values[j] # appends the item in values at j to res, so a, b, c, d, e
  print(res)

This program will loop 5 times on the outer loop, and subsequently 25 times on the inner loop. the output will resemble something like:

0
abcde
1
abcdeabcde
2
abcdeabcdeabcde
3
abcdeabcdeabcdeabcde
4
abcdeabcdeabcdeabcdeabcde

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.

while(true):
  # Do the thing forever, this is an infinite loop.
  # You would stop these by using a break statement, or other program exit status

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:

cards_left = 52
while(cards_left > 0):
  cards_left = cards_left - 1

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 19h 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_ 21h ago edited 21h 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/MacaroonSerious5532 21h ago

I struggle with reading and interpreting what the code does

3

u/lurgi 21h ago

Type it into a computer. Put print statements into the code that show the value of useful variables.

1

u/GarThor_TMK 9h ago

And then set breakpoints and step through what the program is doing slowly.

2

u/EliSka93 21h ago

I think most people do for a while.

I know I used to.

The more you practice, the more that feeling goes away.

Don't let it discourage you, it does get better.

2

u/PythonWithJames 6h 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!

2

u/PythonWithJames 5h ago edited 3h ago • Heartwarming

I also sort of think it as:

A single for loop is like taking a shopping list (cheese, ham. tomato), and then saying:

For each item in that list:
Go and find it!!

--------

A nested one is like saying:

For each item in that list:
For each letter in that item:
Shout it!

EDIT: Thanks for award <3

1

u/Stock_Test2326 21h 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 21h 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 21h ago

Try to draw each interaction of the loops. Making the logic visual might help.

1

u/W31337 21h 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 21h 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 20h ago edited 20h 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 19h ago

How long have you been at it?

1

u/theInfiniteHammer 19h ago

I made this playlist: https://youtube.com/playlist?list=PLogZUlUedQpYTiPL8ccZzEaFZi5Wkd7VQ&si=aj5HZF88LZgh9dCm

Also, what specifically are you struggling with?

1

u/Available_Safe1818 10h ago

How are you able to figure out Physics stuff?

1

u/spinwizard69 9h 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.

  1. Think of a single loop as STEPPING through X number of instructions repeatedly.
  2. Lets call each run through the loop a STEP. If the loop is working on an array, it might get one piece of data from the array and process it in some manner. However in a 2D structure the outer loop, simply has a inner loop to be processed.
  3. So each STEP of the outer loop causes the inner loop to run.
  4. When the inner loop runs out, execution reverts to the outer loop.
  5. The outer loop then STEPS to the next array of data and the process repeats.

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 4h ago

nested loops click faster when you draw them on paper first, no code, just boxes inside boxes

0

u/abccbabcac 20h 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?

1

u/MacaroonSerious5532 20h ago

I want to major in physics which requires coding

2

u/abccbabcac 20h ago

you'll just need to outsource the coding to someone else while you take care of the maths and algorithms.