PYTHON

Python Functions: Syntax, Usage, and Examples

In Python, a function is a block of code that performs a specific task. When the function is called, the function's body is executed.

Like many other programming languages, Python also offers built-in functions for common tasks. For example, print() is a built-in Python function that displays an object in the Python console.

How to Use Functions in Python

Defining Functions in Python

Creating a user-defined function requires the def keyword, a function name, and parentheses that may include parameters. The function's body, an indented block of code, defines the operations the function performs.

Here's the basic syntax for creating a function:

def function_name(parameter1, parameter2):
    # Block of reusable code
    return return_value  # Optional return statement
  • def: The keyword to start the function definition.
  • function_name: A unique identifier to name your function, following Python's naming conventions.
  • parameter(s): Any number of variables listed inside the parentheses help pass data into the function (optional).
  • return: The keyword to exit the function before reaching its end (optional).
  • return_value: A value or variable to return from the function (optional).

Calling Functions in Python

Once a function is defined, it can be executed, or called, by using its name followed by parentheses. A function’s code block is only executed when a function is called.

Here's the basic syntax for executing a function:

function_name(attribute1, attribute2)
  • function_name: The unique identifier of the function
  • attribute(s): Values or variables to pass data into the function (if possible or required).

When to Use Functions in Python

Python functions can be helpful in many ways.

Reusing Code

Creating functions in Python is great for organizing and reusing blocks of code. Functions are especially valuable when you'll need the same or a similar code block multiple times throughout your program.

from math import pi
def calculate_area(radius):
    return pi * (radius ** 2)

# Call the function multiple times with different values
area1 = calculate_area(5)
area2 = calculate_area(10)

Simplifying Complex Operations

You can encapsulate complex operations within a function to simplify the main program flow. Often, such functions return the result of the operation. This makes the code more readable and easier to debug.

def process_data(data):
    # (Imagine complex operations)
    processed_data = data + " has been processed."
    return processed_data

# Using the function simplifies the main code
data = "3, 2.0, TRUE"
result = process_data(data)

Customizing Operations

Functions can accept parameters, making them adaptable based on different inputs. This allows the same function to work with a wide range of data.

def greet(name):
    return f"Hello, {name}!"

# The function can be called with different arguments
greeting1 = greet("Joanna")
greeting2 = greet("Max")

Organizing Code

Functions help organize code into logical sections. You can dedicate a function to a specific task, which makes the program easier to follow and maintain.

def load_data(file_path):
    # Code to load data from a file
    return data

def clean_data(data):
    # Code to clean and preprocess the data
    return clean_data

# Sequential function calls for data processing
raw_data = load_data("data.csv")
processed_data = clean_data(raw_data)

Examples of Functions in Python

Like variables, functions make up virtually every Python application. Here are some potential use cases for functions:

User Authentication

Python applications might use functions to sign in a user by checking a username and password. Here’s a simplified login function:

def authenticate_user(username, password):
    stored_username = "user1"
    stored_password = "pass123"
    if username == stored_username and password == stored_password:
        return True
    else:
        return False

# Attempting to authenticate a user
is_authenticated = authenticate_user("user1", "pass123")
if is_authenticated:
    print("User authenticated successfully.")
else:
    print("Authentication failed.")

Data Filtering

Handling files is a common task in programming. This example shows a function that reads a file, processes its content line by line, and returns the processed data.

from datetime import date
def filter_data(data_list, key, value):
    filtered_data = [item for item in data_list if item.get(key) == value]
    return filtered_data

# Sample data
people_data = [
    {"name": "Warren", "birth_date": date(1930, 8, 30), "city": "Omaha"},
    {"name": "Charlie", "birth_date": date(1924, 1, 1), "city": "Omaha"}
]

# Filtering data for people living in Omaha
omaha_residents = filter_data(people_data, "city", "Omaha")
print("Omaha Residents:", omaha_residents)

File Processing

Handling files is a common task in programming. This example shows a function that reads a file, processes its content line by line, and returns the processed data.

def process_file(file_path):
    processed_lines = []
    with open(file_path, 'r') as file:
        for line in file:
            processed_line = line.strip().upper()  # Example processing
            processed_lines.append(processed_line)
    return processed_lines

# Using the function to process a text file
file_data = process_file('robots.txt')
print("Processed File Content:", file_data)

API Calls

In modern software development, making API calls is essential for interacting with web services. This function demonstrates how to make a simple HTTP GET request to an API and process the JSON response.

import requests

def fetch_data_from_api(url):
    response = requests.get(url)
    if response.status_code == 200:
        return response.json()  # Convert the response to JSON
    else:
        return None

