Functions, when to use?

Hello, i make (beginning), python programs, and if i look to the solution:
sometimes they are using functions (even when it’s not an excercice about functions, and sometimes not .

Is there some logic into this , when using functions ?
(I know the purpose , to brake down into smaller pieces, to do tasks, etc etc etc …).
But i cannot find a line, when to use a function, and when not .

(And if you make excercices : let’s be real : the most part of then when you are a beginner,are not large programs. And that’s i am strugling : when do i use a function, when not …)

I wonder if someone could give me some advice about this topic …

Thanks in advance !

There might not be easy answer for this question.

If it’s some short script, without any clear code repeating, and when code is unlikely to be reused elsewhere, then function is not necessary.

In any other case using function can be convenient either for keeping code structured and simpler. Or required, if there’s need to allow importing code to another file.

For example, having simple script:

"""something.py"""


# code doing something
(...)
print(result)
  • python something.py in terminal will execute all code.
  • Using in another python file import something, will execute all code on import.

At some point it might be needed to allow importing it from other modules. For that putting code in the function is required to not execute everything on import.

"""something.py"""

def do_something():
    # code doing something
    (...)
    print(result)
  • python something.py will not do anything without explicit call to function. Adding simple do_something() at the end of file brings us back to previous case, executing everything on import.
  • Using in another python file import something, will not execute all code on import.

There’s way to allow for both using code as a script and to import it from another module:

"""something.py"""


def do_something():
    # code doing something
    (...)

if __name__ == '__main__':
    print(do_something())
  • When running python something.py from terminal __name__ variable will be __main__, so code in the if block will be executed .
  • Using in another python file import something, will not execute code on import, as in such case __name__ will not be __main__.

can we say that ,as soon we start to use a “for loop” or a “while loop”, it’s a better practice to use functions - for the statements in the for or while loop ?

Not really, there’s no such relation.

Not really a Python user but there is also the variables scope to consider. A function can serve as a scope for the variables. So even if you do not need the organization or code reuse, you might still want some variables to not be global.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.