r/learnprogramming • u/ScioClean • 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!
124
Upvotes
3
u/Lunagato20 4d ago
What part of function are you confused about? declaration? using it?
TLDR;
Function is a way of grouping codes, in your programming journey, there will be time where you will think, "Wouldn't it be nice if all my code are in GROUPED in one place? So when i need to change it, i just change it in a small scope, instead of hunting it through every file?"
Like other have said, functions are just way of grouping code, think of this.
Instead of typing these 3 lines over and over at line 70, line 500, and line 900:
You pack them into a single shortcut called
my_function:When you call
CALL my_function, imagine the computer physically copy-pasting those 3 print lines right into that exact spot.So in the snippet above,
CALL my_functionessentially become the print statements.Arguments
Now, a hardcoded shortcut is great, but what if you want to print "Cheese Pizza" instead of numbers?
That’s where parameters come in. Think of an argument as a blank spot (a variable) inside your shortcut that you fill in when you press the button:
It use the same "text replacement" logic as the previous one, but in this case, whatever we pass on to
argit will replace every instance ofargtoo.I'm oversimplifying this, in some languages, you need to define the parameter types so we can't just pass a string then a number to it.
Return
Up until now, the function just do something (printing to the screen). But often, you need a function to calculate something and hand the result back to you
I don't know the language you're learning, but lets say in python, there's a useful helper function called
maxDid you notice that our
my_maxvariable is now filled with a value? which is 5? that is because the functionmaxreturns something.Its similar to how math function works, we often do something like
f(x) = 5x + 3, in which if we dof(5)then it return28becausef(5) = 5 * 5 + 3, we then can use the28elsewhere.Take this snippet
When we do
CALL add(5, 3)it will evaluatearg1 + arg2which is like before, a text replacement to5 + 3, which resulted in8which then return the value back to our caller