The Basics of Functions in Python

Cris
3 min readJun 6, 2021

Over the last year, I have become a huge fan of functionalizing code for ease of access and lessening repetition. In this post we are going to go over the basics principles of functions in python. To learn more about functions you can visit w3school here.

A function is defined in python by the “def” keyword followed by the name of the function, parentheses, and a colon. Just as when you create loops and if statements, the lines within your function are indented.

Below is a very simple function that prints a statement.

Now if we ever want to run this function, all we need to do is call it.

This function just prints this statement.

You are able to pass information into functions with parameters. A parameter is a variable that is listed inside the parentheses of the function. You can have multiple parameters in a single function.

45 + 72 = 117

Sometimes you may not know how many parameters will be passed into the function. In that case you can add a * before the start of the parameter.

The sum total of (3, 9, 12, 11, 6, 1) is 42.

You can also set a default parameter that the function will default to if no argument is given.

Your name is Finn.
Your name is Jake.

Functions also have the ability to return a value that can be saved as a variable for later.

42

Now the variable total is saved as equaling 42 and can be called upon later if needed.

One last important thing when it comes to functions is the docstring. This is where you can tell future people what the function you created does. The docstring is put right under the first line with three quotation marks.

Now if we forget what the function does we can look at the docstring.

There is so much you can do with functions. This wasn’t even the tip of the iceberg when it comes to the functionality of functions. I would suggest starting to incorporate functions into your everyday coding.

--

--

Cris
0 Followers

Data analyst with experience in web scraping, SQL, data modeling, and machine learning.