Functions

Functions

What is a function?

  • A function is a block of code that only runs when it is called.
  • It can take arguments and return data as a result.
  • But doesn’t have to
  • It is a way to organize code and make it reusable.

Defining a function

  • A function is defined using the def keyword.
  • The function name is followed by parentheses and a colon.
  • The code block that makes up the function is indented.

Defining a Function, Example

def my_function():
    print("Hello from a function")

or

def another_function(string, number):
    num = str(number)
    print(string + num) 

Calling a function

  • We can create a variable that holds the result of a function.
def convert_to_celsius(fahrenheit):
    celsius = (fahrenheit - 32) * 5.0 / 9.0
    return celsius


f_deg = 85
c_deg = convert_to_celsius(f_deg)
print(f_deg, "Fahrenheit is", c_deg, "Celsius")
85 Fahrenheit is 29.444444444444443 Celsius

Arguments and Results are not necessary

def helloworld():
    print("Hello World")


helloworld()
Hello World

Anonymous functions: Lambda

  • A lambda function is a small anonymous function.
  • A lambda function can take any number of arguments,
  • A lambda can only have one expression.
f_deg = 85
convert = lambda f: (f - 32) * 5.0 / 9.0
add = lambda x, y: x + y
print(convert(f_deg))
print(add(5, 3))
29.444444444444443
8

Functions in DFs with apply

import pandas as pd

columns = ["name", "age", "city", "avg_temp"]
data = [
    ["Alice", 24, "Toronto", 72],
    ["Bob", 34, "New York", 74],
    ["Charlie", 45, "Los Angeles", 88],
]
df = pd.DataFrame(data, columns=columns)
df["age"] = df["age"].apply(lambda x: x + 1)
df
name age city avg_temp
0 Alice 25 Toronto 72
1 Bob 35 New York 74
2 Charlie 46 Los Angeles 88

Functions in DFs with apply, cont.

import pandas as pd
columns = ["name", "age", "city", "avg_temp"]
data = [
    ["Alice", 24, "Toronto", 72],
    ["Bob", 34, "New York", 74],
    ["Charlie", 45, "Los Angeles", 88],
]
df = pd.DataFrame(data, columns=columns)
def convert_to_celsius(f):
    celsius = (f - 32) * 5.0 / 9.0
    return round(celsius, 2)
df["avg_temp"] = df["avg_temp"].apply(convert_to_celsius)
df
name age city avg_temp
0 Alice 24 Toronto 22.22
1 Bob 34 New York 23.33
2 Charlie 45 Los Angeles 31.11

Reusing our Functions

  • We can save our functions in a separate file and import them.
  • Must save as .py file NOT .ipynb
  • We can import the file as a module and use the functions.
  • NOTATION: from {filename} import {function}

With Colab

  • Open a text editor (Notepad, Visual Studio Code, etc.)
  • copy function and paste in editor
  • Save file as some_name.py
  • upload file to Colab Notebooks folder in Google Drive
  • mount drive
  • import sys
  • sys.path.append('/content/drive/MyDrive/Colab Notebooks')
  • from some_name import function_name

Example

# test_fn.py
def convert_to_celsius(f):
    celsius = (f - 32) * 5.0 / 9.0
    return round(celsius, 2)

Then in Colab…

from google.colab import drive
drive.mount("/content/drive/")
import sys
sys.path.append('/content/drive/MyDrive/Colab Notebooks')
from test_fn import convert_to_celsius

f = 92
print(convert_to_celsius(f))