# Fetching data from a sample API
api_url = "https://jsonplaceholder.typicode.com/posts/1"
post_data = fetch_data_from_api(api_url)
print("API Response:", post_data)

Learn More About Functions in Python

Parameters vs. Arguments

The terms "parameters" and "arguments" have distinct meanings in the context of functions.

Parameters are the variables listed in the function's definition. They act as placeholders for the values that the function will operate on. Conversely, arguments are the actual values you pass to the function when you call it.

In a function for adding two numbers, the parameters might be x and y. These parameters are placeholders for the numbers to work with:

def add_numbers(x, y):  # 'x' and 'y' are parameters
    return x + y

When you call a function, the values you provide in the call are the arguments. In the call add_numbers(5, 3), the numbers 5 and 3 are the arguments passed to the function.

result = add_numbers(5, 3)  # '5' and '3' are arguments
print(result)  # Output: 8

In the example, 5 is passed as an argument for the parameter x, and 3 is passed as an argument for the parameter y. The function then operates on these arguments to produce a result.

Optional Parameters

With optional parameters, Python functions can accept different numbers of arguments. By providing default values for parameters, you can create functions you can call with fewer arguments. Here's a function for logging messages:

def log_message(message, level="INFO"):
    from datetime import datetime
    current_time = f"{datetime.now():%Y-%m-%d %H:%M:%S}"
    print(f"{current_time} [{level}]: {message}")

# Using the function with the default log level
log_message("User logged in.")

# Using the function with an optional 'level' parameter to specify a different log level
log_message("User attempted unauthorized access.", "WARNING")

In this example, the log_message() function logs messages with a timestamp. The level parameter is optional, with a default argument of "INFO". You can call the function with just the message for routine logs. When a situation requires a warning or an error, you can pass the argument you need.

Using args in Python Functions

The number of arguments to pass to a function might vary in different parts of your Python applications. The *args parameter in Python functions allows you to pass a variable number of arguments to a function.

Consider a function designed to calculate the average of an unknown number of numerical arguments. Using *args makes this function adaptable to any number of input values:

def calculate_average(*args):
    total = sum(args)  # Sums up all the arguments
    count = len(args)  # Counts the number of arguments provided
    if count == 0:
        return 0  # Avoid division by zero if no arguments are provided
    return total / count

# Example usage
print(calculate_average(10, 20, 30))  # Output: 20.0
print(calculate_average(5, 15))  # Output: 10.0

The *args parameter collects extra arguments as a tuple, making it easy to iterate over them. In this example, *args allows calculate_average() to accept any number of numeric arguments. The function sums up the arguments and divides them by their count to find the average.

Using Docstrings in Python Functions

A docstring is a string literal to document Python functions (as well as classes, modules, and packages). Enclosed in triple quotes ("""), a docstring describes a function, its parameters, return values, or other important information.

Docstrings are important for understanding and maintaining code, especially in larger projects or when sharing code with others.

def calculate_area(length, width):
    """
    Calculate and return the area of a rectangle.

    Parameters:
    length (float): The length of the rectangle.
    width (float): The width of the rectangle.

    Returns:
    float: The area of the rectangle.
    """
    return length * width

Naming Functions in Python

A function's name can already tell you a lot about the function. Choosing appropriate names for functions is important in Python. Following Python's naming conventions and best practices makes your functions easy to follow for others and your future self. Here are some guidelines for naming Python functions:

  • Function names should be descriptive and convey the purpose of the function. A name like calculate_total() is more informative and intuitive than a vague name like do_calc().
  • Ideally, function names follow a verb-object form, describing the action and the affected object. For example, send_email(), read_file(), or generate_report() hint at the action and the object.
  • According to Python's style guide, function names should use snake case to ensure readability. Snake-case names are lowercase words separated by underscores.
  • Function names should be as specific as possible. For example, a function named filter() might be too generic unless its context within the module clarifies its purpose. A more specific alternative might be filter_outdated_records().
  • While function names should be descriptive, they should also be concise enough to avoid overly long names that are cumbersome to type and read. Striking a balance between descriptiveness and brevity is ideal.
  • Be cautious not to name functions the same as Python's built-in functions or keywords, since you might cause confusion or even get errors. For example, avoid names like list() or print() for your functions.
Learn to Code in Python for Free
Start learning now
button icon
To advance beyond this tutorial and learn Python by doing, try the interactive experience of Mimo. Whether you're starting from scratch or brushing up your coding skills, Mimo helps you take your coding journey above and beyond.

Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.

You can code, too.

© 2024 Mimo GmbH