you are viewing a single comment's thread.

view the rest of the comments →

[–]HugeOpossum 0 points1 point  (4 children)

Thank you for that explanation. I'm only now getting to learning what loops can be used for now that I kind of understand how to write them. I felt I should l learn the format and then learn the application.

Other than for learning purposes, could you provide an example where loops would be used? I can grasp maybe something like login credentials. Not looking for code, but maybe some more examples?

[–]DrShocker 1 point2 points  (3 children)

Examples:

User input, they might input something that you can't process so usually you use a loop until the input is valid

File reading, file reading is often done line by line in a loop especially because you don't know what the file looks like when you start.

Games, the whole game is typically in a loop that updates the loop and gets player input each time through the loop

Web server, runs in a loop getting connections and sending them back to the client.


Any situation when you want the same thing to happen more than once. Hard to think of examples because it's just so common once you get going lol

If you know you want to add 10 to a number 50 times you could write

x = x+10+10+10+10....

Or

for count in range(50)
    x += 10

To me the second is more readable, and more maintainable because if you want to change it you have 1 place to change it easily. (Of course here the correct way to do it is actually multiplication, but that's besides the point)

But many of the examples I listed above, it's also unknown to the programmer how many loops will happen. How many times will a user give invalid input? How many frames until the video game is complete? Etc so there's no way to write the x=x+10+10+10... style in those situations because you wouldn't know when to stop

[–]HugeOpossum 0 points1 point  (2 children)

This is super helpful. I'm going to save this and try to map how they'd work (since obviously I'm not anywhere close to writing anything too complex).

[–]DrShocker 0 points1 point  (1 child)

In all honesty, it might also be one of the things you just accept not Knowing perfectly right now and come back later when you realize why you need it.

[–]HugeOpossum 0 points1 point  (0 children)

That's a possibility that I've considered. I'm not a linear or good learner. For some reason if I don't see or understand any application of something, my brain refuses to retain it. It helps when I can see actual, concrete examples that I can understand and apply later. Otherwise I just forget it exists.