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 …
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.
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.
python something.py will not do anything without explicit call to function. Adding simpledo_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:
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 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.