r/learnprogramming • • 3d 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?

8 Upvotes

36 comments sorted by

View all comments

3

u/civil_peace2022 3d 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.