Seminar 003: Functions in Python¶
Notes¶
In [ ]:
Copied!
Functions¶
Sometimes you need to repeat the same code over and over again, and you want to avoid copy-pasting. See the example below:
Why?¶
In [ ]:
Copied!
import math
# Task: Calculate the inverse square root of numbers 1 to 100
number_1 = 1 / math.sqrt(1)
number_2 = 1 / math.sqrt(2)
number_3 = 1 / math.sqrt(3)
number_4 = 1 / math.sqrt(4)
number_5 = 1 / math.sqrt(5)
# ... and so on
print(number_5)
# or use a for loop
for number in range(100):
inv_sqrt = 1 / math.sqrt(number)
# Copy and past or even re-writing can be quite faulty!
# Dont let you trick from this simple example
import math
# Task: Calculate the inverse square root of numbers 1 to 100
number_1 = 1 / math.sqrt(1)
number_2 = 1 / math.sqrt(2)
number_3 = 1 / math.sqrt(3)
number_4 = 1 / math.sqrt(4)
number_5 = 1 / math.sqrt(5)
# ... and so on
print(number_5)
# or use a for loop
for number in range(100):
inv_sqrt = 1 / math.sqrt(number)
# Copy and past or even re-writing can be quite faulty!
# Dont let you trick from this simple example
Use a function¶
Python functions are a way to encapsulate code into a single unit that can be reused. These functions can take arguments and optionally return a value. Think of it as having a recipe for a cake. You can use the same recipe to make different cakes.
A function is defined using the def keyword. The function name is followed by parentheses () and a colon :. The body of the function is indented, as with Python loops and conditionals for example.
def function_name(argument: int):
"""Calculates the inverse square root of a number"""
# Do something
result = argument * 2
# Return something
return result
Here is an example of a function that calculates the inverse square root of a number:
In [ ]:
Copied!
In [ ]:
Copied!
# Use it for any number
# Use it for a range of numbers
# Use it for any number
# Use it for a range of numbers
Reasons to use functions¶
- Define it once, use it everywhere - Re-usability across applications
- Reduce overhead code - Split complex code into a series of functions
- Standardize a process - Process A requires X,Y,Z and returns A,B,C
- Share your code - Functions can be imported from your scripts
Arguments and returns¶
In [ ]:
Copied!
# Functions can take input and return something
# Functions can take input and return something
Understanding the variable scope of functions¶
In [ ]:
Copied!
some_variable = "Outside"
some_list = [1, 2, 3, 3]
another_variable = "Outside"
def my_function(another_variable):
print("Calling non-argument variable: ", some_variable)
print("Calling argument variable: ", another_variable)
some_list.append(10)
my_function("Inside")
print("Variable outside of function: ", another_variable)
print("Changed variable: ", some_list)
some_variable = "Outside"
some_list = [1, 2, 3, 3]
another_variable = "Outside"
def my_function(another_variable):
print("Calling non-argument variable: ", some_variable)
print("Calling argument variable: ", another_variable)
some_list.append(10)
my_function("Inside")
print("Variable outside of function: ", another_variable)
print("Changed variable: ", some_list)
In [ ]:
Copied!
def take_a_number(number: str):
# Guardian clause
if isinstance(number, str) is False:
raise TypeError("This requires a string!!!!")
print(number)
def take_a_number(number: str):
# Guardian clause
if isinstance(number, str) is False:
raise TypeError("This requires a string!!!!")
print(number)
In [ ]:
Copied!
take_a_number("10.0")
take_a_number("10.0")
Tips on using functions¶
- Keep it simple, a function should only have one job.
- Dont hesitate defining multiple small functions instead of a big one
- Include at least a brief summary of what your function is doing
- Think about generalization - How can my function be applied to deviating cases?
- Put your functions in another script and import them to reduce overhead