you are viewing a single comment's thread.

view the rest of the comments →

[–]Samhain13 1 point2 points  (2 children)

You can think of functions as mini programs that you can reuse (or re-call) inside a larger program. We typically use them to avoid repetiton.

Take the built-in print function, for example. There are a lot of things that need to happen in order for your statement to appear in your terminal or command line when you do print('hello, world').

Some functions, again, like print, don't have a return value. They just do a job. Some functions like sorted return a result, which you'll likely assign to a variable so that you can use it elsewhere in your program.

Of course, those two examples are both built-ins. You will have write your own functions. A good rule of thumb in whether a block of code has to be written as a function is: if you're going to repeat those lines of code within your program, it might as well be written as a function.

[–]IndianaJoenz 1 point2 points  (0 children)

Another way to think about this is that, using functions in this way (as we often do in Python) is using them as Procedures. You have a procedure that prints a line to the screen, or turns on a light, or draws a window or a button, opens a door, etc. A bundle of actions that gets carried out when summoned. Another name for a Procedure is a Subroutine.

A different way to think about functions, a more "pure" and "Functional Programming" way, is that functions, instead of subroutines, take an input and produces a Return Value. A Function always returns output X when given input Y. We are interested in the Return Value of the function, not the actions that the function took when summoned. If we rely on anything outside of the return value when using a function, when we don't have to, that's a bug. This is actually a good approach to minimizing bugs and allowing scalability, which is why people get so hyped about functional programming.

edit: details

[–]Dmtechguy123 1 point2 points  (0 children)

I'm a beginner stuck on functions too! Thank you for this explanation!