🚧 Under construction — VoTechWorks is being built. A free tech program — complimentary, as our commitment to get America working.
voTechWorksGrade 13 · a vocational technology learning center, by urbanicity
newSchoolWorks.com › VoTechWorks › Technology & Design › Data Science & Analytics › Python and R for Data Science & Analytics › Lesson 8
TEC-DATA85-03 · Lesson 8 · 11 clock hours · lab

Writing Reproducible Notebooks and Scripts

Objective. Students produce a fully reproducible analytical notebook in Jupyter and an R Markdown report that a classmate can re-run from scratch on a fresh environment and obtain identical output.

⚠ Pending professional review

This lesson, its worked examples and its practice questions has not yet been verified by an industry-certified professional or by a certification or approval body. It is a study draft and may contain errors. Do not use it as instructions for work on a job site or on live equipment. Always follow your instructor, your supervising professional, and current official references and regulations.

VoTechWorks program approval and accreditation are still in progress. Credentials are issued only by the certifying bodies named in each program, after their own exams.

Why Reproducibility Matters

Reproducibility is the ability of another analyst — or your future self — to re-run your analysis on a fresh machine and obtain exactly the same output. In data science, a result that cannot be reproduced is a result that cannot be trusted. Industry certifications, including the IBM Data Science Professional Certificate, treat reproducibility as a core professional competency, not an optional nicety. Employers expect that deliverables handed off between team members, or submitted for audit, will run cleanly without undocumented manual steps.

The Two Biggest Threats to Reproducibility

Environment drift happens when your code depends on a specific version of a library that is not recorded anywhere. A teammate installs a newer version of pandas or ggplot2, runs your notebook, and gets different results or an outright error. The fix is to capture every dependency and its version before you share your work.

Hidden execution state happens when a Jupyter notebook has been run out of order — cell 10 before cell 3 — leaving variables in memory that a fresh run would never create. A notebook that produces correct output in its current session but fails on a clean restart is not reproducible. Always restart the kernel and run all cells top-to-bottom before declaring a notebook complete.

Managing Python Environments with requirements.txt

A `requirements.txt` file is a plain-text list of every Python package your project needs, pinned to an exact version. You generate it inside your active virtual environment with:

```

pip freeze > requirements.txt

```

A collaborator who clones your repository recreates the same environment with:

```

python -m venv env

source env/bin/activate # Windows: env\Scripts\activate

pip install -r requirements.txt

```

Keep the file in the root of your repository alongside your notebooks. Without it, environment setup becomes guesswork.

Structuring a Reproducible Jupyter Notebook

A well-structured notebook reads like a technical report. Apply these practices:

1. One imports cell at the top. All `import` statements go in the first code cell so every dependency is visible immediately.

2. Relative paths only. Never hard-code a path like `C:/Users/maria/Desktop/data.csv`. Use relative paths such as `../data/sales.csv` so the notebook works on any machine where the repository structure is intact.

3. Markdown between every major section. Add a Markdown cell above each logical block explaining what the code does and why. This turns a script into a narrative.

4. Functions instead of repeated code. If you copy and paste a block of code more than once, wrap it in a function. Place all helper functions in an early cell or, for larger projects, in a separate `.py` module that the notebook imports.

5. Restart and run all before sharing. Use Kernel → Restart & Run All and confirm every cell completes without error.

Writing Reproducible R Markdown Reports

R Markdown combines prose, code, and output in a single `.Rmd` file that is knitted into HTML, PDF, or Word. Because knitting always executes code in a clean R session from top to bottom, an R Markdown report is naturally more resistant to hidden-state problems than an interactive session.

Key practices:

Version Control as a Safety Net

Git and GitHub are not just for software developers. Committing your notebook and all supporting files — data (if small), `requirements.txt`, and the `.Rmd` file — creates a timestamped record of every change. If a partner cannot reproduce your results, you can both check out the same commit and eliminate version differences as a cause. Use `.gitignore` to exclude large data files, virtual environment folders, and rendered HTML that should be re-generated locally.

