Introduction To Python Functions: Definition and Examples

Martin Ganchev 22 Jul 2021 16 min read

So, you want to learn how to code in Python? Well, you can't do that without knowing how to work with Python functions.

No worries though,  in this tutorial we’ll teach you how to use Python functions and how these can help you when programming in Python. The best way of learning is by doing, so let’s create our first function and see how it can be applied.

How to Define a Function in Python

To tell the computer you would like to create a Python function, just write def at the beginning of the line. Def is neither a command nor a function. It is a keyword. To indicate this, Jupyter will automatically change its font color to green. Then, you can type the name of the function you will use. (To learn how to navigate through the Jupyter dashboard, check out our tutorial The Jupyter Dashboard - A Walkthrough.)

Defining a Function in Python: def function_name (parameters)

For instance, simple, as we will create a very simple function. Then we can add a pair of parentheses. Technically, within these parentheses, you could place the parameters of the function if it requires you to have any. It is no problem to have a function with zero parameters. This is the case with the function we are creating right now. To proceed, don’t forget to add a colon after the name of the function.

Since it is inconvenient to continue on the same line when the function becomes longer, it is much better to build the habit of laying the instructions on a new line, with an indent again. Good legibility counts for а good style of coding! And fewer arguments with the people you are working with (those wise guys...)

Defining a Function in Python: def function_name (parameters) and function body

All right, let’s see what will happen when we ask the machine to print a sentence.

Defining a Function in Python: printing the sentence "My first function"

Not much, at least for now.

The computer created the function “simple” that can print out “My first function”, but that was all. To apply the function, we must call it. We must ask the function to do its job. So, we will obtain its result once we type its name, “simple”, and parentheses. See?

Defining a Function in Python: calling the function

Great! Let's do something a bit more sophisticated though. After all, Python functions can't be this simple, right?

How to Create a Function with a Parameter

Our next task will be to create a Python function with a parameter. Let it be “plus ten” with a parameter ”a”, that gives us the sum of “a” and 10 as a result…

Always begin with the “def” keyword. Then, type the name of the function, “plus ten”, and in parentheses, designate the parameter “a”. The last thing to write on this line would be the colon sign.

Creating a Python Function with a Parameter

Good. What comes next is very important. Even more important than brushing your teeth in the evening. Seriously. (Don't agree? Well, it's at least as important then, so, please pay attention)

Don’t forget to return a value from the function. If we look at the function we wrote previously, there was no value to return; it printed a certain statement. Things are different here. We will need this function to do a specific calculation for us and not just print something.

Creating a Python Function with a Parameter: returning a value from the function

Type:

return a + 10

This will be the body of this function.

Creating a Python Function with a Parameter: return a + 10

Now, let’s call “plus ten” with an argument 2 specified in parentheses.

Creating a Python Function with a Parameter: calling + 10 with an argument 2 specified in parentheses

Amazing! It works. (We were really surprised it did work!)

Once we’ve created a function, we can run it repeatedly, changing its argument. I could run “plus ten” with an argument of 5, and this time, the answer will be 15.

Creating a Python Function with a Parameter: running + 10 with an argument of 5

Pay attention to the following. When we define a function, we specify in parentheses a parameter. In the “plus ten” function, “a” is a parameter. Later, when we call this function, it is correct to say we provide an argument, not a parameter. So we can say “call plus ten with an argument of 2, call plus ten with an argument of 5”.

People often confuse print and return, and the type of situations when we can apply them. To understand the concept better, try to imagine the following.

There is an argument x, which serves as an input in a function, like the one we have here. The function, in this case, is x plus 10. Given that x is an input, we can think of it as a value we already know, so the combination of x and the function will give us the output value y. Well, in programming, return regards the value of y; it just says to the machine “after the operations executed by the function f, return to me the value of “y”. “Return” plays a connection between the second and the third step of the process. In other words, a function can take an input of one or more variables and return a single output composed of one or more values.

This is why “return” can be used only once in a function.

Therefore, we can say the concept of a function applies to programming almost perfectly.

Creating a Python Function with a Parameter: return can be used only once in a function

There are some extra advantages to consider. You could also assign a more intuitive name to a function – “plus ten” or “addition of 10”, and the Python function will still run correctly. This is a sign of good design. On a sheet with one thousand lines of code, if you call all your Python functions x1, x2, x3 and so on, your colleagues will be confused and utterly unhappy.

Creating a Python Function with a Parameter: you can also assign a more intuitive name to a function

Naming Python functions clearly and concisely makes your programming code easy to understand, and it will be accepted as one of good style. (If you want to learn how to type a clean code in any programming language, read our article How to Type Code Cleanly and Perfectly Organized. Or, if you want to gain some powerful all-around Python programming knowledge, make sure you check out our Complete Python Programming Guide.)

Creating a Python Function with a Parameter: good style

Another Way to Define a Function

There is another way in which you could organize the definition of your function. Start by defining “plus ten” with an argument of “a” and a colon. On the next line, instead of directly returning the value of “a” plus 10, another variable can be created inside the function to carry that value. I will use the name “result” here. I will assign it with the desired value of “a” plus 10.

