Newbie Question

January 14, 2020

I didn’t answer at Reddit. If I did, I would write something like this:

A loop encloses a block of code that is executed repeatedly until some condition becomes true. A function is called with one or more parameters and returns a result based on the parameters; it’s purpose is to hide the code that computes the result, so that the programmer doesn’t need to consider that code when calling the function.

Your question is very basic. Instead of trying to learn programming on your own, I recommend you find a teacher who can help you get past the lowest rungs of the learning curve, where it is steepest.

Pages: 1 2

2 Responses to “Newbie Question”

  1. Zack said

    Both are useful programming structures, independent of each other. The loop ensures that several commands are executed until a certain condition is met (e.g. iterate over all the elements of a list, one by one, until one is found that is equal to a predefined value). The function is something more general as it can undertake a specific task when needed. You may call a function just once, but in another case call it several times. A loop can contain a function in it, in which case the function will potentially be executed several times. Also, a function can contain a loop in it, if the task it undertakes requires it. Hopefully, all this clarifies how the two programming structures are different, even if they sometimes involve repeated computations.

  2. Daniel said

    Functions are often created so that 1) various other parts of a program can utilize similar functionality, or 2) to factor out logic so that it is self-contained.

    Loops are often used to repeat the same pattern of computations consecutively.

    The ideas are similar because they both reduce code duplication. That is, the code in a function could alternatively be repeated throughout a program, rather than calling the function directly. Similarly, the pattern of code in a loop can be repeated sequentially, as opposed to using a loop. However, this type of duplication could make a program more difficult to read and maintain.

    A difference between functions and loops is that the computations within a function can be utilized be various code spread throughout a program (by calling the function), whereas the code within a loop is intended to be run during the loop’s execution (and can’t be called elsewhere).

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: