Skip to main content
Jupyter Notebooks
CHAPTER 07 Beginner

Working with Functions and Modules

Updated: May 18, 2026
5 min read

# CHAPTER 7

Working with Functions and Modules

1. Chapter Introduction

If you find yourself copying and pasting the exact same block of code in three different Jupyter cells, you are doing it wrong. In programming, the DRY principle (Don't Repeat Yourself) is king. This chapter teaches you how to encapsulate code into reusable "Functions", and how to import "Modules" (libraries of code written by other people) to give your Jupyter Notebook superpowers.

2. Defining Functions in Python

A function is a block of code that only runs when it is called. You can pass data (parameters) into it, and it can return data back as a result.

Syntax:

  • Use the def keyword.
  • Name the function (using snake_case).
  • Add parentheses () and a colon :.
  • *Indent* the code block inside the function (Jupyter does this automatically).

Cell 1:

python
123456789101112
# Defining the function
def greet_user(name):
    """This is a docstring. It explains what the function does."""
    message = f"Hello there, {name}!"
    return message

# Calling the function
output1 = greet_user("Alice")
output2 = greet_user("Bob")

print(output1)
print(output2)

3. Multiple Arguments and Default Values

Functions can accept multiple inputs, and you can provide default values so an argument becomes optional.

Cell 2:

python
12345678910
def calculate_total(price, tax_rate=0.05):
    """Calculates total price with default 5% tax."""
    total = price + (price * tax_rate)
    return total

# Using the default tax rate
print(calculate_total(100))        # Output: 105.0

# Overriding the default tax rate (e.g., 20% tax)
print(calculate_total(100, 0.20))  # Output: 120.0

4. Importing Modules (The Standard Library)

Python comes with a "Standard Library"—a collection of pre-written modules you can use for common tasks like math, dates, and random numbers. You must import them to use them.

*Best Practice:* In Jupyter, place all your import statements in the very first cell of the notebook.

Cell 3:

python
12345678910
import math
import random

# Using the math module
root = math.sqrt(64)
print(f"Square root: {root}")

# Using the random module
dice_roll = random.randint(1, 6)
print(f"You rolled a {dice_roll}")

5. Different Ways to Import

If a module's name is too long, or you only need one specific function, you can change how you import it.

Cell 4:

python
1234567891011
# Import with an alias (standard practice for data science)
import statistics as stats

data = [10, 20, 30, 40, 50]
print(stats.mean(data))

# Import ONE specific function from a module
from datetime import date

today = date.today()
print(f"Today's date is: {today}")

6. Package Management (pip) and Magic Commands

The Standard Library is great, but data scientists use external, third-party libraries (like Pandas and Scikit-Learn). To install these, you use Python's package manager, pip.

In Jupyter, you can run terminal commands directly in a code cell by prefixing the command with an exclamation mark !.

Cell 5:

python
12
# Installing a package directly from a Jupyter cell
!pip install requests

*(After this finishes, you can import requests in the next cell).*

7. Mini Project: Utility Notebook Toolkit

Imagine you are analyzing temperatures. Instead of writing the math every time, you build a toolkit function.

Cell 6:

python
123456789101112131415161718
def c_to_f(celsius):
    """Converts Celsius to Fahrenheit."""
    return (celsius * 9/5) + 32

def analyze_temp(temp_c):
    temp_f = c_to_f(temp_c)
    status = "Normal"
    
    if temp_c > 37.5:
        status = "Fever"
    elif temp_c < 35.0:
        status = "Hypothermia"
        
    return f"{temp_c}°C ({temp_f}°F) - Status: {status}"

# Test the toolkit
print(analyze_temp(36.5))
print(analyze_temp(39.0))

8. Common Mistakes

  • Indentation Errors: Python does not use curly brackets {} to define code blocks. It relies strictly on indentation (usually 4 spaces). If your return statement is not indented properly, it will break.
  • Forgetting to run the definition cell: If you write a def function in Cell 1, and try to call it in Cell 2 *before running Cell 1*, Jupyter will say the function is not defined. The Kernel must "read" the definition first.

9. MCQs

Question 1

What keyword is used to define a function in Python?

Question 2

What is the purpose of the return statement in a function?

Question 3

If a function is defined as def calculate(x, y=10):, what happens if you call calculate(5)?

Question 4

Where is the best place to put import statements in a Jupyter Notebook?

Question 5

How do you import the statistics module and give it the nickname st?

Question 6

What happens if you try to use a function you defined in Cell 3, but you haven't actually run Cell 3 yet?

Question 7

How does Python know which lines of code belong inside a function?

Question 8

What does placing an exclamation mark ! before a command in a Jupyter cell do?

Question 9

Which command is used to install third-party Python packages?

Question 10

A string enclosed in triple quotes """ right below a function definition is called a?

10. Interview Questions

  • Q: What is the difference between print() and return in a Python function?
  • Q: Explain the difference between import math and from math import sqrt.

11. Summary

Functions encapsulate code into reusable blocks, adhering to the DRY principle. They are defined using def, rely on indentation, and use return to pass data back. Modules are files containing pre-written functions. You bring them into your notebook using import. For external libraries not included in Python, you can install them directly inside Jupyter using the !pip install magic command.

12. Next Chapter Recommendation

In Chapter 8: Data Structures in Jupyter, we will learn how to store and manage large collections of data using Lists, Tuples, and Dictionaries.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·