Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 1

Defining Python Functions

Recommended resources

Welcome to your first lesson! Your journey to becoming a Full Stack AI Developer starts with mastering the fundamentals of Python. This course is designed to take you from the very beginning to an industry-ready level, and our first module, "Python Programming Foundations," will build the solid base you need for everything that follows.

In this lesson, we'll focus on one of the most essential concepts in any programming language: functions. You will learn how to write your own Python functions, complete with parameters to pass in data, return values to get results back, and docstrings to keep your code understandable and maintainable.

Functions are the building blocks of larger applications. In AI, you'll use them for everything from cleaning data and defining machine learning models to creating the API that serves your model to users. A strong grasp of functions is non-negotiable, and by the end of this lesson, you'll have it.

1. What Are Functions and Why Do We Use Them?

At its core, a function is a named, reusable block of code that performs a specific task. Instead of writing the same lines of code over and over, you can package them into a function and call it whenever you need it.

This practice offers several key advantages:

  • Reusability: Write the logic once and use it multiple times, saving you time and reducing the chance of errors from copy-pasting.
  • Modularity: Functions help you break down a complex problem into smaller, logical, and more manageable pieces. This makes your code cleaner and easier to read, test, and debug.
  • Abstraction: A function hides the complexity of its internal workings. You can use a function without needing to know every detail of its implementationβ€”you only need to know what it does, what inputs it needs, and what it gives back.

To get a better sense of why functions are so valuable, especially for a beginner, please read the following brief introduction.

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

This article from Jessica Miles provides an excellent, beginner-friendly explanation of why functions are a cornerstone of good programming.

Please read the section titled 'First, why write functions?'. Pay close attention to the three advantages the author highlights.


2. The Anatomy of a Python Function

Now, let's look at how you actually create a function in Python. The syntax is straightforward.

Python Functions Explained
This image breaks down the essential components of a Python function: the `def` keyword, the function name, parameters, the function body, and the `return` statement.

To see these components explained visually, let's watch a short video.

Python Functions - Visually Explained

This video from the 'Visually Explained' channel provides a clear, animated breakdown of how to define and call a function in Python.

Watch the video from the beginning until timestamp 02:53. Focus on understanding the roles of the def keyword, the function name, the parentheses (), the colon :, and the indented function body.

As you saw in the video, here’s a summary of the basic structure:

  1. def keyword: This signals the start of a function definition.
  2. Function Name: You choose a descriptive name for your function. The convention is to use snake_case (lowercase words separated by underscores).
  3. Parentheses (): These follow the function name and will hold the function's parameters, which we'll discuss next.
  4. Colon :: This marks the end of the function header.
  5. Function Body: The block of code that the function executes. It must be indented (typically by 4 spaces).

Here is a simple example:




# Function definition
def greet():
    print("Hello, welcome to your first function!")




# Function call
greet() 



# Output: Hello, welcome to your first function!

This function, greet, takes no inputs and doesn't return any value. It simply performs an action (printing a message). While useful, the real power of functions comes from their ability to process data.


3. Communicating with Functions

Functions become truly powerful when you can pass data into them and get results out of them.

Parameters and Arguments

You pass data into a function using parameters. When you call the function, the values you provide for those parameters are called arguments. It's a subtle but important distinction.

  • Parameters are the variables listed inside the parentheses in the function definition. They are placeholders for the data the function expects.
  • Arguments are the actual values you pass to the function when you call it.

The following video provides a detailed look at defining parameters and passing arguments, including different ways to do so.

Python Functions Deep Dive: Define, Call & Return Values

The 'Code with Gunnar' channel offers a deep dive into function parameters and arguments. This will clarify how to make your functions flexible.

Watch the section from 00:31 to 03:19. Pay close attention to the explanation of positional arguments, keyword arguments, and default values.

Let's summarize the key types of arguments from the video:

  • Positional Arguments: The arguments are matched to parameters based on their order.
    def introduce(name, age):
        print(f"This is {name}, and they are {age} years old.")
    
    introduce("Alex", 30) # "Alex" maps to name, 30 maps to age
    
  • Keyword Arguments: You explicitly name which parameter each argument corresponds to. The order no longer matters.
    introduce(age=30, name="Alex") # Same result as above
    
  • Default Arguments: You can provide a default value for a parameter. If an argument for that parameter isn't provided during the function call, the default value is used.
    def greet_user(name, greeting="Hello"):
        print(f"{greeting}, {name}!")
    
    greet_user("Maria") # Output: Hello, Maria!
    greet_user("David", "Good morning") # Output: Good morning, David!
    

