On way to understand functions, is to go back to basic mathematics.
Consider the mathematical expression :
f(x) = x + 2
In this case, the f(x) will add 2 to the value of x.
therefore, f(0) = 0 + 2 , gives 2.
Similarly for other values of x.
when x = 3....f(3) = 5
when x = 5....f(5) = 7
Thus, for an input value of x, it will produce an output which is the evaluation of the expression x + 2.
In python, this expression will be something like this :
def f(x): # here x is the input value
output = x + 2 #calculates the expression using x
return(x+2) #and we return the value
suppose we want to find the value for x = 3. this will be : f(3)
f(3) will now give you 5 as above.
We can save this value in another variable ,
y =f(3)
Here y saves the value returned by our function when you pass 3 to it. Thus y will be 5.
In your example,
def secret_formula(started): #here we have **started** instead of x
jelly_beans = started * 500 #bunch of calculations
jars = jelly_beans / 1000
crates = jars / 100
return jelly_beans, jars, crates #returns the calculated value
Below that,
start_point = 10000
beans, jars, crates = secret_formula(start_point) #what will the output be , if I give 1000 to secret_formula .. ie... secret_formula(1000)
Now secret_formula function returns three outputs
return jelly_beans, jars, crates
We are assigning these outputs to beans, jars, crates in the respective order.
Now beans will have the value that jelly_beans has, so on...
So what happened to jelly_beans? To put it crudely, variables which are used within a function are only available within itself. Consider them as intermediate values which are discarded once used. Do read upon scope and scope rules.
The function will return some values which we now store in other variables.
Functions can be very useful when you have to do something repeatedly. Instead of rewriting the same code again and again, you can just call the function.
Consider this, random scenario :
def printNow():
print("Hiwatsup, blah blah blah ")
#some insane calculations
print("Hiwatsup, blah blah blah ")
#more random things.
Now, whenever you want to do all these things , you just need to put printNow().
You don't have to retype all of it!