Skip to main content

Welcome to a Grasp lesson

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

Lesson 7

Creating and Using Functions

Recommended resources

Hello! Welcome to the seventh lesson in your "AI Automation" course.

In our last lesson, we explored for and while loops, which gave you the power to automate repetitive tasks by executing code multiple times. This is a cornerstone of automation. Now, as our scripts get more complex, we need a way to keep them organized, readable, and efficient.

Today, we will learn how to define and call functions. A function is a named, reusable block of code that performs a specific task. By organizing our code into functions, we can make our automation scripts cleaner, easier to debug, and much more powerful.

Since you have experience with C, the concept of a function will be familiar. The main goal today is to master how functions work in Python, paying close attention to its unique syntax and features.

1. Why Use Functions? The Art of Reusable Code

Before we dive into the syntax, let's understand why functions are so important in programming. At its core, a function allows you to write a piece of code once and then use it over and over again.

Imagine from your storekeeper experience that you frequently need to check if a product is close to its expiry date. Instead of copying and pasting the same checking logic everywhere, you can put it inside a function called check_expiry(). This has several advantages:

  • Reusability: You can call check_expiry() for any product, saving you from rewriting code.
  • Readability: Your main script becomes simpler. A line like check_expiry(product) is easier to understand than a big block of logic.
  • Maintainability: If you need to change how the expiry check works (e.g., change the warning period from 30 days to 45 days), you only need to update it in one place: inside the function.

Writing Functions in Python— A Beginner's Guide | by Jessica Miles

This article, 'Writing Functions in Python— A Beginner's Guide' by Jessica Miles, provides an excellent explanation of the benefits of using functions. It will help you understand the motivation behind organizing your code this way.

Read the first section titled 'First, why write functions?'. Pay attention to the three main advantages it lists: avoiding errors, managing complexity ('freeing up mental capacity'), and applying logic consistently.


2. Defining and Calling a Function

Now, let's look at the syntax. In C, you define a function with a return type, a name, and curly braces {}. Python's syntax is a bit different, relying on the def keyword and indentation.

This image breaks down the syntax visually:

Python Function Syntax Explained
This image shows the basic components of a Python function: the `def` keyword, the function name, arguments (parameters), the colon, the indented function body, and the optional `return` statement.

Here's a direct comparison to what you know from C.

Python and C - Comparisons and C - Rose-Hulman

This comparison table from Rose-Hulman Institute of Technology directly shows the difference in function syntax between Python and C. It's a quick way to map your existing knowledge to Python.

In the table, find the row for 'simple function definition'. Compare the Python code on the left with the C code on the right. Notice Python's use of def, the colon :, and indentation instead of void and curly braces {}.

To see this in action, let's watch a short video that demonstrates how to define and call a very simple function.

Functions in Python are easy 📞

This video from the Bro Code channel gives a quick, no-nonsense introduction to defining and calling functions.

Watch from the beginning to 01:47. The 'Happy Birthday' example clearly shows how a function prevents you from repeating code and how you can 'invoke' or 'call' it multiple times.


3. Making Functions Flexible with Parameters and Arguments

A function becomes truly powerful when you can pass data into it. For example, a greet() function is more useful if it can greet different people by name.

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

Python Functions | Python Tutorial for Absolute Beginners #1

Programming with Mosh has a great explanation of the difference between parameters and arguments, which is a key concept to understand.

Watch from 02:34 to 04:16. Mosh clearly explains that parameters are the 'placeholders' in the function definition, and arguments are the 'actual values' you supply when you call it.

When you call a function, the arguments you provide are assigned to the parameters in order.

# 'name' and 'product_id' are parameters
def log_order_preparation(name, product_id):
    print(f"Preparing order for {name}, Product ID: {product_id}.")

# 'Alice' and 101 are positional arguments
log_order_preparation("Alice", 101) 
# Output: Preparing order for Alice, Product ID: 101.

# 'Bob' and 205 are positional arguments
log_order_preparation("Bob", 205)
# Output: Preparing order for Bob, Product ID: 205.

Keyword Arguments and Default Values

Python offers more flexibility. You can also pass arguments by specifying the parameter name. These are called keyword arguments. The advantage is that their order doesn't matter, which makes your code more readable.

You can also provide a default value for a parameter, making it optional.

Python Functions | Python Tutorial for Absolute Beginners #1

Let's continue with Mosh's video to see how to use keyword arguments and set up optional parameters with default values.

Watch from 10:02 to 12:22. Notice how keyword arguments (by=1) make the function call easier to read. Also, see how setting a default value (by=1 in the function definition) makes that parameter optional.

Here's an example:

# 'status' is an optional parameter with a default value
def update_inventory(product, quantity, status="In Stock"):
    print(f"Product: {product}, Quantity: {quantity}, Status: {status}")

# Calling with only the required arguments
update_inventory("Scanner", 50)
# Output: Product: Scanner, Quantity: 50, Status: In Stock