Let’s check what we just did.

If I execute the code in the cell, I will obtain nothing. Why? Because to this moment, I have only declared the variable “result” in the body of our function.

Another Way to Define a Python Function: assigning the name "result" with the desired value of a + 10

Naturally, to obtain the desired outcome, I will also have to return that variable.

Another Way to Define a Python Function: returning the result variable

See? When I call “plus ten” with an argument of 2, I obtain 12. It is all fine again.

Another Way to Define a Python Function: calling +10 with an argument of 2

Print” takes a statement or, better, an object, and provides its printed representation in the output cell.

It just makes a certain statement visible to the programmer. A good reason to do that would be when you have a huge amount of code, and you want to see the intermediary steps of your program printed out, so you can follow the control flow. Otherwise, print does not affect the calculation of the output.

Differently, return does not visualize the output. It specifies what a certain function is supposed to give back. It’s important you understand what each of the two keywords does. This will help you a great deal when working with Python functions.

The following could be helpful.

Let that same function also print out the statement “outcome”. If we put down only “return outcome”, and then “return result”, what will we get when we call the function? Just the first object to return – the statement “outcome”.

Another Way to Define a Python Function: printing out the statement 'outcome'

If instead, we print that statement and then return ‘result’, we will get what we wanted: the “outcome” statement and the result of the calculation – 12. (If you want to learn an elegant way of adding a statement with the elif keyword, check our tutorial What is Elif in Python.)

Another Way to Define a Python Function: printing out the statement 'outcome' and returning 'result' with outcome 12

This was to show you we can return only a single result out of a function.  

How to Use a Function in Another Function

It isn’t a secret we can have a function within the function (which is way more useful than a picture within a picture). For instance, let’s define a function called ‘wage’ that calculates your daily wage. Say you use working hours as a parameter, and you are paid 25 dollars per hour.

Notice, I don’t technically need the print command here.

I could print out the wage afterwards, but I don’t really need to. So, I’ll proceed this way, just returning the value I need.

Using a Function in Another Function in Python: return w_hours * 25

When you do well in a day, your boss will be very happy to pay a bonus of 50 dollars added to your salary (well, at least he says he's happy...). Hence, I’ll define a “with bonus” function for you. And as a parameter, I will use working hours once again. But this time, we will have two arguments defining this function - your wage (which is a function of the number of hours you worked, and the extra 50 dollars you will be paid when your boss decides you deserve a bonus.

Using a Function in Another Function in Python: defining a "with bonus" function

This is how the first function is involved in the output of the second one – a function within the function!

Using a Function in Another Function in Python: how the first function is involved in the output of the second one, def wage w hours return wage w hours

Let’s see what the output will be if you worked 8 hours today and the boss was very happy with your performance.

'Wage' with an argument 8, and “with bonus” with an argument 8.

Using a Function in Another Python Function: 'wage' with an argument 8, and “with bonus” with an argument 8

Great! 200 of base compensation, which becomes 250 with the bonus! You earned every penny of it! :)

Author's note: If you are interested in a career that will not only earn you a few pennies but potentially north of $130,000, don't miss out on our free "how to become a data scientist" career guide.

How to Combine Conditional Statements and Functions

We already know how to work with if statements, and how to work with Python functions. In this post, we’ll learn how to combine the two. This is a fundamental concept in programming, so please pay attention! You’ll encounter it quite regularly when coding.

Johnny's mom told him that, by the end of the week, if he has saved at least 100 dollars, she would give him an extra 10 dollars.If he does not manage to save at least 100 dollars, though, she would prefer not to give him the extra cash.

Clear. Now, let’s define a function called “add 10”,  which takes as a parameter the unknown “m” that represents the money Johnny saved by the end of the week.

What should we ask the computer to do?

If “m” is greater than or equal to 100, then add 10 to the saved amount. If it is not, return a statement that lets us know Johnny should save more.

That is, if “m” is greater than or equal to 100, let “m” assume the value of “m” plus 10.

Combining Conditional Statements and Functions in Python: if 'm' is greater than or equal to 100, let 'm' assume the value of 'm +10'

We have “m” on both sides of the equation, and that is perfectly fine. As a matter of fact, this is not an equation. Remember that the “equality” sign stands for assigning the expression on the right side to what is written on the left side.

Let’s complete the if-part with “return m”. To sum up, logically, we mention “m” as a parameter. Then, we substitute its value with a value greater than “m” with 10. In the end, we say: from now on, return a value equal to the new “m”.

Combining Conditional Statements and Functions in Python: substituting the value of 'm' with a value greater than 'm' with 10 and return a value equal to the new 'm'

Finally, in all other cases, the function would display “Save more!” (Johnny should learn it is a good habit to have some cash on the side, right?)

Combining Conditional Statements and Functions in Python: if m < 100, then 'Save more'

Let’s see if our intuition was correct.

add_10(110)

 

Combining Conditional Statements and Functions in Python: outcome equals to 120

Good, 120! And if “m” was equal to 50…?

Combining Statements and Functions in Python: else: return 'Save more!'

