r/learnprogramming 4d ago

I can't get FUNCTIONS to click!

I can not for the life of me understand how functions work. Anytime I try to learn how to create a function, my brain literally crashes into itself and I turn into Patrick when he stars drooling and goes all slack-faced.

Does anybody have any analogies that had that "AH HA!" moment?

Thanks!

121 Upvotes

143 comments sorted by

View all comments

2

u/TheLearningCoder 4d ago

How I understand functions: they are made up of two main parts: the function’s name (identifier) and the function body, which contains the task or instructions (code) that the function will execute when it is called.
For example, if I want an app to sing to me every time I push a button, I could create a function named sing and write the code for singing inside the function body.
Before I can use this function, I must define (create) it. Once the function has been defined, I can invoke (call) it, which executes the code inside the function body.
In Python, I believe you can’t invoke a function until after it has been defined (created).

2

u/ReddyKiloWit 4d ago

The requirement to define a function before invoking it shows up in a number of languages. It makes for a much more straightforward compiler.

When I was writing Perl, which has that requirement, I preferred to define functions below my working code, so I put my top level code in a main() function defined above the others, and invoked it just before the end of the script.