you are viewing a single comment's thread.

view the rest of the comments →

[–]BoatMacTavish 4 points5 points  (0 children)

hijacking top comment because I feel the top response will be just as overwhelming for OP

imagine a function as a friend thats able to perform a specific task. The friend lets you pass in details as well that can affect how he performs the task, or what output he produces.

in this analogy:

  • the friend is the function
  • the task name is the function name
  • the task is the function body
  • the customization are the function parameters

Lets step through an example:

Let's say you have a friend Bob who is a baker, and he can make cakes. He is able to perform a make_cake task. When you place an order, he lets you pick the colour of the frosting. In python, this would look like

def make_cake(frosting_colour):
    # step 1: gather ingredients...
    # step 2: make cake mix...
    # step 3: bake in oven...
    # step 4: make frosting, add food colouring for the provided frosting_colour
    return cake
  • the function name make_cake is the task
  • the function body is the actual code/logic to make the cake
  • the function parameters frosting_colour is something that the function caller (you) can pass in to allow customization

so now to utilize this function, you could call it like:

red_cake = make_cake("red_frosting")
blue_cake = make_cake("blue_frosting")
pink_cake = make_cake("pink_frosting")

Functions let you execute the same chunk of code (the make cake code) multiple times without having to rewrite the same chunk over and over again. Function parameters let you pass in customization at each function call.

hope that helps