Functions

As in mathematics, where functions take inputs and produce outputs, programming functions perform similarly. They take inputs, execute predefined actions or calculations, and then return an output. Functions can accept and return data types, objects and even other functions as arguments.

Benefits of using functions

Modularity: Functions break down complex tasks into manageable components
Reusability: Functions can be used multiple times without rewriting code
Readability: Functions with meaningful names enhance code understanding
Debugging: Isolating functions eases troubleshooting and issue fixing
Abstraction: Functions simplify complex processes behind a user-friendly interface
Collaboration: Team members can work on different functions concurrently
Maintenance: Changes made in a function automatically apply wherever it’s used

Built-in Python functions we are very familiar with such as: len(), sum() max(), min()….

Define

  • def function_name(paramaters) is how you define the function and assign it a name
  • note the : and indentation
  • parameters/arguments if any are placed inside the ( )
def function_name():
        pass
  • Here is a simple example
def greeting(name):
        print("Hello "+ name )
        
greeting("Santa")
Hello Santa
  • The values returned from the function can be assigned to a variable and used for other conditions
answer = greeting("Cowboy")
print("What did you say? ", answer)
Hello Cowboy
What did you say?  None

Docstrings

  • Documentation strings (docstrings) explain what a function does
  • Place it inside ’’’’’ triple quotes right after the definition of the function
  • Helps other developers understand your code
  • Docstring MUST be indented
def add(a):
    """
    add 1 to a
    """
    b = a + 1
    print(a, "if you add one", b)
    return(b)

Return

  • Return gives back a value from a function
  • Ends the function’s execution and sends the result
  • A function can return various types of data
def add(a, b):
    return a + b
sum_result = add(3, 5)  # sum_result gets the value 8

Scope & Variable

Global Scope

Scope is where a variable can be seen and used:

  • Global Scope: Variables defined outside functions; accessible everywhere
    • Global variables are declared outside or inside the function, usually before the function definition
  • Local Scope: Variables inside functions; only usable within that function
    • Local variables are declared inside the function

Global variables are accessible throughout the entire program, both inside and outside functions.

# This initiates a global variable called global_variable and assigns it a value
global_variable = "I'm global"

Local Scope

  • Local variables are declared inside the functions they are local to
  • They cannot be used outside that functions
  • Since they are local, you can declare them as local to other functions, as long as you redefine them locally
  • As you see in the example below, the entire script can have access to the global_variable, but that certain function can have access to its local variable
  • Variables we create in the function is a local variable, meaning that the variable assignment does not persist outside the function.

Local variables are only visible and accessible within the scope of the function where they are defined.

def example_function():
    local_variable = "I'm local"
    print(global_variable)  # Accessing global variable
    print(local_variable)   # Accessing local variable
  • Now let’s call the example_function which will access the global_variable from within it
  • Note: this function does not require any parameters/arguments to be passed
example_function()
I'm global
I'm local

Global within function

artist = "Michael Jackson"

def printer(artist):
    global internal_var 
    internal_var= "Whitney Houston"
    print(artist,"is an artist")

printer(artist) 
printer(internal_var)
Michael Jackson is an artist
Whitney Houston is an artist

Access Global

  • Access global variable from outside the function
print(global_variable)
I'm global
  • Access local variable from outside its function
print(local_variable)

# OUTPUT
NameError: name 'local_variable' is not defined

Loops


Of course functions can contain loops which help

  • complex tasks more organized
  • the loop code can be repeatable and usable with other script files (will get to that later)
  • Functions group similar actions for easy understanding
  • Notice the double set of indentation, one for the function, and one for the for loop
  • Also note that return is not needed in all functions
def print_numbers(limit):
    for i in range(1, limit+1):
        print(i)
        
print_numbers(5)
1
2
3
4
5

Arguments

Default

  • You can set a default value for arguments in your function.
  • For example, in the isGoodRating() function, what if we wanted to create a threshold for what we consider to be a good rating?
  • Perhaps by default, we should have a default rating of 4
# Example for setting param with default value

def isGoodRating(rating=4): 
    if(rating < 7):
        print("this album sucks it's rating is",rating)
        
    else:
        print("this album is good its rating is",rating)
  • Test the function with and without passing an argument
isGoodRating()
isGoodRating(10)
this album sucks it's rating is 4
this album is good its rating is 10

Arg. Tuple

  • When the number of arguments are known for a function, they can all be packed into a tuple
  • We express that in the function definition as def function_name(*args):
  • This way you can pass 1 argument, 2, 7, or 100 arguments in the tuple
# All the arguments are 'packed' into *args a tuple

def printAll(*args):
    print("No of arguments:", len(args)) 
    for argument in args:
        print(argument)
        
# call the function with the 3 element tuple
printAll('Horsefeather','Adonis','Bone')
No of arguments: 3
Horsefeather
Adonis
Bone
# Call the function with a 5 element tuple
printAll('Horsefeather','Adonis','Bone','Santa','Claus')
No of arguments: 5
Horsefeather
Adonis
Bone
Santa
Claus

Arg. Dictionary

  • Similarly we can pack the arguments into a dictionary
  • Note the (**args) to denote a dictionary
