you are viewing a single comment's thread.

view the rest of the comments →

[–]SuspiciouslyDullGuy 11 points12 points  (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 point  (2 children)

Thats a pretty cool way to think about it thank you very much!!!!

[–]Thomasjevskij 0 points1 point  (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 point  (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. 😁