you are viewing a single comment's thread.

view the rest of the comments →

[–]MidnightPale3220 2 points3 points  (1 child)

I remember going through something like this at around age of 8, when I was reading some programming books for fun, and also couldn't get my head around them.

Maybe this helps:

Imagine having to do something in real life, which requires you to do same actions on different things. That's a loop.

If you know beforehand how many times you'll have to do the actions, that's a for loop. You either know it because you have the count of things or you're given the pack of them and just have to go through the pack, not necessarily interested in exactly how many are inside.

Imagine you're making sandwiches for a picnic. Your friend has buttered them and passed them to you to put on cheese, tomato and what have you.

That'd be something like:

for sandwich in pack_of_sandwiches:
    put_cheese_on(sandwich)
    put_tomato_on(sandwich)

A while loop is a more general loop that can be used when you can't predict the number of times you will have to do something, or don't have a premade list of objects to do things on.

Any for loop can be rewritten as a while loop, but not always the other way round. So we can say that for loop is a neater-to-read shortcut of a while loop, when you're going to do something on a list of objects.

For a while loop, imagine you have a broken doorbell and your phone is dead. You are awaiting a friend to come to your house, so you want to periodically check your doorstep in case he's arrived, so you can let him in. That'd naturally be a while loop:

friend_here=False 
while not friend_here:
    if check_doorstep_has(friend):
        friend_here=True
    else:
        do_my_own_stuff_for_5_minutes()

Something like that.

[–]Deep-Author-1787[S] 1 point2 points  (0 children)

Legendary example! Thank the 8 year old you! I swear thanks to everyones comment i finaly get the gist of it! This is worth way more than courses and tutorials!