Python

Functions

YouTube

Functions in Python are blocks of reusable code that can be called multiple times in a program. They allow us to break up our code into smaller, more manageable chunks and make it easier to understand and maintain. Functions can also help us adhere to the “DRY” principle, which stands for “Don’t Repeat Yourself.” This means that we should avoid writing the same code multiple times in our programs.

Creation

To create functions in Python, we use the def keyword followed by the function name and a pair of parentheses. We can also include parameters within the parentheses, which are values that can be passed to the function when it is called. For example:

def greet(name):
  print("Hello, " + name)
Parameters and Arguments

This function, called greet, takes in a single parameter called name and prints a greeting to the screen. When creating a function, a parameter can be named arbitrarily, however, the referencing of the parameter throughout the functions code, needs to stay consistent.

If there are more than one parameters, they need to be called in the correct order, otherwise you may encounter some bugs.

Calling a function

To call the function, we simply write its name followed by a pair of parentheses and any necessary arguments. For example:

greet("John")

This would output “Hello, John” to the screen.

Return

Functions can also return a value using the return keyword. The return keyword only returns the data from the function, if we wanted to output it, we would either need to assign it to a variable, or print the function call. For example:

def add(x, y):
  return x + y

print(add(4, 3))
# Outputs 7

This function, called add, takes in two parameters, x and y, and returns their sum. We can store the result of this function in a variable like this:

result = add(3, 4)

print(result)
# Outputs 7
Default Values

Functions can also have default values for their parameters. This means that if we don’t pass a value for that parameter when calling the function, it will use the default value instead. For example:

def greet(name="John"):
  print("Hello, " + name)

In this case, the greet function has a default value of “John” for its name parameter. If we call the function like this:

greet()

It will output “Hello, John” to the screen. However, we can also pass a different value for the name parameter when calling the function, like this:

greet("Mary")