Lesson 9.1: Defining Functions with def
What You'll Learn
- What functions are and why they matter
- How to define a function using the
defkeyword - How to call (use) a function
- How to write docstrings to document your functions
- The difference between defining and calling a function
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.
Why Functions Matter
- Reusability: Write code once, use it many times
- Organization: Break complex problems into smaller, manageable pieces
- Readability: Well-named functions make code self-documenting
- Testing: Functions can be tested individually
- Collaboration: Teams can work on different functions independently
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:
def— the keyword that tells Python you are defining a functiongreet— the name of the function (follows the same rules as variable names)()— parentheses for parameters (empty here because this function takes no input):— a colon marks the end of the function header- The indented block below is the function body — the code that runs when the function is called
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
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()
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")
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)
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_emailis better thanseorsend_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
- Define a function called
introducethat prints your name and favorite hobby - Add a docstring to the function
- Call the function three times
- Define a function called
print_boxthat prints a small text box using*characters
Key Takeaways
- Functions are reusable blocks of code defined with the
defkeyword - Defining a function does not run it — you must call it with parentheses
- The function body is indented and runs each time the function is called
- Docstrings document what a function does and should be included in every function
- Use descriptive, verb-based names in
snake_case