Python Functions for Beginners — An Introduction to Python Functions
By: Data Science
Tags: Python Programming, Programming, Python, Python Functions

We’ll deal with Python functions — an invaluable tool for programmers. The best way of learning is by doing, so let’s create a function and see how it can be applied.

Defining a Function in Python

To tell the computer you are about to create a 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. 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 miss to put 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!

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

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?

Great!

Creating a Function with a Parameter

Our next task will be to create a 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.

Good. What comes next is very important.

Don’t forget to return a value from the function. If we look at the function we wrote in the previous lesson, 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.

Type “return “a” plus 10”. This will be the body of this function.

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

Amazing! It works.

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.

Great!

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.

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 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 functions x1, x2, x3 and so on, your colleagues will be confused and utterly unhappy.

Naming functions clearly and concisely makes your programming code easy to understand, and it will be accepted as one of 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 get nothing. Why? Because to this moment, I have only declared the variable “result” in the body of our function.

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

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

“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 supposedto give back. It’s important you understand what each of the two keywords does. This will help you a great deal when working with 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”.

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.

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

Using a Function in another Function

It isn’t a secret we can have a function within the function. 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.

When you do well in a day, your boss will be very happy to give a bonus of 50 dollars added to your salary. Hence, I’ll define a “with bonus” function for you. And as a parameter, I will take again the working hours. But this time, I will allow myself to return directly the wage with working hours as an output, which would be the value obtained after the wage function has been run, plus the extra 50 dollars you’ve earned.

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

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.

Great! 200 of base compensation and 250 with the bonus!

Combining Conditional Statements and Functions

We know how to work with if statements, and we know how to work with functions. In this lesson, 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 did 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 tell 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 a hundred, let “m” assume the value of “m” plus 10.

Yes, it is what you saw! We have “m” on both sides of the equation, and that is perfectly fine. As a matter of fact, it 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. At the end, we say: from now on, return a value equal to the new “m”.

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

Let’s see if our intuition was correct. “Add 10” of 110 — good, 120!

And if “m” was equal to 50…? 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 certainlimits 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.

Creating Functions Containing a Few Arguments

We are almost there. In this lesson, 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.

Shall I call the function we have here for, say, 10, 3, and 2? I get 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.

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!

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

Notable 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 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.

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.

Great!

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.

“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.

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?

Perfect!

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.

“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.

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

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!

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.

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