Functions in Python

From Sustainability Methods

THIS ARTICLE IS STILL IN EDITING MODE

Description

Functions (or “Methods” in some other programming languages) are reusable blocks of code that do a specific thing and can be reused multiple times in a program. It is good for task breakdown and code readability.

We have already used several functions in the tutorials above, such as the “print()” function. These functions are default functions readily available in Python. However, it might be handy sometimes to develop your own functions for specific occasions. First, we will look at pre-defined functions and then develop our own user-defined functions.

Pre-defined Functions

Understanding all the pre-defined functions in python is a journey of a lifetime. However, through our exercises, you will know and get used to the most common functions that exist.

We can start with the 3 examples that most of you have seen before:

# suppose we have a height of pupils in a class
heights = [150, 166, 154, 145, 159]

# print() is a predefined function
print(heights)

# sum() is also a predefined function to add every element in a list
sum(heights)

# len() is a predefined function to show the length of a list
len(heights)

This was quite intuitive, right? Next, we will make our own functions, just like the pre-defined functions have been created by someone.

User Defined Functions

String Example

An example function looks as follows:

# First function example: A function to greet people
def greet(name):
    """
    this is a documentation: explaining the function
		input: name (str)
		output: says hello, and the person name
    """
    print("Hi, how are you,", name)
    return

As you can see above:

  • The function begins with a special word: "def", and then the function name. In this case, our function name is "greet"
  • After that, we need parentheses "( )". Inside parentheses is what we call argument (or input parameters). Arguments can be more than one. In the example above, we only have 1 argument, which is the “name” to store the name of the person we want to greet.
  • To finish the first line of code, a colon (:) is needed.
  • The body of a function is the “inside” of a function. Important is to indent (adding TAB before code) **the body.

Adding documentation to your function will make it look professional and will help with the readability of your whole program.

  • Lastly, using the “return” statement will end your function.

We can call the documentation of a function using:

help(greet)

And of course, we can use (or "call") the function

greet('Stephen')

And as you can see above, the syntax is similar to $print('argument')$. That is because “print” is also a function, however, it is by default defined by the system.

Math Example

def multiplication(a, b):
	"""
	Define a function to multiply 2 numbers
	"""
	c = a * b
	return (c)
	print("not printed", c)
result = multiplication(2,3)
print(result)

The example above is really similar to our first example with greeting names. However, now you know that we can use functions for not only strings, but also numbers, tuples, arrays, and so on, depending on your function.

A short quiz for you, can you multiply a string with a number?

multiplication(4, 'Arthuria')


Default Argument Values

It is possible to set a default value for arguments in a function.

def is_mood_good(good_mood=True):
	"""
	True if good mood
	False if bad mood
	"""
	if(good_mood == True):
		print("I feel good")
	else:
		print("I feel good... just kidding")

And you can try the default argument, and your own argument:

is_mood_good()
is_mood_good(True)
is_mood_good(False)

Local versus Global Variables

We can create a variable in a function. That variable can only “live” inside that function. On the opposite, if we create a variable outside a function, it can “live” both inside and outside the function. The advantage of local variables is that they cannot be altered by any other commands in your script and make it easier to oversee. Let's say you only need a part of a string for one certain calculation you are doing, but the whole string for other calculations. It would be best to then store the partial string as a local variable so it does not get confused later on.

Example:

global_var = "global is here"

def local_func():
	"""
	example of a local function
	"""
	local_var = "local_var is here"
	print(local_var)
	return

print(global_var)
print(local_var) # this will throw an error because it doesn't exist outside the local_func

Quiz

  1. Write a function to divide the first input by the second input
  2. Complete the function below to return a product of the first and second input
def f(x1, x2):
	# TODO
	return
  1. Consider c = [1,2,3,4,5] and g is a function that computes its sum
def g(c):
	# TODO
	return

The author of this entry is XX. Edited by Milan Maushart