Python Tutorial: Functions Including Parameters and Returns
Share this post
You might have used and created simple functions that carry out one task in isolation. This type of function is often referred to as a procedure or subroutine. These functions might accept parameters, but they do not return any information to the program that called them.
In this article, you’ll learn more about these two aspects of functions – parameters and return values – and how they make functions incredibly useful.
Let’s imagine our function as a machine carrying out a some computational task when switched on or called. A simple function or procedure is like a basic machine: it does one fixed task, like a kettle. We turn it on, it does the task, and we recieve no real feedback from the machine. Every time this function is called it carries out its task.
Parameters = inputs
Most everyday machines allow us some control over what the machine does: the temperature of an oven, the speed of a fan, or the amount of water a washing machine should use. Without these controllable elements we’d need a different machine with a different setting for every job, e.g. a different oven for each temperature we want to cook at.
It’s a similar story with programming. Whilst simple functions allow a programmer to package up code and reuse it, without controllable elements they would need a different function for every scenario, even if they are very similar.
Rather than re-invent the wheel every time, a programmer will create a function that can apply to multiple situations and be tailored to each one, using inputs or parameters.
For example, here’s a pair of functions that each load some map data from a file. As you can see, they have very similar actions: they each open a text file in r (read) mode, and add the contents of the file to a list.
map1 = [] #Creates an empty list
#Here we define the function
def load_level_1():
with open("map1.txt",mode="r") as file:
for line in file:
map1.append(line.strip().split(","))
map2 = [] #Creates an empty list
#Here we define the function
def load_level_2():
with open("map2.txt",mode="r") as file:
for line in file:
map2.append(line.strip().split(","))
Such duplication in programs can be avoided by writing a single function with parameters, which can then be used to load either map data file. Here the parameters have been given descriptive names (file
and map
), but you can call them anything you like. The names don’t need to relate to anything in the rest of the program: they only exist within the scope of this function.
map1 = []
map2 = []
def load_level(file,map):
with open(file,mode="r") as file:
for line in file:
map.append(line.strip().split(","))
This function can then be called, and will use whichever map file and variable you ask for:
load_level("map1.txt",map1)
Return values = outputs
A real life machine, like the functions we have seen, has consequences or side effects: it washes clothes, cooks food, or boils water, for example. However, unlike the functions we’ve seen so far, it may also provide some feedback or information as output. Machines might beep, display some text, or sound an alarm, for example. A function can also provide information, simply by returning some data to the program that called it.
When programming, you will often need to get data back from a function, either simply to confirm that the function has done its job, or to get some richer data that the function has calculated. This is done via the return
command, which “returns” data back to the process that called the function. In the simple example below, the function isWeekday
checks whether the date provided is a weekday.
from datetime import datetime
def isWeekday(mydate):
day = mydate.weekday() #Get the nunber of the day of the week - Monday = 0, Tuesday = 1 etc.
if day < 5:
return True
else:
return False
# Calls the function providing a date
workday = isWeekday(datetime.now()) #Call the isWeekday function with today's date, store the returned data in a variable "workday".
Once defined, a function like isWeekday
, which returns a True or False (Boolean) value, can be used in conditional statements:
if isWeekday(datetime.now()):
print("It is a week day")
Of course, functions aren’t just limited to returning Boolean values. They can return any variable, list, or other object. For example, the following function asks the user to input some numbers, and then returns the same numbers as a list.
def getNums(size):
nums = []
for x in range(size):
num = int(input("Enter a whole number: "))
nums.append(num)
return nums
mynums = getNums(10)
You can even return several values from one function and then store these in separate variables:
def get_profile():
firstname = input("What is your first name? ")
lastname = input("What is your last name? ")
age = int(input("What is your age? "))
return firstname, lastname, age
fname,lname,user_age = get_profile()
In this example, we have used different variable names when calling the function from the variable names inside the function. Whilst this is good practice as it helps the programmer distinguish between them, it is not actually necessary in Python. In other words, we could have called the function like this:
firstname,lastname,age = get_profile()
Variables defined inside a function, like firstname
, exist in isolation from other variables and only whilst the function is run. This is their scope. Variables defined in the main program, rather than within functions, exist for the duration of the program and are said to be global in scope. If you want a function to have access to variables outside its own scope, best practice would be to add them as parameters to the function:
am = "Good Morning"
pm = "Good Evening"
def get_profile(msg):
print (msg)
firstname = input("What is your first name? ")
lastname = input("What is your last name? ")
age = int(input("What is your age? "))
return firstname, lastname, age
#Function called passing in variable from global scope
fname,lname,user_age = get_profile(am)
Combining functions
Once you’ve got to grips with creating your own functions, you can begin to add more structure to your programs, taking each component of the program and creating a reusable function from it.
For example, imagine you wanted to create a program that could send Morse code messages by blinking a single LED. This problem can be broken down into a hierarchy of functions.
-
- The highest or most abstract function might be
morseMessage()
, whose job is to take a given string and turn it into a Morse sequence. To do this, it will callcharLookup()
for each character in turn, and then the relevantdot
,dash
, andpause
functions.
- The highest or most abstract function might be
-
- The
charLookup()
function looks up a given character and determines the correct sequence of dots, dashes and pauses for that character. This sequence is returned as a string to themorseMessage()
function.
- The
- The
dot()
,dash()
, andpause()
functions receive no input, and simply turn the LED on and off for the appropriate lengths of time to represent dots and dashes.
We could represent this diagramatically like this:
An example of the full code for a Morse code generator can be found here.
Over to you
Can you create your own functions that use parameters and return values? Pick one of these challenges to complete.
- Create a function that accepts the dimensions of a triangle and returns its area.
- Create a function that accepts a string and returns the same string reversed.
- Create a function that simulates a pair of dice being rolled n times and returns the number of occurrences of each score.
Share this post
Programming 102: Think Like a Computer Scientist

Programming 102: Think Like a Computer Scientist

Our purpose is to transform access to education.
We offer a diverse selection of courses from leading universities and cultural institutions from around the world. These are delivered one step at a time, and are accessible on mobile, tablet and desktop, so you can fit learning around your life.
We believe learning should be an enjoyable, social experience, so our courses offer the opportunity to discuss what you’re learning with others as you go, helping you make fresh discoveries and form new ideas.
You can unlock new opportunities with unlimited access to hundreds of online short courses for a year by subscribing to our Unlimited package. Build your knowledge with top universities and organisations.
Learn more about how FutureLearn is transforming access to education
Register to receive updates
-
Create an account to receive our newsletter, course recommendations and promotions.
Register for free