15
The Art of Functions
Wondering, what's up with this weird ancient art? Well, they help portray how civilization evolved much like how we learned to evolve our ways to talk to machines. Like us humans divided our society to do specific tasks say carpenters to work with wood, barbers to trim our hairs, similarly, we can ask machines to work specifically on something or take a specific action when some work is given. As an example imagine, when we wake up, we follow the below step -
Get your bed done > Brush your teeth > Wash your face > Dry your face
For machines, these are described as functions. To understand what a function is imagine a set of instructions that needs to be done when something happens.
Now you might think why do we need to have functions? It's simple, however much we like to abuse Ctrl+C & Ctrl+V it's not a good practice to have repeatable code. Instead, every time you have to do the same action, you can simply call the function to make it work.
In Python, there are two kinds of functions - Built-in functions and User-defined functions. We will talk about Built-in functions in a later post.
Today, we will discuss the three kinds of User-defined functions, let's start with the basic one. To write any function we need to have a few important things in mind -
- A function should always start with
def
word - The
def
will be followed by the name of the function, recommended in all lower case - The name of the function is followed by a parenthesis and colon
():
, denoting the end of defining a function - Any lines inside the function should be indented to work under the function call.
- Optional requirement, a docstring can be added right below the function.
Here's how it would look like. π
Now the important takeaway from here is how a function when defined doesn't do anything, which means that it would be defined inside the variable wake_up
when you run the file, however, you would need to call it to make sure it does what you have asked it to do. You can call it by writing the unique name of the function you have defined, followed by the parenthesis.
Here, I've asked it to print I woke up at 8 AM
Before we jump into understanding the other two types of functions and when to use them, we need to understand two important concepts:
- Parameters - Parameters are something that your function can take and work with, inside the function. Think of it as a variable inside a function that can take inputs or can be optional too.
- Arguments - Arguments are the values that you would assign to your parameter when calling the function. Think of it as assigning a value to the pre-defined parameters. Arguments are again defined into two groups:
- Positional Arguments - Arguments that are called into functions based on the positions of the paraments.
- Keyword Arguments - Arguments that are called into functions using the same keyword that is used to define the parameters.
As we have grasped the basic idea of Parameters and Arguments let's dive into the next type of function drum-roll -
Here, we can see that wake_up
has two parameters time
& meridian
. You can see that time
requires a value however meridian
has a pre-assigned value of a string 'AM'
, which means that the meridian is optional for you to assign. Here's how you can call this function:
Calling the function with only the required data -
-
Positional argument:
wake_up(12)
--> This will print I woke up at 12 AM -
Keyword argument:
wake_up(time=12)
--> This will also print I woke up at 12 AM
Here, the 12 gets assigned to the time variable whereas the meridian uses the 'AM' as the default value.
Calling the function with both data -
-
Positional argument:
wake_up(12, 'PM')
--> This will print I woke up at 12 PM -
Keyword argument:
wake_up(meridian='PM', time=12)
--> This will print I woke up at 12 PM
Here, the 12 gets assigned to the time variable and the meridian gets assigned to the 'PM' value. This is one of the benefits of using keyword variables as it doesn't require the position of arguments to match the position of parameters.
Note: Changing the positional argument wake_up('PM', 12)
would print --> I woke up at PM 12
This is probably the most used kind of function and is really handy to work with. Almost every rule stays the same from when we defined the Fundamentals of Functions apart from the addition of one:
- As this gives us an output a command
return
is added at the end which allocates the output to a variable outside the function which can then be re-used.
Note: Anything after the command return
would be ignored by the console as the function would immediately end and allocate the value.
Calling the function with positional argument -
returned_value = add(2, 3)
--> This doesn't print any value but instead allocated the variable returned_value
with 5
.
Try this out and see, how the print statement is absolutely ignored by the console.
Calling the function with keyword argument -
returned_value = add(number1 = 6, number2 = 3)
--> This too doesn't print any value but instead allocated the variable returned_value
with 9
.
We have now understood the types of functions that we can write to help us talk to machines efficiently, without having to repeat ourselves. However, sometimes, we speak in languages our machines have a hard time understanding, those are bugs or errors in our code.
Here are a few common ones for you to catch:
- Missing an argument, if your function has parameters would pop a
TypeError
- Writing a Keyword argument before a Positional argument would result in
SyntaxError
- Any line of code after the
return
command on the same indentation level would be ignored.
Here's an image that summarizes how functions are triggered and how they work.
- The code starts execution from the arrow tail and follows its head
- When it hits the star
- It jumps to see the function under the name of
sum
- Executes everything inside the function taking the arguments to replace the parameters
- Hits the
return
statement - Allocates the value of the local variable
num
to the global variableaddition
That's it for Functions! Next, we will talk about more advanced function usages. Hope this has helped you understand how functions work & what exactly happens under the hood making our lives easier. If you have any interesting suggestions or feedbacks, feel free to connect with me on Twitter. I also have a newsletter, which I send out every week Thursday. You can subscribe it here.
I hope this message finds you in good health!
15