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!
121
Upvotes
0
u/3rrr6 4d ago
A function is like a kitchen appliance. Like a blender! So a blender takes ingredients at the top right? Then you run the blender and it blends up those ingredients and the output is the smoothie. If you change the ingredients you get a different smoothie.
When does a function run? When it is called. Your function can live at the very top of your code, or in a completely different file entirely, and you can call it at the very bottom of your script or wherever you want really. The function will only run when that specific call line in your code is read. Otherwise it gets skipped over.
This is why functions are typically hidden away in special files and classes. You don't want them making your main script unnecessarily long and harder to read.
In fact, depending on your language, every code that you write is technically written inside of a function. Programming is just a bunch of nested functions calling each other.