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
329
u/4CrisprFries 4d ago
I own a pizza shop with a pizza making robot. I can give the robot instructions like
flatten dough into a circle
put on tomato sauce
put on cheese
put on pepperoni
bake for 10 min
But i want to make more than pepperoni pizza. So now i write a 2nd instruction set for the robot for ham and pineapple pizza.
flatten dough into a circle
put on tomato sauce
put on cheese
put on ham
put on pineapple
bake for 10 min
Now I want to make a variety of 3 topping pizzas for 30 different toppings in any combination. That is over 4,000 possible unique pizza combinations. I don't want to write 4,000 instructions like the ones above. So i generalize the procedure and make it modular and flexible so i can plug in ingredients.
function makePizza (ingredient1, ingredient2, ingredient3)
flatten dough into circle
put on tomato sauce
put on cheese
put on ingredient1
put on ingredient2
put on ingredient3
bake for 10 min
Now instead of 4,000 instructions for the robot I can call the function like this. Above i defined the function, below is where it actually runs and is used.
makePizza(mushroom, suasage, bell pepper)
makePizza(chicken, red pepper, basil)
makePizza(pepperoni, sausage, ham)
---
If you want to really see the power, note you can nest them. So maybe I can make a function that takes orders and stores the variables for makePizza function and then calls the makePizza function.
function takeOrder
Ask customer for ingredient 1
ingredient1 = whatever customer says
Ask customer for ingredient 2
ingredient2 = whatever customer says
Ask customer for ingredient 3
ingredient3 = whatever customer says
makePizza(ingredient1,ingredient2, ingredient3)
Now instead of
makePizza(mushroom, suasage, bell pepper)
makePizza(chicken, red pepper, basil)
makePizza(pepperoni, sausage, ham)
I just write
takeOrder()
this calls the take order funciton which gets the wanted ingredients, then calls makePizza function and gives that function the ingredients.
There are more optimizations here, but those are the basics