Area 2.7

Functions and Procedures

Learn to create reusable code through user-written functions and leverage powerful pre-written library functions. Master the principles of code organization and reusability.

4
Function Types
20+
Library Functions
~2hrs
Study Time

Learning Objectives

  • Understand the difference between functions and procedures
  • Create user-defined functions with parameters and return values
  • Use pre-written library functions effectively
  • Apply the principle of code reusability through function design
  • Evaluate trade-offs between custom functions and library solutions
  • Implement proper function documentation and naming conventions

User-Written vs Pre-Written Functions

User-Written Functions

Custom functions created by the programmer for specific tasks

Advantages:

  • Tailored to exact requirements
  • Full control over implementation
  • Can be optimized for specific use case
  • No external dependencies

Disadvantages:

  • Takes time to develop and test
  • May contain bugs or inefficiencies
  • Requires maintenance and updates
  • Potential for reinventing the wheel

Python Examples:

# User-written function examples
def calculate_discount(price, discount_percent):
    """Calculate discounted price"""
    discount_amount = price * (discount_percent / 100)
    return price - discount_amount

def validate_email(email):
    """Simple email validation"""
    if "@" in email and "." in email:
        return True
    return False

def format_currency(amount):
    """Format number as currency"""
    return f"£{amount:.2f}"

# Using user-written functions
original_price = 100.00
discounted_price = calculate_discount(original_price, 15)
print(format_currency(discounted_price))  # £85.00

Best Practices:

  • Use descriptive function names
  • Keep functions focused on single task
  • Add docstrings for documentation
  • Use meaningful parameter names

Pre-Written Library Functions

Ready-made functions from Python standard library and external modules

Advantages:

  • Tested and optimized by experts
  • Saves development time
  • Reduces code complexity
  • Regular updates and improvements

Disadvantages:

  • May include unnecessary features
  • Less control over behavior
  • Potential compatibility issues
  • Learning curve for complex libraries

Python Examples:

# Built-in library functions

# Math library functions
radius = 5
area = math.pi * math.pow(radius, 2)
print(f"Circle area: {area:.2f}")

# Random library functions
numbers = [1, 2, 3, 4, 5]
random.shuffle(numbers)
random_choice = random.choice(numbers)
print(f"Random number: {random_choice}")

# DateTime library functions
now = datetime.datetime.now()
formatted_date = now.strftime("%Y-%m-%d %H:%M:%S")
print(f"Current time: {formatted_date}")

# String methods (built-in)
text = "  Hello World  "
cleaned = text.strip().upper()
print(cleaned)  # "HELLO WORLD"

Best Practices:

  • Import only what you need
  • Read documentation before using
  • Handle potential exceptions
  • Consider performance implications

Function Types and Patterns

Function (with return)

Performs calculation and returns a value

Syntax Pattern:

def function_name(parameters):
    # code
    return value

Example:

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

result = add_numbers(5, 3)  # result = 8

When to Use:

Mathematical calculations, data processing, value transformations

Procedure (no return)

Performs actions but doesn't return a value

Syntax Pattern:

def procedure_name(parameters):
    # code
    # no return statement

Example:

def print_welcome(name):
    print(f"Welcome, {name}!")
    print("Enjoy your visit")

print_welcome("Alice")

When to Use:

Printing output, file operations, updating global variables

Function with Default Parameters

Provides default values for optional parameters

Syntax Pattern:

def function_name(required, optional=default):
    # code

Example:

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

print(greet("Bob"))  # "Hello, Bob!"
print(greet("Alice", "Hi"))  # "Hi, Alice!"

When to Use:

When some parameters are commonly used with default values

Function with Multiple Returns

Returns multiple values as a tuple

Syntax Pattern:

def function_name(parameters):
    # code
    return value1, value2

Example:

def divide_with_remainder(a, b):
    quotient = a // b
    remainder = a % b
    return quotient, remainder

q, r = divide_with_remainder(17, 5)  # q=3, r=2

When to Use:

When a function naturally produces multiple related results

Common Python Libraries

math

Mathematical functions and constants

Key Functions:

math.sqrt()math.pow()math.pimath.ceil()math.floor()

Example:

import math
print(math.sqrt(16))  # 4.0

random

Random number generation and selection

Key Functions:

random.randint()random.choice()random.shuffle()random.random()

Example:

import random
print(random.randint(1, 10))  # Random number 1-10

datetime

Date and time manipulation

Key Functions:

datetime.now()datetime.strftime()timedelta()

Example:

from datetime import datetime
print(datetime.now())

os

Operating system interface

Key Functions:

os.path.exists()os.listdir()os.getcwd()

Example:

import os
print(os.getcwd())  # Current directory

Learning Activities

Function Design Workshop

Design
50 minutes

Design and implement user-defined functions for common programming tasks

Library Exploration Challenge

Exploration
45 minutes

Explore Python standard library modules and implement solutions using pre-built functions

Code Refactoring Exercise

Refactoring
40 minutes

Refactor repetitive code by creating reusable functions and procedures