Skip to main content

Someone wanted to learn this too, so Grasp built them a personal learning path.

You can keep exploring this one or create your own

Functions: Parameters & Return Values

Hello! In our last session, we built a word frequency counter using dictionaries. While effective, imagine you needed to count frequencies for ten different texts. You'd have to copy and paste that same block of code ten times, a process that is both tedious and prone to error. This is where functions become indispensable.

This lesson addresses exactly that problem. You will learn how to define your own Python functions with parameters and return values. This is one of the most important concepts in programming, as it allows you to package code into reusable, organized, and powerful blocks. Mastering functions is a critical step on our path to building the sophisticated, multi-component NLP applications you're interested in, like chatbots and text processors.

What is a Function and Why Use One?

At its core, a function is a named block of code designed to perform a specific task. Instead of rewriting the code every time you need the task done, you simply "call" the function by its name.

The most obvious benefit is code reusability, but functions also bring clarity and organization to your programs. By breaking a large problem down into smaller, manageable tasks, each handled by a specific function, your code becomes easier to read, test, and maintain.

The article "Writing Functions in Python" explains this philosophy well. It introduces the idea of thinking of a function as a tool you build for a specific job.

Writing Functions in Pythonβ€” A Beginner's Guide

Please read the introduction and the section "First, why write functions?".

Start by reading the definition of a function, from the first paragraph. Then, focus on the section Why Write Functions?, which highlights the advantages beyond simple code reuse. The author's analogy of building a tool, starting with a simple rock and gradually improving it, is particularly useful.

The Anatomy of a Python Function

Now that you understand the "why," let's look at the "how." A function has a specific structure. The image below from Pynative breaks down a simple Python function into its core components.

This diagram shows the essential parts of a Python function: the `def` keyword to start the definition, a unique function name, parentheses for parameters, an indented function body where the logic resides, and an optional `return` statement to send a value back.

Let's break these parts down:

  1. def keyword: This signals the start of a function definition.
  2. Function Name: A unique, descriptive name that follows Python's variable naming rules (e.g., calculate_average).
  3. Parameters: Variables listed inside the parentheses (). They act as placeholders for the data you will pass into the function when you call it. A function can have zero or more parameters.
  4. Colon :: Marks the end of the function header.
  5. Function Body: An indented block of code that performs the function's task.
  6. return statement: (Optional) Sends a result back to wherever the function was called.

A short video from the Bro Code channel provides a great dynamic introduction to defining and calling your first function.

Functions in Python are easy πŸ“ž

This video clearly demonstrates the basic syntax and the concept of passing data to a function.

Watch the first two parts of the video. First, watch the segment on defining and calling a function to see how a simple block of code is made reusable. Next, focus on how to pass arguments to parameters. Pay close attention to the distinction between parameters (the placeholders in the function definition) and arguments (the actual values you provide when calling the function).

Getting a Result: The return Statement

Many functions perform a calculation or a transformation and need to send a result back. A function that just prints a value to the screen is of limited use, because you can't use that printed value in other parts of your code. The return statement is how a function hands back its result.

This is a fundamental concept, and the distinction between print() and return inside a function is a very common point of confusion for beginners.

  • print() is for display purposes only. It shows a value on the screen for a human to see.
  • return actually outputs a value from the function that your program can capture in a variable and use for further processing.
This diagram illustrates the flow of control for a function that returns a value. When `find_square(3)` is called, the value `3` is passed to the `num` parameter. The function calculates the result and the `return` statement sends that result back, where it is assigned to the `square` variable.

Let's watch two short videos that make this difference crystal clear. The first continues the Bro Code video, and the second, from Coding with Estefania, is entirely dedicated to this topic.

Functions in Python are easy πŸ“ž

This video will show you how to use return to get a value back from a function.

Watch the section on the return statement. Notice how the result of the add, subtract, and multiply functions is captured in a variable and then printed.

Now, let's solidify this concept. The next video is short and exceptionally clear about what happens when a function doesn't have a return statement.

print() vs. return in Python Functions

This video provides a direct comparison of print vs. return.

Watch the entire video. It first explains how return works by storing the output in a variable. Then, it shows what happens when you only use print, and why the function implicitly returns None. The final recap summarizes the key difference.

By default, if you don't include a return statement, a Python function automatically returns a special value called None. This is why trying to assign the result of a print-only function to a variable gives you None.

Your First Function: From Script to Reusable Tool

Let's apply this step-by-step approach to the word frequency counter you built in the previous lesson. We will transform it from a one-off script into a reusable function.

Here's the code from last time:




# The original script
words = ['like', 'a', 'rose', 'a', 'rose', 'is', 'a', 'rose']

word_counts = {}

for word in words:
    if word in word_counts:
        word_counts[word] = word_counts[word] + 1
    else:
        word_counts[word] = 1

