In my post about print(), we briefly mentioned built-in functions which are named prewritten codes that we use do certain tasks multiple times. Besides print()
, there are many other useful built-in functions in Python. The list does not just stop there. You can load external libraries into Python for more prewritten functions. And if those are still not enough, you can even write your own functions! In this post, we will learn more about functions in Python. So, let us dive in. All the codes in this post are also in this notebook.
More built-in functions in Python
Base Python has so many functions that we do not have enough spaces to discuss here. Instead, I will just introduce you to those that I use the most often. First is the type()
function. Just like its name says, type()
returns the type of whatever input that you gave it. The cells below give a few examples. First, type(10)
gives you the output int
meaning 10
belonging to the integer type. Similarly, 1.6
is of the float type, and 'hello'
the string type.
type(10)
int
type(1.6)
float
type('hello')
str
Checking types of literal values like 10
, 1.6
, or 'hello'
, is not that helpful as we already know what they are. A better use for type()
is for variables which yields the type of their actual values like in example below. Here, it still seems very obvious what num
is, but later on, there will be cases where you have variables generated from other codes. So, tracking those variables’ types is much more meaningful.
num = 12345
type(num)
int
While we are at it, we can also cast variables to different types. Most commonly, we cast between integers, floats, and strings using int()
, float()
, and str()
. Some examples of them are as follows. You can see the differences between the inputs and outputs of these functions. The float 5.7
becomes the integer 5
(yes, Python rounds down your float in this conversion), the integer 1
becomes the float 1.0
, and the number 15
becomes the string '15'
. Casting numbers to strings is easy enough, however, you need to be careful when casting strings to numbers. If your inputs are not actual numbers (like 1...5
or abc
), you will get an error.
int(5.7)
5
float(1)
1.0
str(15)
'15'
int('100')
100
int('abcxyz')
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) Input In [24], in <cell line: 1>() ----> 1 int('abcxyz') ValueError: invalid literal for int() with base 10: 'abcxyz'
Functions from libraries
Functions in base Python are fairly general. For more specific purposes, you likely need to use an additional library (also called a package). Libraries are also prewritten codes, however, at a bigger scale than functions. They come with other tools like new classes (in object-oriented programming, we will discuss this some times later), new data types, new error types, etc. Usually, a library provides functionalities of a particular topic. For examples, numpy
is a library for numerical manipulations, matplotlib
is a library for visualization. As we move into data analytics, we will discuss more about them.
Now, let us use the math
library for demonstration purpose. The math
library is in base Python but needs import it before using. The syntax is very simple, import <library>
with <library>
being math
. We can then use any functions from math
with math.<function>()
. Basically, this library provides, well, mathematical functions, so now you can use those like sin
, cos
, tan
, log
, etc. You can also find constant like pi
or e
here. Below are some demonstrations.
import math
math.factorial(7)
5040
num2 = 64
math.log2(num2)
6.0
angle1 = math.pi / 2
math.sin(angle1)
1.0
User-defined functions in Python
The last function type we will discuss in this post is user-defined functions. Here, “user” refers to you, so this is the type of functions that you write. While the amount of prewritten functions from Python and its libraries is enormous, there are still cases where you want a function very specific to your situation. So, understanding how to write function is very valuable.
Syntax to write function
The syntax to define your own function is as follows.
def <function_name>(<inputs>):
codes to run
return <value> #optional
Now let us discuss what are in the syntax above
– def
is the key word to define a function, and is mandatory
– function_name
defines the function’s name which follows the requirement of variables’ names
– inputs
lists the set of inputs that you want your function to take. They are symbolic names separated by commas ,
. You can use the inputs inside the function as if they are already defined, i.e., no needs to and do not create them before the function definition (not that this causes error but avoid to have more understandable codes). You will provide the actual values of these inputs when calling the function. A function can not have inputs.
– codes to run
is the code your function that will execute when you call it
– return
is the key word for the return statement. Whatever you put after return is the value that the function yields after it finishes executing. Usually, you return the result of what the function tries to do. However, some functions return the state whether they successes in executing something. In certain cases, there are also functions that do not return anything, so the return statement is optional.
Remember to run the cell that defines your function before using it. Function definitions do not show any outputs after running, so do not worry if you see that. To use your function, just call them like built-in ones, function_name(inputs)
with inputs
separated by commas ,
.
Detailed example
It may be a bit abstract for now, so let us examine one example. The code below defines a function that let the user input an integer number n
. It then calculates the sum of all integer numbers from 1
to n
and returns the result. Ignore the def
statement and the return
statement, the code inside the function is just a regular use of accumulator to calculating the sum of a sequence. Back to the def
statement, we declared n
as an input, so, n
can be used inside the function without being created. Next, accumulator
appears after return
, which means this function will yield the final value of accumulator
after finishing to run.
def sum_1_to_n(n):
accumulator = 0
for num in range(n+1):
accumulator = accumulator + num
return accumulator
As we have discussed, call a function when you want to use it, and provide inputs if necessary. Because we defined sum_1_to_n()
with one input, we must always provide a value when calling the function. You can try using the function without or with more than one inputs and observe the error message. Lastly, because this function returns a result, we can assign the function call to a variable to store the value for uses later.
sum_1_to_n(10)
55
sum_1_to_n(20)
210
sum_1_to_n(50)
1275
sum_1_to_100 = sum_1_to_n(100)
print(sum_1_to_100)
5050
Some reiterations
This post give you a gentle introduction on different types of functions in Python. We actually use functions very frequently in data analysis, so it is important to understand them. Furthermore, mastering how to write function is also very helpful and may save you a lot of headaches later on. So, like the other concepts in programming, take your time to get used to the concept of functions as well as practice with them. After this point, you should have enough basic knowledge about Python to move on to data analytics! As usual, let us see each other in my next post!