Lesson 1 • Intermediate

    Functions in Python

    Learn to organize, reuse, and simplify your code with Python functions.

    What You'll Learn in This Lesson

    • What a function is and why it's the #1 tool for code reuse
    • How to define functions with def and call them
    • How to pass data into functions using parameters
    • How to get results back from functions with return
    • Default parameters and keyword arguments
    • How to return multiple values at once

    1. What Are Functions?

    A function is a reusable block of code that performs a specific task. Instead of writing the same code over and over, you write it once in a function and call it whenever you need it.

    Why Use Functions?

    • Reusability — Write once, use many times
    • Organization — Break complex programs into smaller pieces
    • Easier debugging — Fix bugs in one place, not everywhere
    • Readability — Code is easier to understand

    2. Defining a Function

    Use the def keyword to create a function:

    # Syntax
    def function_name():
    # code to run
    PartMeaning
    defKeyword that starts a function definition
    function_nameThe name you give your function (use snake_case)
    ()Parentheses for parameters (empty if none)
    :Colon to start the function body
    Indented codeThe code that runs when you call the function

    Try It: Your First Function

    Define a function and call it

    Try it Yourself »
    Python
    # Define a simple function
    def greet():
        print("Hello, World!")
    
    # Call the function
    greet()
    
    # You can call it multiple times
    greet()
    greet()

    3. Parameters — Giving Functions Inputs

    Parameters are variables listed inside the parentheses when defining a function. They allow you to pass information into the function.

    def greet(name): # 'name' is a parameter
    print(f"Hello, {name}!")
    greet("Alice") # "Alice" is the argument

    Try It: Parameters

    Pass information into functions

    Try it Yourself »
    Python
    # Function with one parameter
    def greet(name):
        print(f"Hello, {name}!")
    
    # Call with different arguments
    greet("Alice")
    greet("Bob")
    greet("Charlie")
    
    # Function with multiple parameters
    def introduce(name, age):
        print(f"I'm {name} and I'm {age} years old.")
    
    introduce("Alice", 25)
    introduce("Bob", 30)

    4. Return Values — Getting Results Back

    The return keyword sends a value back to the code that called the function. This lets you use the result!

    Without return (just prints)
    def add(a, b):
        print(a + b)
    
    result = add(5, 3)
    # Prints: 8
    # result is None!
    With return (reusable)
    def add(a, b):
        return a + b
    
    result = add(5, 3)
    # result is 8
    print(result * 2)  # 16

    Try It: Return Values

    Get results back from functions

    Try it Yourself »
    Python
    # Function that returns a value
    def add(a, b):
        return a + b
    
    # Store the result
    result = add(5, 3)
    print(f"5 + 3 = {result}")
    
    # Use the result in another calculation
    doubled = result * 2
    print(f"Doubled: {doubled}")
    
    # Use directly in expressions
    total = add(10, 20) + add(5, 5)
    print(f"Total: {total}")

    5. Default Parameter Values

    You can give parameters default values. If no argument is passed, the default is used:

    def greet(name="Guest"):
    print(f"Hello, {name}!")
    greet() # "Hello, Guest!"
    greet("Alice") # "Hello, Alice!"

    Try It: Default Parameters

    Make parameters optional with defaults

    Try it Yourself »
    Python
    # Function with default parameter
    def greet(name="Guest"):
        print(f"Hello, {name}!")
    
    greet()          # Uses default
    greet("Alice")   # Uses provided value
    
    # Multiple defaults
    def create_user(name, role="user", active=True):
        print(f"Created: {name} ({role}), Active: {active}")
    
    create_user("Alice")
    create_user("Bob", "admin")
    create_user("Charlie", "mod", False)

    6. Positional vs Keyword Arguments

    When calling a function, you can pass arguments in two ways:

    TypeExampleDescription
    Positionalfunc("Alice", 25)Arguments matched by position/order
    Keywordfunc(name="Alice", age=25)Arguments matched by name (any order)

    Try It: Argument Types

    Positional and keyword arguments

    Try it Yourself »
    Python
    def describe_pet(animal, name):
        print(f"I have a {animal} named {name}.")
    
    # Positional arguments (order matters)
    describe_pet("dog", "Rex")
    describe_pet("cat", "Whiskers")
    
    # Keyword arguments (order doesn't matter)
    describe_pet(name="Buddy", animal="hamster")
    describe_pet(animal="fish", name="Nemo")
    
    # Mixing: positional first, then keyword
    describe_pet("bird", name="Tweety")

    7. Returning Multiple Values

    Python functions can return multiple values at once! They're returned as a tuple.

    Try It: Multiple Returns

    Return multiple values from a function

    Try it Yourself »
    Python
    # Return multiple values
    def calculate(a, b):
        sum_val = a + b
        diff = a - b
        product = a * b
        return sum_val, diff, product
    
    # Unpack the results
    s, d, p = calculate(10, 5)
    print(f"Sum: {s}, Difference: {d}, Product: {p}")
    
    # Or store as tuple
    results = calculate(20, 3)
    print(f"All results: {results}")
    print(f"Just the sum: {results[0]}")

    8. Variable Scope — Local vs Global

    Scope determines where a variable can be accessed:

    ScopeWhere DefinedWhere Accessible
    LocalInside a functionOnly inside that function
    GlobalOutside all functionsEverywhere in the file

    Try It: Variable Scope

    Understand local and global variables

    Try it Yourself »
    Python
    # Global variable
    message = "Hello from outside!"
    
    def my_function():
        # Local variable
        local_msg = "Hello from inside!"
        print(local_msg)   # Works - local variable
        print(message)     # Works - can read global
    
    my_function()
    print(message)         # Works - global variable
    # print(local_msg)     # ERROR - local_msg doesn't exist here!

    9. Docstrings — Documenting Your Functions

    A docstring is a special string that describes what your function does. Put it right after the def line:

    Try It: Docstrings

    Document your functions properly

    Try it Yourself »
    Python
    def calculate_area(width, height):
        """
        Calculate the area of a rectangle.
        
        Parameters:
            width: The width of the rectangle
            height: The height of the rectangle
        
        Returns:
            The area (width * height)
        """
        return width * height
    
    # Access the docstring
    print(calculate_area.__doc__)
    
    # Use help() to see it
    help(calculate_area)

    10. Common Mistakes to Avoid

    MistakeWrongCorrect
    Forgetting parenthesesgreetgreet()
    Forgetting colondef greet()def greet():
    Missing indentationdef greet():
    print("Hi")
    def greet():
    print("Hi")
    Using print instead of returnprint(a + b)return a + b
    Wrong argument countadd(5)add(5, 3)

    11. Practical Examples

    Example 1: Temperature Converter

    Temperature Converter

    Convert between Celsius and Fahrenheit

    Try it Yourself »
    Python
    def celsius_to_fahrenheit(celsius):
        """Convert Celsius to Fahrenheit."""
        return (celsius * 9/5) + 32
    
    def fahrenheit_to_celsius(fahrenheit):
        """Convert Fahrenheit to Celsius."""
        return (fahrenheit - 32) * 5/9
    
    # Test the functions
    print(f"0°C = {celsius_to_fahrenheit(0)}°F")
    print(f"100°C = {celsius_to_fahrenheit(100)}°F")
    print(f"98.6°F = {fahrenheit_to_celsius(98.6):.1f}°C")

    Example 2: Grade Calculator

    Grade Calculator

    Convert numeric scores to letter grades

    Try it Yourself »
    Python
    def calculate_grade(score):
        """Return letter grade based on score."""
        if score >= 90:
            return "A"
        elif score >= 80:
            return "B"
        elif score >= 70:
            return "C"
        elif score >= 60:
            return "D"
        else:
            return "F"
    
    # Test with different scores
    scores = [95, 82, 73, 65, 45]
    for score in scores:
        grade = calculate_grade(score)
        print(f"Score: {score} → Grade: {grade}")

    Example 3: Simple Calculator

    Simple Calculator

    Basic arithmetic functions with error handling

    Try it Yourself »
    Python
    def add(a, b):
        return a + b
    
    def subtract(a, b):
        return a - b
    
    def multiply(a, b):
        return a * b
    
    def divide(a, b):
        if b == 0:
            return "Error: Cannot divide by zero"
        return a / b
    
    # Use the calculator functions
    print(f"10 + 5 = {add(10, 5)}")
    print(f"10 - 5 = {subtract(10, 5)}")
    print(f"10 × 5 = {multiply(10, 5)}")
    print(f"10 ÷ 5 = {divide(10, 5)}")
    print(f"10 ÷ 0 = {divide(10, 0)}")

    Summary: Quick Reference

    ConceptSyntaxExample
    Define functiondef name():def greet():
    With parameterdef name(param):def greet(name):
    Return valuereturn valuereturn a + b
    Default paramparam="default"def greet(name="Guest"):
    Keyword argparam=valuegreet(name="Alice")
    Multiple returnsreturn a, bx, y = func()
    Docstring"""text""""""Calculate area."""
    🎉

    Lesson 6 done — you can now write reusable code like a pro!

    Functions are the single most important concept in all of programming. You now know how to define them, pass data in, get results out, set defaults, and return multiple values.

    🚀 Up next: Lists — learn to store and manage collections of data, the backbone of most real programs.

    Sign up for free to track which lessons you've completed and get learning reminders.

    Previous

    Cookie & Privacy Settings

    We use cookies to improve your experience, analyze traffic, and show personalized ads. You can manage your preferences below.

    By clicking "Accept All", you consent to our use of cookies for analytics and personalized advertising. You can customize your preferences or reject non-essential cookies.

    Privacy PolicyTerms of Service