# Pack the args into a dictionary, note the **args
def printDictionary(**args):
    for key in args:
        print(key + " : " + args[key])

printDictionary(Country='Canada',Province='Ontario',City='Toronto')
Country : Canada
Province : Ontario
City : Toronto

Arg. List

  • Here we pass a list as argument
  • list is a reference so be very careful that list is not used somewhere else that might affect the value of the argument
def addItems(list):
    list.append("Three")
    list.append("Four")

myList = ["One","Two"]

addItems(myList)

myList
['One', 'Two', 'Three', 'Four']

Examples


List Examples

Add & remove from list

  • Use a list as the initial data structure and create a function to
  • add and remove elements from that list
# Initialize an empty list
my_list = []


# Define function to add elements to the list
def add_element(data_structure, element):
        data_structure.append(element)
        
        
# Define function to remove element from the list
def remove_element(data_structure, element):
        if element in data_structure:
                data_structure.remove(element)
        else:
                print(f"{element} not found in the list.")
  • Add elements to the list
  • View the list
add_element(my_list, 42)
add_element(my_list, 17)
add_element(my_list, 99)

print("Current list: ", my_list)
Current list:  [42, 17, 99]
  • Remove elements from the list
  • View the list
remove_element(my_list, 17)

print("Current list: ", my_list)
Current list:  [42, 99]
  • Let’s attempt to remove an element not in the list to verify our if else statement is accurate
# Let's attempt to remove an element not in the list
remove_element(my_list, 154)
154 not found in the list.
  • Print the final list
print("Final list is: ", my_list)
Final list is:  [42, 99]

Compare strings w in

# Compare Two Strings Directly using in operator 

# Declare string
string= "Michael Jackson is the best"

# Define a funtion
def check_string(text):
    
# Use if else statement and 'in' operatore to compare the string
    if text in string:
        return 'String matched'
    else:
        return 'String not matched'

# Call the function on the string below
check_string("Michael Jackson is the best")
'String matched'

Compare strings w ==

# Compare two strings using == operator and function

# Define the function
def compareStrings(x, y):
# Use if else statement to compare x and y
    if x==y:
        return 1
    
# Declare two different variables as string1 and string2 
string1 = "Michael Jackson is the best"
string2 = "Michael Jackson is the best"

# Declare a variable to store result after comparing both the strings
check = compareStrings(string1, string2)

#Use if else statement to compare the string
if check==1:
    print("\nString Matched")
else:
    print("\nString not Matched")

String Matched

Dictionary Examples

Count Occ of Every Word

  • Count the occurrence of every word in our string using a dictionary
# Count words in a String using Dictionary

# Define the function
def freq(string):
    
    #step1: A list variable is declared and initialized to an empty list.
    words = []
    
    #step2: Break the string into list of words
    words = string.split() # or string.lower().split()
    
    #step3: Declare a dictionary
    Dict = {}
    
    #step4: Use for loop to iterate words and values to the dictionary
    for key in words:
        Dict[key] = words.count(key)
        
    #step5: Print the dictionary
    print("The Frequency of words is:",Dict)

    
# Call the function and pass string in it
freq("Mary had a little lamb Little lamb, little lamb Mary had a little lamb.Its fleece was white as snow And everywhere that Mary went Mary went, Mary went \
Everywhere that Mary went The lamb was sure to go")
The Frequency of words is: {'Mary': 6, 'had': 2, 'a': 2, 'little': 3, 'lamb': 3, 'Little': 1, 'lamb,': 1, 'lamb.Its': 1, 'fleece': 1, 'was': 2, 'white': 1, 'as': 1, 'snow': 1, 'And': 1, 'everywhere': 1, 'that': 2, 'went': 3, 'went,': 1, 'Everywhere': 1, 'The': 1, 'sure': 1, 'to': 1, 'go': 1}

Count Occ or One Word

  • If we want to count the occurrence one one key/word passed as argument we just edit the above code block slightly to
  • include the passed key as argument and test for it conditionally
# Count the occurrence of one key/word in a String using Dictionary

# Define the function
def freq(string,passed_key):
    
    #step1: A list variable is declared and initialized to an empty list.
    words = []
    
    #step2: Break the string into list of words
    words = string.split() # or string.lower().split()
    
    #step3: Declare a dictionary
    Dict = {}
    
    #step4: Use for loop to iterate words and values to the dictionary
    for key in words:
        if key == passed_key:       # count the occurrence only if condition is True
                Dict[key] = words.count(key)
        
    #step5: Print the dictionary
    #print(f"{passed_key} Occurs: ",Dict," times")
    # The above prints out: little Occurs: {'little': 3} times
    
    # Let's just print out the count of occurrence without the dictionary
    print(f"{passed_key} Occurs: ",Dict[passed_key]," times")

    
# Call the function and pass string in it
freq("Mary had a little lamb Little lamb, little lamb Mary had a little lamb.Its fleece was white as snow And everywhere that Mary went Mary went, Mary went \
Everywhere that Mary went The lamb was sure to go","little")
little Occurs:  3  times