11  Python Functions

TipLearning Objectives
  • Understand how data flows into and out of custom functions
  • Learn the syntax for defining custom Python functions using def
  • Write and run your own custom functions using standard operators and basic string, list, and maths operations

11.1 What is a Function?

A function in Python is a reusable block of code designed to perform a specific task. You can provide inputs (arguments), the function executes its code, and it returns an output (a result).

Functions allow you to organise your code logically, eliminate repetitive code, and make your programs significantly easier to read, test, and maintain.


11.2 Defining Your Own Functions

To define a custom function in Python, use the def keyword followed by the function name, parentheses (), and a colon :.

11.2.1 Function Syntax

def function_name(parameter_name):
    """Optional docstring explaining what the function does."""
    # Function body (indented)
    result = parameter_name + 10
    return result

Key parts of a function definition:

  • def: The keyword used to define a function.
  • function_name: The name you choose for your function (written in lowercase with words separated by underscores).
  • parameters: Optional input variables passed into the function inside ().
  • return: Sends the final output value back to where the function was called.

11.2.2 Step-by-Step Examples

Example 1: Function without Inputs

Functions do not always require input parameters.

def display_welcome_message():
    print("Welcome to the Python workshop!")

# Calling the function
display_welcome_message()
Welcome to the Python workshop!

Example 2: Function with Input Parameters

def greet_person(name):
    print(f"Hello, {name}!")

greet_person("Kavi")
greet_person("Tom")
Hello, Kavi!
Hello, Tom!

Example 3: Function Returning a Value

def add_numbers(a, b):
    return a + b

# Store the returned output in a variable
total = add_numbers(5, 10)
print(total)  # Output: 15
15

Example 4: Function with Default Parameters

You can set default parameter values so a function can be called with fewer arguments when needed.

def greet_with_default(name="Guest"):
    print(f"Hello, {name}!")

greet_with_default("Sarah")  # Uses provided argument
greet_with_default()         # Uses default value "Guest"
Hello, Sarah!
Hello, Guest!

Example 5: Custom Function for numeric processing

def calculate_average(scores):
    """Calculates the average score from a list of numbers."""
    total_score = sum(scores)
    number_of_scores = len(scores)
    average = total_score / number_of_scores
    return round(average, 2)

test_scores = [85, 90, 78, 92]
final_average = calculate_average(test_scores)
print(f"Average score: {final_average}")  # Output: 86.25
Average score: 86.25

11.3 Exercises

ExerciseExercise 1 - Formatting User Input

Write a function named format_greeting that accepts a single parameter name. 1. Use .strip() and .title() to clean up extra whitespace and capitalise the name properly (e.g., " alex " becomes "Alex"). 2. Return a formatted greeting string: "Welcome, [Clean Name]!".

def format_greeting(name):
    clean_name = name.strip().title()
    return f"Welcome, {clean_name}!"

# Test the function
print(format_greeting("  alex  "))  # Output: Welcome, Alex!
Welcome, Alex!
ExerciseExercise 2 - Budget Checker

Write a function called is_over_budget that takes two parameters: - expenses: A list of numbers representing spending items. - budget_limit: A single number representing the overall spending limit.

The function should calculate the sum of expenses. If total spending exceeds budget_limit, return True; otherwise, return False.

def is_over_budget(expenses, budget_limit):
    total_spent = sum(expenses)
    return total_spent > budget_limit

# Test the function
my_expenses = [12.50, 45.00, 30.00]
print(is_over_budget(my_expenses, 80))  # Output: True
True
ExerciseExercise 3 - Discount Calculator

Write a function called apply_discount that takes a list of item prices and a percentage discount (e.g., 10 for 10%). 1. Sum all items in the list to calculate the total price. 2. Calculate the discounted total using arithmetic operators (* and /). 3. Return the final price rounded to 2 decimal places using round().

def apply_discount(prices, discount_percent):
    total = sum(prices)
    discount_amount = total * (discount_percent / 100)
    final_price = total - discount_amount
    return round(final_price, 2)

# Test the function
items = [20.0, 15.0, 50.0]
print(apply_discount(items, 10))  # Output: 76.5
76.5
ExerciseExercise 4 - Discussion - Function Documentation

Try running Python’s built-in help() function on a custom function you have written:

def add_bonus(salary):
    """Calculates total salary after adding a 500 standard bonus."""
    return salary + 500

help(add_bonus)

What information does help() display? Why is it good practice to include docstrings (text inside triple quotes """ ... """) inside your custom functions?

def add_bonus(salary):
    """Calculates total salary after adding a 500 standard bonus."""
    return salary + 500

help(add_bonus)
Help on function add_bonus in module __main__:

add_bonus(salary)
    Calculates total salary after adding a 500 standard bonus.

The help() function reads and displays the signature and docstring of the custom function. Including docstrings helps other developers (and your future self) understand what your custom functions do and how to use them effectively.

11.4 Summary

TipKey Points
  • Custom functions are defined using the def keyword followed by the function name and parameter list.
  • Data flows into a function via parameters (inputs are optional) and flows out via the return statement.
  • Default parameters make custom functions flexible when called with varying numbers of arguments.
  • Writing custom functions helps organise complex code into small, manageable, and reusable blocks.