Skip to Main Content
It looks like you're using Internet Explorer 11 or older. This website works best with modern browsers such as the latest versions of Chrome, Firefox, Safari, and Edge. If you continue with this browser, you may see unexpected results.

Python for Basic Data Analysis: 2.1 Introduction to Functions in Python

Get started on your learning journey towards data science using Python. Equip yourself with practical skills in Python programming for the purpose of basic data manipulation and analysis.

Functions in Python

Functions are a way of writing code whereby you group together a set of "tasks". Therefore, instead of writing tasks individually, multiple times, you simply use the Function that houses the set of tasks. 

This means if you have a repetitive task, you do not have to write the code over and over. Just write the code into a function and use the function to do the task.

Functions will be building blocks for constructing complex codes. 

Basic Structure for Functions

Structure of a function

Functions start with a def, followed by a function name and parenthesis, the docstring (optional), the function statements (i.e. codes) and ending with either return, pass, or nothing at all. Watch the accompanying video for a more detailed explanation. 

Python functions usually looks something like this:

Syntax

def functionname(arguments):

 """This is the docstring that explains what this function is supposed to do"""
 
 function statements

 return

 

Calling a function

To use the function we simply call its name by writing functionname()

Example

In this example, my function name is hello.
Note that this function does not have a return statement, otherwise known as a void function.


Here is another example of a void function. The function rounds any decimal number that a user inputs to 3 decimal places. 

Activity

Write a function that will return the number 1.2347586839402 to 5 decimal places

Video Guide

From 1.41 to 4.58