Chapter 6: Functions in Python

Hands-on exercises to practice creating and using functions

Chapter 6 Concepts

This chapter covers the fundamentals of functions in Python programming:

Function Definition Parameters & Arguments Return Values Default Parameters Keyword Arguments Variable-length Arguments Scope Lambda Functions
Exercise 1

Basic Function

Create a simple function that greets a user by name.

# Define a function called greet_user
# It should take a name parameter
# It should print "Hello, [name]! Welcome to Python."
# Call the function with your name
  • Use the def keyword to define the function
  • Include a parameter for the name
  • Use a print statement inside the function
  • Call the function with your name as an argument
  • Call it again with a different name
  • Exercise 2

    Return Values

    Create a function that calculates the area of a circle and returns the result.

    # Define a function called circle_area
    # It should take a radius parameter
    # It should return the area (πr²)
    # Call the function and print the result
  • Import math module to get the value of π
  • Define the function with the radius parameter
  • Calculate the area using the formula
  • Use the return statement to return the result
  • Call the function and print the returned value
  • Exercise 3

    Default Parameters

    Create a function with default parameter values.

    # Define a function called create_message
    # It should take name and greeting parameters
    # greeting should have a default value of "Hello"
    # It should return a formatted string
    # Call it with and without the greeting argument
  • Define the function with two parameters
  • Set a default value for the greeting parameter
  • Return a string that combines the greeting and name
  • Call the function with both arguments
  • Call the function with only the name argument
  • Exercise 4

    Keyword Arguments

    Create a function that uses keyword arguments.

    # Define a function called describe_pet
    # It should take animal_type and pet_name parameters
    # It should print a message about the pet
    # Call it using keyword arguments
  • Define the function with two parameters
  • Print a message using both parameters
  • Call the function with positional arguments
  • Call the function with keyword arguments
  • Change the order of keyword arguments
  • Exercise 5

    Variable-length Arguments

    Create a function that accepts any number of arguments.

    # Define a function called calculate_average
    # It should take any number of numbers
    # It should return the average of these numbers
    # Call it with different numbers of arguments
  • Use *args to accept variable arguments
  • Calculate the sum of all numbers
  • Count how many numbers were provided
  • Calculate and return the average
  • Call the function with different numbers of arguments
  • Exercise 6

    Global vs Local Scope

    Create a program that demonstrates the difference between global and local variables.

    # Create a global variable
    global_var = "I'm global"

    # Define a function that uses a local variable
    def test_scope():
        local_var = "I'm local"
        print("Inside function:", local_var)
        print("Inside function:", global_var)

    # Call the function and try to access local_var outside
  • Create a global variable
  • Define a function that creates a local variable
  • Print both variables inside the function
  • Call the function
  • Try to print the local variable outside the function (will cause error)
  • Exercise 7

    Lambda Functions

    Create and use lambda functions for simple operations.

    # Create a lambda function to double a number
    double = lambda x: x * 2

    # Create a lambda function to add two numbers
    add = lambda x, y: x + y

    # Use these lambda functions
  • Create a lambda function that doubles a number
  • Create a lambda function that adds two numbers
  • Call both lambda functions with sample values
  • Use the lambda functions in a print statement
  • Try creating another lambda function (e.g., multiply)
  • Exercise 8

    Function Composition

    Create multiple functions that work together.

    # Create a function to convert Fahrenheit to Celsius
    def fahrenheit_to_celsius(f):
        return (f - 32) * 5/9

    # Create a function to convert Celsius to Kelvin
    def celsius_to_kelvin(c):
        return c + 273.15

    # Create a function that converts Fahrenheit to Kelvin
    # by using the other two functions
  • Create a function to convert Fahrenheit to Celsius
  • Create a function to convert Celsius to Kelvin
  • Create a function that uses both to convert Fahrenheit to Kelvin
  • Test all three functions with sample values
  • Print the results in a user-friendly way
  • Exercise 9

    Documentation Strings

    Create a well-documented function with a docstring.

    # Create a function to calculate compound interest
    def compound_interest(principal, rate, time):
        """
        Calculate compound interest.
        
        Args:
          principal (float): The initial amount
          rate (float): The annual interest rate (as decimal)
          time (int): The time in years
        
        Returns:
          float: The compound interest
        """
        amount = principal * (1 + rate) ** time
        return amount - principal

    # Test the function and access its docstring
  • Create a function with a detailed docstring
  • Include information about parameters
  • Include information about the return value
  • Test the function with sample values
  • Access the docstring using help() or .__doc__