Difference between defining a function and simply writing a for loop

Hello, I’d be grateful if someone could explain the difference between defining a function and simply writing a for loop.

This is my answer:

love_maybe_lines_stripped = []

for lines in love_maybe_lines:
  love_maybe_lines_stripped.append(lines.strip())

I didn’t think to use a function. How am I supposed to know when to write a function and when to just write a for loop?

Also, I initially wrote the code with the empty list inside the loop, but it didn’t work. Why does the empty list have to be outside of the loop?

Sorry for the long post. Thanks in advance.

Functions are code blocks that are written so that they could be used whenever they required in program. Functions do a particular operation and if you are doing any program in which some lines of code will needed to be written multiple times so better to wrap those code blocks in a function and call that function whenever required. Loops are code blocks which you’ll have to write each time for similar operations if you don’t wrap them in function. Functions are like tools/machinery or say mathematical formula in which you give input and take output. These are my views as far as I’ve known functions. Hope it helps.

It follows the D. R. Y. principle to write functions that do all the heavy lifting in a program. Functions abstract away procedures that are repetitive in a program. More than that, they are abstracts of code patterns.

Say we have several instances where we need a product? The pattern that is repeating in our code is a * b. If we write that pattern in a function, then every time a reader sees our function, they will know what pattern is being evaluated.

 def mul(a, b): return a * b

When the reader sees,

 y = mul(6, 7)

they see, y = 42.

1 Like

yeah exactly…Don’t Repeat Yourself (DRY) principle. Btw I was not knowing about this principle, thank you for acknowledge me. I guess your rest lines are same as I describe in words above.