Define and Use Functions in Python

PythonBeginner
Practice Now

Introduction

In this lab, you will learn how to define and use functions in Python. Functions are essential for organizing code and promoting reusability. You will begin by understanding the concept of functions and exploring Python's built-in functions, learning how to call them with parameters and observe their output.

Following the exploration of built-in functions, you will learn how to define your own simple functions. Finally, you will practice calling these user-defined functions to execute the code blocks they contain, solidifying your understanding of function creation and usage in Python.

Understand and Use Built-in Functions

In this step, we will explore the concept of functions and learn how to use Python's built-in functions. A function is a reusable block of code that performs a specific action. Python provides many built-in functions that are ready to use, such as print(), len(), and sum().

Let's start by writing a Python script to see some of these functions in action.

First, find the builtin_functions.py file in the WebIDE file explorer on the left. This file has been pre-created for you in the ~/project directory. Double-click the file to open it in the editor.

Now, add the following Python code to the builtin_functions.py file. This code demonstrates how to call several built-in functions.

## Using the print() function to display output
print("Hello, Python Functions!")

## Using the len() function to get the length of a string
message = "Hello World"
print(len(message))

## Using the sum() function to add numbers in a list
numbers = [1, 2, 3, 4, 5]
total = sum(numbers)
print(total)

After writing the code, save the file by pressing Ctrl+S.

To run the script, open the integrated terminal in the WebIDE (if it's not already open, go to the top menu and select Terminal > New Terminal). Then, execute the following command:

python ~/project/builtin_functions.py

You will see the output from each print() call in the terminal.

Hello, Python Functions!
11
15

This output shows the results of calling the built-in functions: print() displays text, len() returns the number of characters in a string, and sum() calculates the sum of the items in a list.

Use Functions with Parameters and Return Values

Functions often need input data to work with. This data is passed to the function as parameters (also called arguments). After processing, a function can send back a result, which is known as the return value.

Let's expand our builtin_functions.py script to explore functions that take parameters and see how we can use their return values.

Open the builtin_functions.py file again in the WebIDE editor. Add the following code to the end of the file:

## Using the max() function with multiple number parameters
largest_number = max(10, 25, 15)
print(largest_number)

## Using the round() function with two parameters
pi_approx = 3.14159
rounded_pi = round(pi_approx, 2) ## round to 2 decimal places
print(rounded_pi)

## Using the sorted() function with a list parameter
unsorted_list = ['cherry', 'apple', 'banana']
sorted_list = sorted(unsorted_list)
print(sorted_list)

Save the changes to the file (Ctrl+S).

Now, run the updated script from the terminal:

python ~/project/builtin_functions.py

The terminal will display the output from both the original and the new code.

Hello, Python Functions!
11
15
25
3.14
['apple', 'banana', 'cherry']

Let's review the new output:

  • max(10, 25, 15) takes three numbers as parameters and returns the largest one, 25.
  • round(pi_approx, 2) takes a number and the number of decimal places as parameters. It returns the rounded value, 3.14.
  • sorted(unsorted_list) takes a list as a parameter and returns a new list with the elements sorted in ascending order.

In each case, we stored the function's return value in a variable (largest_number, rounded_pi, sorted_list) before printing it. This is a common and useful practice.

Define a Simple Function

While built-in functions are powerful, you will often need to create your own functions to perform custom tasks. This is called defining a function.

In Python, you define a function using the def keyword. The basic syntax is:

def function_name(parameters):
    """Docstring: An optional description of the function."""
    ## Code to be executed (the function body)
    ## ...
    return value  ## Optional return statement
  • def: The keyword that starts a function definition.
  • function_name: A descriptive name for your function.
  • (parameters): Input variables for the function. A function can have zero or more parameters.
  • :: The colon marks the end of the function header.
  • Indentation: The lines of code inside the function must be indented (usually with 4 spaces). This is how Python groups statements.

Let's create our first function. In the WebIDE file explorer, find and open the my_functions.py file.

Add the following code to my_functions.py to define a function that prints a greeting:

## Define a simple function named 'greet'
def greet():
    """This function prints a simple greeting message."""
    print("Hello from a user-defined function!")

Save the file.

At this point, you have successfully defined a function named greet. However, if you run this script, nothing will happen. Defining a function just tells Python what the function does; it doesn't actually run the code inside it. To execute the function's code, you need to call it, which we will cover in the next step.

Call a User-Defined Function

After defining a function, you need to call it to execute its code. Calling a function is straightforward: you just type its name followed by parentheses ().

Let's call the greet function we defined in the previous step.

Open the my_functions.py file in the WebIDE editor. Add a line of code after the function definition to call the function.

## Define a simple function named 'greet'
def greet():
    """This function prints a simple greeting message."""
    print("Hello from a user-defined function!")

## Call the greet function to execute its code
print("Calling the function now...")
greet()

Save the file. It's important that the function call greet() appears after the def greet(): block. Python reads files from top to bottom, so you must define a function before you can call it.

Now, run the script from the terminal:

python ~/project/my_functions.py

You will see the output printed to the console:

Calling the function now...
Hello from a user-defined function!

The great advantage of functions is reusability. You can call the same function multiple times without rewriting its code. Let's call greet() again. Modify my_functions.py to look like this:

## Define a simple function named 'greet'
def greet():
    """This function prints a simple greeting message."""
    print("Hello from a user-defined function!")

## Call the greet function multiple times
print("Calling the function...")
greet()
print("Calling it again...")
greet()

Save the file and run it one more time:

python ~/project/my_functions.py

The output now shows that the function was executed twice:

Calling the function...
Hello from a user-defined function!
Calling it again...
Hello from a user-defined function!

This demonstrates how functions help you write cleaner, more organized, and reusable code.

Summary

In this lab, you have learned the fundamentals of functions in Python. You started by exploring Python's built-in functions, such as print(), len(), and sum(), and practiced calling them in a script. You then delved deeper into how functions work by passing parameters and using their return values with examples like max(), round(), and sorted().

Finally, you learned the syntax for defining your own custom functions using the def keyword and practiced calling your user-defined function to execute its code. This lab has provided a solid foundation for creating modular and reusable code, a key skill for any Python programmer.