Skip to content

Purpose of Functions

  • Lesson
  • 2 min read
  • 1 of 4 in this chapter

What is a function?

A function is a named part of your code that carries out a specific task or set of tasks. A function is first defined (decide what the function actually does) and must then be called. When a function is "called", we are asking the computer to perform the tasks we already assigned to the function.

Purpose of Functions

Functions allow us to reuse a set of commands (multiple lines) with just a single line of code (the line to call the function). This makes our code much shorter. In addition, the code can be given a descriptive name through the function’s name to give readers a clearer understanding of what is going on. For example, if I had a brush and was giving it commands to draw a certain shape(a square in this case), it would be like so…

Text
Go straight 5 units
Turn Right
Go straight 5 units
Turn Right
Go straight 5 units
Turn Right
Go straight 5 units
Turn Right

But I could simplify it with a function…

Text
CREATE Function to make a side = Go straight 5 units + Turn Right
Now the code would be something like …

RUN Function to make a side
RUN Function to make a side
RUN Function to make a side
RUN Function to make a side

And we could simplify it even further…

Text
CREATE Function to make a square =  Function to make a side + Function to make a side
 + Function to make a side + Function to make a side  

And the code would now be…

Text
RUN Function to make a square

Make sense? Great! Basically, we use them to avoid repetition of code. Now, moving on to functions in Python.