The return Statement

To get a value out of a function, you use the return statement. When Python encounters a return statement, it immediately exits the function and sends the specified value back to where the function was called.

The next segment of the video you just watched explains this concept.

Python Functions Deep Dive: Define, Call & Return Values

Let's continue with the 'Code with Gunnar' video to understand how to get data back from our functions.

Watch the section from 03:19 to 04:43. Focus on how return sends a value back, how to return multiple values, and what happens if you don't have a return statement.

Key points about return:

  • A function can return any kind of data: a number, a string, a list, even another function.
  • If you don't include a return statement, the function implicitly returns None.
  • You can return multiple values by separating them with commas. Python automatically packs them into a tuple.

Here's an example combining parameters and a return value:

def calculate_area(length, width):
    """Calculates the area of a rectangle."""
    area = length * width
    return area




# Call the function and store the returned value in a variable
rect_area = calculate_area(10, 5)
print(f"The area is: {rect_area}") # Output: The area is: 50

4. Documenting Your Functions with Docstrings

Writing code is only half the battle. You also need to make sure it's understandable for other developers, and for your future self! Docstrings are the standard way to document Python functions.

A docstring is a string literal that occurs as the first statement in a function's body. It's enclosed in triple quotes ("""...""" or '''...''').

Python Functions Deep Dive: Define, Call & Return Values

The final part of this video covers the professional practice of documenting your functions with docstrings.

Watch from 04:43 to the end (05:33). Observe the syntax and the recommended content for a good docstring.

A good docstring briefly explains:

  1. What the function does.
  2. What arguments it takes (Args: or Parameters:).
  3. What it returns (Returns:).

Here is our calculate_area function with a complete docstring:

def calculate_area(length, width):
    """Calculates the area of a rectangle.

    Args:
        length (int or float): The length of the rectangle.
        width (int or float): The width of the rectangle.

    Returns:
        int or float: The calculated area of the rectangle.
    """
    if length < 0 or width < 0:
        return 0 # A simple check to handle invalid input
    
    area = length * width
    return area




# You can access the docstring using the help() function
help(calculate_area)

Practice: Putting It All Together

Now it's your turn. Let's write a function from scratch that incorporates everything we've learned.

Your task: Write a Python function named get_final_price that calculates the final price of an item after applying a discount.

Requirements:

  1. The function should accept two parameters: original_price and discount_percent.
  2. It should have a default discount_percent of 10.
  3. The function should calculate the discounted price and return it.
  4. Include a complete docstring that describes the function, its parameters, and what it returns.

Try to write this yourself in a code editor. Once you're done, you can compare your solution to the one below.

Click here to see a possible solution
def get_final_price(original_price, discount_percent=10):
    """Calculates the final price after applying a discount.

    Args:
        original_price (float): The starting price of the item.
        discount_percent (float, optional): The discount percentage. 
                                            Defaults to 10.

    Returns:
        float: The price after the discount is applied.
    """
    if not (0 <= discount_percent <= 100):
        print("Warning: Discount must be between 0 and 100.")
        return original_price

    discount_amount = original_price * (discount_percent / 100)
    final_price = original_price - discount_amount
    return final_price




# --- Example Usage ---




# Using the default discount
price1 = get_final_price(200)
print(f"Price with default 10% discount: ${price1:.2f}") # Output: $180.00




# Specifying a different discount
price2 = get_final_price(200, 25)
print(f"Price with 25% discount: ${price2:.2f}") # Output: $150.00




# Using keyword arguments
price3 = get_final_price(discount_percent=50, original_price=200)
print(f"Price with 50% discount: ${price3:.2f}") # Output: $100.00

Conclusion

Congratulations on completing your first lesson! You've taken a significant step in building your Python programming foundation.

Here are the key takeaways:

  • Functions are reusable, named blocks of code defined with the def keyword.
  • They help make your code modular, readable, and less error-prone.
  • You pass data into functions using parameters, for which you provide arguments when you call the function.
  • The return statement sends a value back from a function and exits it.
  • Docstrings ("""...""") are the professional standard for documenting what your functions do.

Mastering functions is about learning to think in a more structured way. As you build more complex programs, you'll constantly be asking yourself, "Can I turn this logic into a function?" The answer will almost always be yes.

In our next lesson, we will explore list comprehensions and generator expressions. These are powerful, concise Python features for creating and processing sequences of data, which you will often use to prepare data before passing it into the functions you now know how to write.