Amazing! Everything is correct!

When you think of it from a logical perspective, it makes sense, doesn’t it? What would you use a computer for? – to solve problems for you. And it can do that through functions. You’ll most probably need to ask the machine to execute something if a given parameter is within certain limits and ask it to execute another thing if the parameter is beyond these limits. Therefore, combining your knowledge about conditionals and Python functions comes right on the money.

How to Create Python Functions Containing a Few Arguments

We are almost there. Now, we’ll learn how to work with more than one parameter in a function. The way this is done in Python is by enlisting all the arguments within the parentheses, separated by a comma.

Creating Python Functions Containing a Few Arguments: def function_name (parameter #1, parameter #2)

Shall I call the function we have here for, say, 10, 3, and 2? I get 4.

Creating Python Functions Containing a Few Arguments: a-b*c = 10 - 3x2 = 4

Seems easy to add a few parameters, right? And it is! Just be careful with the order in which you state their values. In our case, I assigned 10 to the variable a, 3 to b, and 2 to c.

Creating Python Functions Containing a Few Arguments: order matters: parameter a equals 10, parameter b equals 3, parameter c equals 2

Otherwise, the order won’t matter if and only if you specify the names of the variables within the parentheses like this: b equals 3, a equals 10, and c equals 2.

And of course, we could obtain the same answer – 4!

Creating Python Functions Containing a Few Arguments: subtract_bc (b=3, a=10, c=2)

This is how we can work with functions that have multiple arguments.

Built-In Functions in Python

When you install Python on your computer, you are also installing some of its built-in functions. This means you won’t need to type their code every time you use them – these Python functions are already on your computer and can be applied directly.

The function “type” allows you to obtain the type of variable you use as an argument, like in this cell – “Type” of 10 gives “int” for integer.

Built-In Python Functions: type () obtains the type of variable you use as an argument

The “int”, “float”, and “string” functions transform their arguments in an integer, float, and string data type, respectively. This is why 5.0 was converted to 5, 3 was converted to 3.0, and the number 500 became text.

Built-In Python Functions: int, float, string functions

Now, let me show you a few other built-in functions that are quite useful.

“Max” returns the highest value from a sequence of numbers. This is why “Max” returned a value of 30 as an output in this cell. Good.

Built-In Python Functions: max function

“Min” does just the opposite – it returns the lowest value from a sequence. So, we get 10 in that cell over here – it is the smallest among 10, 20, and 30.

Built-In Python Functions: min function

Another built-in function, “Abs”, allows you to obtain the absolute value of its argument.

Let “z” be equal to minus 20. If we apply the “abs” function to “z”, the result will be its absolute value of 20. See?

Built-In Python Functions: abs function

An essential function that can help you a great deal is “sum”. It will calculate the sum of all the elements in a list designated as an argument. Consider the following list made of 1, 2, 3, and 4 as its data. When I type “sum list 1”, my output will be equal to 1 plus 2 plus 3 plus 4. The sum of these numbers equals 10.

Built-In Python Functions: sum function

“Round” returns the float of its argument, rounded to a specified number of digits after the decimal point. “Round” 3.555 with 2 digits after the decimal point will turn into 3.56.

Built-In Python Functions: round function

If the number of digits is not indicated, it defaults to zero. 3.2 is rounded down to 3.0. Great!

Built-In Python Functions: round function. If the number of digits is not indicated, it defaults to zero. 3.2 is rounded down to 3.0.

If you are interested in elevating 2 to the power of 10, you know you could type “2 double star 10”. You can get the same result if you use the “pow” function, which stands for “power”. Write “pow”, and in the “parentheses”, specify the base and the power, separated by a comma. In our case, “2 comma 10”. Execute with “Shift and Enter” and… voilà! 1024!

Built-In Python Functions: pow function

And what if you wanted to see how many elements there are in an object? The “Len” function, as in “length”, is going to help you do that. If you choose a string as an argument, the “Len” function will tell you how many characters there are in a word. For instance, in the word “Mathematics”, we have 11 characters.

Built-In Python Functions: len function

There are many other built-in Python functions, but these are a few examples you will often need to use when programming.

Ok, this wraps up our article, in which we introduced you to some of the basic (but very important!) Python functions. To continue your Python journey why not check out our tutorial on how to work with lists in Python?  If you’re enthusiastic about boosting your Python knowledge, go to our super practical tutorials. For some exercises to test your skills try your hand at these: Functions containing a few arguments, Combining statements and functions, Combining conditional statements and functions, Using a function in another function.

GRAB 1 OF 200 ANNUAL PLANS UP TO
72% OFF

Martin Ganchev

Instructor at 365 Data Science

Martin holds an MSc degree in Economic and Social Sciences from Bocconi University. His diverse academic and research experience combined with his friendly and explanatory approach to teaching have made him one of the most beloved instructors on our team. Some of the courses he has authored include: SQL, SQL + Tableau, SQL+Tableau+Python, Introduction to Python, Introduction to Jupyter, to name a few.

GRAB 1 OF 200 ANNUAL PLANS UP TO
72% OFF
Top