Seminar 003: Functions in Python¶
Notes¶
In [1]:
Copied!
# Merging dictionaries
dict1 = {"Hello": "World"}
dict2 = {"Foo": "Bar"}
merged = {}
dict_list = [dict1, dict2]
for entry in dict_list:
for key, value in entry.items():
merged[key] = value
merged
# Merging dictionaries
dict1 = {"Hello": "World"}
dict2 = {"Foo": "Bar"}
merged = {}
dict_list = [dict1, dict2]
for entry in dict_list:
for key, value in entry.items():
merged[key] = value
merged
Out[1]:
{'Hello': 'World', 'Foo': 'Bar'}
In [2]:
Copied!
# Pythonic merging of dictionaries
dict1 = {"Hello": "World"}
dict2 = {"Foo": "Bar"}
merged = {
**dict1,
**dict2,
}
merged
# Pythonic merging of dictionaries
dict1 = {"Hello": "World"}
dict2 = {"Foo": "Bar"}
merged = {
**dict1,
**dict2,
}
merged
Out[2]:
{'Hello': 'World', 'Foo': 'Bar'}
In [6]:
Copied!
# Pythonic way of merging lists
list1 = [1,2,3,4]
list2 = [5,6,7,8]
all_list = [*list1, *list2]
all_list
# Pythonic way of merging lists
list1 = [1,2,3,4]
list2 = [5,6,7,8]
all_list = [*list1, *list2]
all_list
Out[6]:
[1, 2, 3, 4, 5, 6, 7, 8]
Functions¶
Why?¶
In [7]:
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
# Copy and past or even re-writing can be quite faulty!
# Dont let you trick from this simple example
print(number_5)
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
# Copy and past or even re-writing can be quite faulty!
# Dont let you trick from this simple example
print(number_5)
0.4472135954999579
Use a function¶
In [8]:
Copied!
def get_inverse_square_root(number: int):
"""Calculates the inverse square root of a number"""
result = 1 / math.sqrt(number)
return result
def get_inverse_square_root(number: int):
"""Calculates the inverse square root of a number"""
result = 1 / math.sqrt(number)
return result
In [10]:
Copied!
inv_sqrt = get_inverse_square_root(19892)
print(inv_sqrt)
inv_sqrt = get_inverse_square_root(19892)
print(inv_sqrt)
0.007090237366685696
In [ ]:
Copied!
for i in range(1, 100):
inv_sqrt = get_inverse_square_root(i)
print(inv_sqrt)
# "0.3456\n"
# do something else
for i in range(1, 100):
inv_sqrt = get_inverse_square_root(i)
print(inv_sqrt)
# "0.3456\n"
# do something else
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 [12]:
Copied!
# Functions can take input and return something
def my_function(arguments):
# do something
print("Inside function has arguments: ", arguments)
return "something"
returned= my_function("Hello")
print("Function returned: ", returned)
# Functions can take input and return something
def my_function(arguments):
# do something
print("Inside function has arguments: ", arguments)
return "something"
returned= my_function("Hello")
print("Function returned: ", returned)
Inside function has arguments: Hello Function returned: something
Understanding the variable scope¶
In [13]:
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)
Calling non-argument variable: Outside Calling argument variable: Inside Variable outside of function: Outside Changed variable: [1, 2, 3, 3, 10]
In [16]:
Copied!
def take_a_number(number: str):
# Guardian clause
if isinstance(number, str) == False:
raise TypeError("This requires a string!!!!")
print(number)
def take_a_number(number: str):
# Guardian clause
if isinstance(number, str) == False:
raise TypeError("This requires a string!!!!")
print(number)
In [18]:
Copied!
take_a_number("10.0")
take_a_number("10.0")
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