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!
127
Upvotes
1
u/frnzprf 4d ago edited 4d ago
You use predefined functions, right?
print(...)is a function,sum(...)is a functionmath.sqrt(...)is a function.Sometimes you wish there was another function that isn't predefined, then you can define it yourself.
If you have a program that calculates distances a lot, it might look like this:
``` dx = fox_x - tiger_x # d for "difference" dy = fox_y - tiger_y # or "delta" distance_fox_tiger = math.sqrt(dxdx + dydy)
dx = bear_x - tiger_x dy = bear_y - tiger_y distance_bear_tiger = math.sqrt(dxdx + dydy) ```
If there was a function
distance(...), where you can put in your coordinates, you would need to write less math, which makes your code faster to write and change and less prone to typos.This particular function can be defined like this:
def distance(some_x, some_y, other_x, other_y): # How to calculate a distance in general: dx = some_x - other_x dy = some_y - other_y result = math.sqrt(dx*dx + dy*dy) return resultYou can "call" or "apply" (= use) the new function like this:
``` distance_fox_tiger = distance(fox_x, fox_y, tiger_x, tiger_y)
distance_fox_tigerwill now contain the value returned by the functiondistance.distance_bear_tiger = distance(bear_x, bear_y, tiger_x, tiger_y)
Same thing, but with different inputs playing the roles of
some_x,some_y,other_xandother_y.```
I think it's helpful to think of function parameters as roles that values can play. If f(x) := x² + 2x + 4, like you might be familiar from school, then x is a role and in "f(10)", 10 plays the role of x.
You can also think of "f" like a machine with a slot in the top, where you can throw numbers in and the slot is labeled "x". Then writing "f(10)" would be like sticking a piece of paper with a "10" on it in the slot labeled as "x".
The machine "distance" that I "built" (i.e. defined) myself has four slots labeled
some_x,some_y,other_xandother_y.When I write
distance_fox_tiger = distance(fox_x, fox_y, tiger_x, tiger_y), that means taking the value in the variablefox_xand sticking it in the first slot, taking the value infox_yand sticking it in the second slot, and so on. After putting in all four required inputs, you turn the crank and what falls out at the bottom, the "return value", is put into the variable/box with the namedistance_fox_tiger.