Building our own functions

Video: Functions in Python

Defining a function

We use the keyword def (short for ‘define’) to create a new function. When you define a function, you specify a name for the function as well as a sequence of statements in an indented block. The function is stored in the program’s memory, but the code does not run right away. After the definition, we can call the function to run the code.

Here’s what it looks like:

# Define a function.
def function_name(parameter_1, parameter_2):
	# Follow these steps (the indented function body)
	# print each parameter
	print(parameter_1)
	print(parameter_2)

# Use function_name to call the function.
function_name(argument_1, argument_2)

When defining a function:

  • Use the keyword def
  • Give the function a name, ideally one that tells what the function does
  • Give names for each of the function's parameters
  • Use an indented block for the code for the function

Below is an example of a Python function that calculates the sum of two numbers:

def add(a, b):
  return a + b

Later, when we want to run the statements in the function, we call the function, which runs the code from the function definition.

add(3, 5) # 8
add(10, 30) # 40

Parameters and Arguments

def add(a, b):
  return a + b

In the example above, a and b are parameters. Parameters are names that stand in for the values passed to the function. You use them in the function body like variables.

We can call the add function like this:

>>> add(3,5)
8

The values passed to the function are called arguments. In this example, 3 and 5 are arguments. The parameters a and b get assigned the values 3 and 5 in the function body.

Practice

A sample run of your code with argument Keno, i.e., greet("Keno") should look like this:

Welcome to Kibo, Keno
We're glad you're here Keno.
Keno, how did you hear about us?
Explanation

If you put the function definition at the end of the program, you will get an error.

A function must be defined before you use it in your program. If you try to call greet("Keno") before the function greet is defined, Python doesn't know how to run the function, and will raise a NameError.

Functions can have any code inside them

Any code can go inside a function. Variables, loops, conditions, other function calls — it all works. Anything that you’ve written in a program so far can go inside a function.

# A function with an if/else statement
def check_password(attempt):
	password = "sEcRetPaSsWoRd"
	if attempt == password:
		return "You're in!"
	else:
		return "Access denied"

print(check_password("open sesame")) # Access denied
print(check_password("sEcRetPaSsWoRd")) # You're in!

# A function with a loop inside
def add_up_to(number):
	total = 0
	for i in range(1,number):
		total += number
	return total

print(add_up_to(5))   # 20
print(add_up_to(10))  # 90
print(add_up_to(100)) # 9900