# Overriding the default value by providing a third argument
update_inventory("Printer", 10, "Low Stock")
# Output: Product: Printer, Quantity: 10, Status: Low Stock

# Using keyword arguments (order doesn't matter)
update_inventory(quantity=5, product="Keyboard", status="Backordered")
# Output: Product: Keyboard, Quantity: 5, Status: Backordered
Test your understanding!

You need to create a function to generate a report summary line.

  1. Define a function called create_summary that takes two parameters: report_name and author.
  2. The function should print a string like: Summary for 'Monthly Sales' by 'Admin'.
  3. Call the function with a report name "Daily Inventory" and your name as the author.
  4. Now, modify the function to make the author parameter optional, with a default value of "System".
  5. Call the function again, but this time only provide the report_name "Error Log".
Show answer
# Step 1-3: Initial function
def create_summary(report_name, author):
    print(f"Summary for '{report_name}' by '{author}'.")

create_summary("Daily Inventory", "Amine")
# Expected output: Summary for 'Daily Inventory' by 'Amine'.

print("---") # Separator

# Step 4-5: Modified function with default parameter
def create_summary(report_name, author="System"):
    print(f"Summary for '{report_name}' by '{author}'.")

create_summary("Error Log")
# Expected output: Summary for 'Error Log' by 'System'.

4. Getting Data Back with return

Functions can be divided into two main types:

  1. Functions that perform a task: Like print(), they do something but don't give you a value back.
  2. Functions that calculate and return a value: They process inputs and send a result back to where they were called.

To send a value back, you use the return statement.

Python Functions | Python Tutorial for Absolute Beginners #1

This concept is fundamental. Mosh explains the two types of functions and how the return statement works.

Watch from 04:43 to 09:28. This is a key section. Pay close attention to: The difference between printing a value inside a function and returning it. Why returning a value is more flexible (you can store it, print it, write it to a file, etc.). What None means (it's the default return value for functions that don't explicitly return anything).

When a function returns a value, you can store that value in a variable for later use.

# This function calculates and returns a value
def calculate_vat(price):
    vat_amount = price * 0.20
    return vat_amount

# Call the function and store the returned value
item_price = 150
tax = calculate_vat(item_price)
total_price = item_price + tax

print(f"Item price: {item_price}")
print(f"VAT: {tax}")
print(f"Total price: {total_price}")

# Expected output:
# Item price: 150
# VAT: 30.0
# Total price: 180.0
Test your understanding!

Write a function that takes a first name and a last name and returns a full name.

  1. Define a function format_full_name that accepts first_name and last_name.
  2. Inside the function, combine them into a single string with a space in between.
  3. Use the return statement to send this full name string back.
  4. Call the function with your first and last names and store the result in a variable called my_full_name.
  5. Print the my_full_name variable.
Show answer
def format_full_name(first_name, last_name):
    full_name = f"{first_name} {last_name}"
    return full_name

# Call the function and capture the return value
my_full_name = format_full_name("Amine", "El Aabidi")

# Print the captured value
print(my_full_name)

# Expected output:
# Amine El Aabidi

5. Best Practices: Scope and Documentation

As you write more functions, two concepts will help you avoid common bugs: scope and documentation.

Variable Scope: A variable created inside a function (a "local variable") only exists within that function. This is a good thing! It prevents functions from accidentally modifying each other's data. You should generally avoid using "global variables" (variables defined outside all functions) inside your functions.

Python Functions | Python Tutorial for Absolute Beginners #1

This final clip from Mosh explains variable scope. It's a slightly more advanced topic, but understanding it now will save you a lot of headaches later.

Watch from 19:11 to 24:29. The key takeaway is to avoid modifying global variables inside functions. It's better to pass data in as parameters and send results back with return.

Documentation (Docstrings): It's good practice to write a brief description of what your function does, what parameters it expects, and what it returns. In Python, this is done using a special comment called a docstring (a multi-line string right after the def line).

def calculate_vat(price):
    """Calculates the 20% VAT for a given price.

    Args:
        price (float): The price of the item before tax.

    Returns:
        float: The calculated VAT amount.
    """
    vat_amount = price * 0.20
    return vat_amount

This makes it much easier for you (or others) to understand how to use your function in the future.


Conclusion

Great job! You've just learned one of the most important concepts in programming. Functions are the building blocks of any significant application, including automation scripts.

Key Takeaways:

  • Functions help you organize code into reusable and manageable blocks using the def keyword.
  • You can pass data into functions using parameters, and the values you send are called arguments.
  • Keyword arguments and default parameter values make your functions more flexible and readable.
  • The return statement allows a function to send a value back to the caller.
  • Functions that don't explicitly return a value will return None by default.
  • Variables defined inside a function are local to that function, which helps prevent bugs.

Next Lesson:
You now know how to build your own tools with functions. But what if the tool you need already exists? In the next lesson, we will learn how to import and use modules from the Python Standard Library. This will unlock a huge collection of pre-written functions that can do everything from working with dates and times to managing files on your computer, dramatically speeding up your automation development.