Lab Safety and Data Handling

Data science labs do not involve physical hazards requiring PPE, but professional data handling standards apply. Never commit real personal or proprietary data to a public repository. Use anonymized sample datasets for all lab exercises. If a dataset contains identifiers, remove or mask them before sharing. Treat credentials (API keys, database passwords) as secrets: store them in environment variables or a `.env` file that is listed in `.gitignore`, never hard-coded in a notebook cell.

Key terms8

ReproducibilityThe property of an analysis that allows a different analyst on a different machine to re-run it and obtain identical results without undocumented manual steps.
requirements.txtA plain-text file listing every Python package and its pinned version number needed to recreate the exact environment in which a project was developed.
Virtual environmentAn isolated Python installation that keeps one project's package dependencies separate from those of other projects on the same machine.
R MarkdownA file format (.Rmd) that combines prose written in Markdown with executable R code chunks; knitting the file runs all code in a clean session and produces a formatted report.
set.seed()An R function that fixes the starting point of R's random-number generator so that any random process produces the same result every time the code is run.
Relative pathA file path defined relative to the current project directory (e.g., ../data/file.csv) rather than an absolute machine-specific location, making code portable across different computers.
Kernel restartThe act of clearing all variables and state from a Jupyter session; running all cells after a restart confirms that the notebook executes correctly from a clean starting point.
KnitThe R Markdown process of executing all code chunks in a fresh R session and weaving the code, output, and prose into a final formatted document such as HTML or PDF.
In class: Refactor a prior messy Jupyter notebook by moving repeated code into reusable functions, adding a requirements.txt file listing all package versions, and inserting Markdown headers and explanatory text between every major code section. · Exchange notebooks with a partner who clones the repository, creates a new virtual environment using the requirements.txt, and attempts to run all cells top-to-bottom; the original author must resolve any environment or path errors the partner encounters. · Write an R Markdown report covering the Lesson 7 tidyverse analysis; set a fixed random seed where applicable, use relative file paths, and knit to HTML; a second student knits the .Rmd file on their machine and confirms identical HTML output.
Materials: Jupyter Notebook, RStudio, Git/GitHub, requirements.txt convention, R Markdown documentation (rmarkdown.rstudio.com), lab log
Check: Partner successfully re-runs Jupyter notebook with zero manual intervention after environment setup; R Markdown report knits identically on a second machine — maps to IBM Data Science reproducibility competencies; both conditions required to pass.

Practice check8

Answer each question, then check it. Nothing is recorded; this is your own practice.

IBM Data Science — Reproducibility and Environment Management
1. A classmate clones your repository and runs `pip install -r requirements.txt` but receives an error saying a package is not found. What is the most likely cause?
IBM Data Science — Reproducibility and Environment Management
2. Which Jupyter Notebook action best confirms that a notebook is fully reproducible before sharing it with a partner?
IBM Data Science — Reproducibility and Analytical Rigor
3. In an R Markdown report that includes a train/test split of a dataset, why must `set.seed()` be called before the split?
Google Data Analytics — Data Preparation and Workflow Best Practices
4. A notebook contains the file path `C:/Users/alex/Documents/project/data.csv`. What problem does this create for reproducibility?
IBM Data Science — Python Development Environment
5. Which of the following is the correct command to generate a requirements.txt file from the currently active Python virtual environment?
IBM Data Science — Reproducibility and R Programming
6. You are preparing a reproducible R Markdown report. Which practice best ensures your file paths work on a collaborator's machine?
CompTIA Data+ — Data Analysis Tools and Best Practices
7. A notebook runs successfully on its author's machine but fails when a partner runs it on a fresh machine. The error message says a function from a third-party library does not exist. What is the MOST likely root cause?
CompTIA Data+ — Data Governance, Security, and Professional Standards
8. Why should API keys and database passwords never be hard-coded inside a Jupyter notebook cell, even in a private repository?
Record this lesson on my transcript. Sign in with your key and enrollment email to record lessons (enroll free if you have no key). This page stays open to read and practise.