print(word_counts)



# Output: {'like': 1, 'a': 3, 'rose': 3, 'is': 1}

Now, let's package this logic into a function called count_word_frequency.

  1. Define the function signature: We need a function that accepts one piece of data: a list of words. We'll call the parameter text_list.
    def count_word_frequency(text_list):
    
  2. Add the function body: Copy the logic from your script and indent it so it's inside the function.
    def count_word_frequency(text_list):
        word_counts = {}
    
    
    
    
        # The parameter `text_list` is used here instead of the hardcoded `words`
        for word in text_list:
            if word in word_counts:
                word_counts[word] = word_counts[word] + 1
            else:
                word_counts[word] = 1
    
  3. Return the result: Instead of printing the dictionary, we'll return it so we can use it elsewhere.
    def count_word_frequency(text_list):
        word_counts = {}
        for word in text_list:
            if word in word_counts:
                word_counts[word] = word_counts[word] + 1
            else:
                word_counts[word] = 1
        
        return word_counts # Return the dictionary
    
  4. Call the function and use its result: Now you can call your function with any list of words and store the returned dictionary in a variable.
    sentence1 = ['this', 'is', 'the', 'first', 'sentence']
    sentence2 = ['this', 'is', 'another', 'sentence', 'a', 'second', 'sentence']
    
    
    
    
    # Call the function for the first sentence
    freq1 = count_word_frequency(sentence1)
    print("Frequencies for sentence 1:", freq1)
    
    
    
    
    # Call the same function for the second sentence
    freq2 = count_word_frequency(sentence2)
    print("Frequencies for sentence 2:", freq2)
    

Notice how we defined the logic once and reused it for two different inputs. This is the power of functions.

Your Turn: Calculate Word Percentage

Now it's your turn to build a function from scratch. This exercise is inspired by the NLTK book, a classic resource in Natural Language Processing.

Task:
Define a function named calculate_percentage that takes two arguments: a word (a string) and a text_list (a list of strings). The function should calculate how often the given word appears in the text list and return the result as a percentage.

The formula is:

For example, if the word is "rose" and the list is ['a', 'rose', 'is', 'a', 'rose'], the count of "rose" is 2 and the total number of words is 5. The percentage is .

Instructions:

  1. Define a function calculate_percentage that accepts two parameters: word and text_list.
  2. Inside the function, get the total number of words in text_list using the len() function.
  3. Inside the function, count how many times word appears in text_list. You can do this with a for loop and a counter variable, or you can use the built-in list method .count(). For example, text_list.count(word).
  4. Calculate the percentage using the formula above. Be careful: if the list is empty, you'll be dividing by zero, which causes an error. Add an if statement to check if the total number of words is 0. If it is, return 0.0.
  5. Return the calculated percentage.

Use the starter code below to complete your task.

def calculate_percentage(word, text_list):



    # 1. Get the total number of words
    total_words = len(text_list)
    



    # 2. Handle the case of an empty list to avoid division by zero
    if total_words == 0:
        return 0.0
    



    # 3. Count the occurrences of the specific word
    word_count = text_list.count(word)
    



    # 4. Calculate the percentage
    percentage = (word_count / total_words) * 100
    



    # 5. Return the final result
    return percentage




# --- Test your function ---
my_text = ['a', 'rose', 'is', 'a', 'rose']




# Calculate percentage for the word 'rose'
rose_percentage = calculate_percentage('rose', my_text)
print(f"The word 'rose' makes up {rose_percentage}% of the text.")




# Calculate percentage for the word 'a'
a_percentage = calculate_percentage('a', my_text)
print(f"The word 'a' makes up {a_percentage}% of the text.")




# Test with an empty list
empty_percentage = calculate_percentage('hello', [])
print(f"The percentage in an empty list is: {empty_percentage}%")

Conclusion

In this lesson, you've learned one of the most fundamental skills in programming: how to create and use functions. By encapsulating logic into named, reusable blocks, you can write cleaner, more organized, and more powerful code.

Key takeaways from today:

  • Functions promote reusability and organization. They are the building blocks of larger programs.
  • Functions are defined with the def keyword, followed by a name, parameters in (), and a colon.
  • Parameters are the placeholders in a function's definition, while arguments are the actual values passed to the function when it's called.
  • The return statement is used to send a value back from a function, allowing you to use the function's output in other parts of your code. A function without an explicit return statement returns None.

You now have a solid grasp of Python's main data structures (lists and dictionaries) and the primary way of structuring code (functions). In our next lesson, we'll dive deeper into how to effectively combine these concepts, focusing on iterating over lists and dictionaries to process collections of dataβ€”a skill that is absolutely essential for the text preprocessing pipelines we will soon be building.

Can't find a good explanation? Sign up and we'll make it for you

Sign up