Learn Without Walls
← Module 9 Home Lesson 1 of 4 Next Lesson →

Lesson 9.1: Defining Functions with def

What You'll Learn

1. What is a Function?

A function is a reusable block of code that performs a specific task. You have already used many built-in functions like print(), len(), and input(). Now you will learn to create your own.

Function: A named block of code that you can define once and call (run) as many times as you need. Functions help you organize your code, avoid repetition, and make programs easier to read and maintain.

Why Functions Matter

2. Defining Your First Function

Use the def keyword to define a function:

def greet():
    """Print a greeting message."""
    print("Hello! Welcome to Python.")

Let's break down the syntax:

Important: Defining a function does not run it. You must call the function to execute its code.

3. Calling a Function

To run a function, write its name followed by parentheses:

def greet():
    """Print a greeting message."""
    print("Hello! Welcome to Python.")

# Call the function
greet()
greet()  # You can call it as many times as you want
Hello! Welcome to Python. Hello! Welcome to Python.

Define Once, Call Many Times

def print_separator():
    """Print a visual separator line."""
    print("=" * 40)

print_separator()
print("Section 1: Introduction")
print_separator()
print("Section 2: Details")
print_separator()
======================================== Section 1: Introduction ======================================== Section 2: Details ========================================

4. Functions with Simple Parameters

Functions become much more powerful when they accept input. Here is a preview (we cover parameters in depth in the next lesson):

def greet_person(name):
    """Greet a person by name."""
    print(f"Hello, {name}! Welcome to Python.")

greet_person("Alice")
greet_person("Bob")
Hello, Alice! Welcome to Python. Hello, Bob! Welcome to Python.

5. Docstrings

A docstring is a string that describes what a function does. It goes on the first line of the function body, enclosed in triple quotes:

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

    Args:
        length: The length of the rectangle.
        width: The width of the rectangle.

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

# You can view a function's docstring with help()
help(calculate_area)
Docstring: A documentation string placed immediately after the def line. It describes the function's purpose, parameters, and return value. Best practice is to always include one.

6. Naming Functions

Good function names make your code readable:

Naming Conventions

  • Use lowercase with underscores: calculate_total, get_user_input
  • Start with a verb that describes the action: print_report, validate_email
  • Be descriptive but concise: send_email is better than se or send_the_electronic_mail_message
  • Follow the same rules as variable names (no spaces, no starting with numbers)
# Good function names
def calculate_average(numbers):
    ...

def is_valid_email(email):
    ...

def print_welcome_message():
    ...

# Avoid these names
# def f():        # too short, meaningless
# def DoStuff():  # not snake_case
# def data():     # noun, not a verb

Check Your Understanding

Question: What is wrong with this code?

def say_hello():
    print("Hello!")

print("The program starts here")
say_hello

Answer: The last line writes say_hello without parentheses. This references the function object but does not call it. To actually run the function, you need say_hello() with parentheses.

Try It Yourself

  1. Define a function called introduce that prints your name and favorite hobby
  2. Add a docstring to the function
  3. Call the function three times
  4. Define a function called print_box that prints a small text box using * characters

Key Takeaways

← Module 9 Home Next: Parameters & Return Values →