DELIGHT Cybersecurity Workbook Series

Google Colab

Enter the access code provided by your instructor to open this workbook.

DELIGHT Cybersecurity Workbook Series  ·  Cloud Computing Series  ·  Python Environments
Guide No. 01
A Complete Introduction

Google
Colab

The cloud notebook that put machine learning in everyone's hands — no installs, no hardware, no barriers. Here's what it is, how it compares to a local Python terminal, who uses it, and why.

Google Colaboratory Python 3 Jupyter-Based Free GPU / TPU Browser-Only

A Notebook That Lives in Your Browser

Google Colaboratory — universally shortened to Colab — is a free, cloud-hosted Python programming environment developed by Google. It runs entirely inside your web browser and requires absolutely nothing to install on your computer. You open a tab, start writing Python, and run it — the code executes on Google's remote servers, not your machine.

At its core, Colab is built on Jupyter Notebook technology: an open-source format that interleaves executable code cells with rich-text documentation cells (written in Markdown). This makes Colab ideal not just for running code, but for telling the story around that code — explaining what each step does, why it matters, and what the results mean. It is simultaneously a programming environment, a documentation tool, and a presentation medium.

"Colab is to Python what Google Docs is to Microsoft Word — it moved the work to the cloud, made collaboration instant, and eliminated the setup tax entirely."

— Common description among data science educators
my_first_colab.ipynb  ·  Google Colab
FileEditRuntimeHelp
markdown
## My First Colab Notebook This cell contains formatted text. The next cell contains runnable Python code.
[ 1 ]
import pandas as pd import matplotlib.pyplot as plt data = pd.DataFrame({'Score': [72, 88, 91, 65, 77, 95, 83]}) print("Mean score:", data['Score'].mean()) data.plot(kind='hist', title='Score Distribution') plt.show()
Mean score: 81.57142857142857 [Chart rendered inline below ↓]
[ 2 ]
# Install any library with a single command — no admin rights needed !pip install seaborn --quiet print("✅ seaborn ready to use")
✅ seaborn ready to use

Each code cell is an independent, runnable block. You click the play button (or press Shift + Enter) and the output appears immediately below that cell — plots, tables, printed values, even interactive widgets. Each text cell renders formatted prose, headings, maths (LaTeX), and images, letting you narrate your analysis in-line with the code that produces it.

💡
Key point: Colab notebooks are saved as .ipynb files (Interactive Python Notebook) directly to your Google Drive. They are also version-controlled by Google, meaning you can view the full edit history — just like a Google Doc.

Two Ways to Run Python — One Important Choice

Both Google Colab and a conventional Python terminal execute the same Python language. The differences are in where the code runs, how you interact with it, and what you can do with it. Understanding these differences helps you choose the right tool for each job.

☁  Google Colab — Cloud Notebook
# In Colab, you type in a cell UI # and click ▶ or press Shift+Enter In [1]: x = 10 y = 20 print(x + y) Out[1]: 30 In [2]: import matplotlib.pyplot as plt plt.plot([1,2,3],[4,9,16]) plt.show() [Chart appears inline ↓] 📊
⬛ Python Terminal — Local Shell
# In terminal, you type line by line # or run a .py script file $ python3 script.py # or interactively: $ python3 >>> x = 10 >>> y = 20 >>> print(x + y) 30 >>> import matplotlib.pyplot as plt >>> plt.plot([1,2,3],[4,9,16]) >>> plt.show() # Window pops up separately # No inline rendering
🌐
Google Colab
cloud · browser · notebook
No installation required. Open a browser tab and start coding immediately.
Free GPU and TPU access. Google provides NVIDIA GPU runtime for deep learning workloads — no hardware purchase.
Inline output. Charts, dataframes, images, and widgets render directly below each cell — not in a separate window.
Real-time collaboration. Share a link and multiple people can view and edit the same notebook simultaneously, like Google Docs.
Pre-installed libraries. NumPy, Pandas, TensorFlow, PyTorch, sklearn, and hundreds more are ready to import immediately.
Google Drive integration. Notebooks save automatically and can read/write files directly from your Drive.
Session time limits. Free tier disconnects after 90 minutes of idle time or 12 hours maximum per session.
Internet required. Cannot run offline — all computation happens on Google's servers, not locally.
Shared compute. Free GPU access is shared; you may be queued or limited during peak usage.
Python Terminal
local · shell · script-based
Works completely offline. No internet connection needed once Python is installed. Ideal for secure environments.
No time limits. A script can run for days or weeks without interruption — essential for long training jobs.
Full system access. Read/write any directory, call OS commands, connect to databases, use hardware peripherals.
Automation-friendly. Python scripts can be scheduled, chained, and run headlessly — ideal for production pipelines.
Your own hardware. For very large local datasets or specialised hardware (custom GPUs, sensors), local execution is mandatory.
Setup friction. Must install Python, pip, virtual environments, and every library yourself. Version conflicts are common.
No inline output. Plots open in separate windows; there is no native way to mix code, output, and explanation in one document.
Sharing is harder. Sending your work requires others to have the same Python version, OS, and libraries installed.
No free GPU. Any GPU access requires purchasing hardware or paying a cloud provider separately.

Feature-by-Feature Comparison at a Glance

Feature Google Colab Python Terminal Winner
Setup time Zero — open browser and go Minutes to hours (install Python, pip, venv, packages) ☁ Colab
Hardware requirement Any device with a modern browser, even a Chromebook or tablet Needs a capable machine; GPU requires specific hardware ☁ Colab
Free GPU/TPU access Yes — NVIDIA T4 GPU and Google TPU v2 available free No — must purchase hardware or pay cloud provider ☁ Colab
Offline use Not supported — internet connection mandatory Fully offline — no internet needed after setup ⬛ Terminal
Session continuity Resets after idle or 12 hr max (free tier) Unlimited runtime — runs indefinitely ⬛ Terminal
Output presentation Rich inline: charts, tables, HTML widgets in-cell Text only inline; charts open in external window ☁ Colab
Collaboration Real-time sharing via link — like Google Docs Requires file sharing (Git, email, USB drive) ☁ Colab
Library management Most ML libs pre-installed; use !pip install in a cell Explicit pip install + virtual environments needed ☁ Colab
Production deployment Not suitable — interactive notebooks don't scale to production Standard — Python scripts run on servers, in cron jobs, pipelines ⬛ Terminal
Privacy / data security Data is uploaded to Google servers — not for sensitive data Fully local — data never leaves your machine ⬛ Terminal
Debugging experience Cell-level debugging with variable inspector; some limitations Full-featured debugger (pdb, IDE integration) ⬛ Terminal
Documentation + code Native: Markdown + code + outputs in one scrollable document Requires separate README files or comments only ☁ Colab
Cost Free tier available; Pro at ~$10/month for more GPU time Free (open-source Python) — hardware cost only ⚖ Tie
Version control (Git) Basic GitHub sync; notebooks don't diff cleanly in Git Full Git integration — scripts are plain text, diff perfectly ⬛ Terminal
🔄
Not either/or: Most professional data scientists use both. They prototype and explore in Colab (or Jupyter), then migrate clean code to Python scripts for production. Colab is the laboratory; the terminal is the factory floor.

What Makes Colab Different

Colab is not simply "Python in a browser." It is a platform with a set of features specifically engineered for data science, machine learning, and education. Each feature below addresses a real friction point that conventional Python environments leave unsolved.

🖥️
Free GPU & TPU Runtimes
Switch your runtime to GPU (NVIDIA T4, A100 on Pro) or Google's own TPU v2 in one click. Training deep learning models that would take hours on CPU finishes in minutes. This is Colab's single most impactful differentiator — it democratised access to accelerated compute.
📦
Pre-installed Libraries
NumPy, Pandas, Matplotlib, Seaborn, Scikit-learn, TensorFlow, PyTorch, Keras, OpenCV, NLTK, spaCy, and hundreds more are pre-installed in every runtime. No pip install setup required. Run !pip install in a cell to add anything extra.
☁️
Google Drive Integration
Mount your entire Google Drive with two lines of code. Read CSV files, load images, save model checkpoints — everything persists to your Drive even after the session ends. Combined with Google Sheets integration, it forms a complete data pipeline.
👥
Real-Time Collaboration
Share a Colab notebook link and collaborators can view (or edit, with permission) in real time. Comments can be added to specific cells. This is far more powerful than emailing .py files — the code, outputs, and discussion all live together.
📄
Text + Code = One Document
Mix Markdown text cells (with headings, bold, LaTeX maths, images, and links) with code cells. The notebook tells a complete story — hypothesis, code, results, and interpretation — all in one scrollable, shareable document. Perfect for reports, tutorials, and papers.
🔒
Secrets Manager
Store API keys, database passwords, and tokens in the Secrets panel (🔑 icon in the sidebar). Access them in code as userdata.get('MY_KEY') without ever exposing sensitive values in the notebook itself or in version control.
📊
Interactive Widgets & Forms
Create interactive UI elements with @param decorators: dropdowns, sliders, text inputs, and checkboxes that update code behaviour without editing the code itself. Great for demos and building small tools for non-technical teammates.
🧠
Gemini AI Assistance
Built-in AI code completion, explanation, and error diagnosis powered by Google's Gemini model. Highlight code and ask it to explain, optimise, or debug. Generates code from natural-language descriptions inside the editor.
🐙
GitHub Integration
Open notebooks directly from GitHub repositories with a single URL change (github.comcolab.research.google.com/github/). Save notebooks back to GitHub. Colab's "Open in Colab" badge is standard on ML research repositories.
⌨️
Shell & System Commands
Prefix any command with ! to run it in the underlying Linux shell: !ls, !wget https://..., !unzip file.zip, !nvidia-smi. The Colab runtime is a full Ubuntu VM — you have root access to the runtime environment.
📁
File Browser & Upload
The Files panel in the left sidebar lets you browse the runtime filesystem, upload files from your computer, and download outputs. Or use from google.colab import files; files.upload() programmatically to build file-upload flows directly in your notebook.
🔢
Variable Inspector
The Variables panel (sidebar) lists every variable currently in memory — its name, type, shape (for arrays/DataFrames), and value. No need to print everything to understand what is in memory. Invaluable for debugging complex data pipelines.

Colab Plans — Free, Pro, and Enterprise

Colab has three tiers. The free tier is generous enough for most students and exploratory work. Pro and Pro+ provide longer runtimes, priority GPU access, and more RAM for demanding models.

Colab Free
$0 / mo
  • T4 GPU (shared, limited hours)
  • 12.7 GB RAM
  • 107 GB disk
  • Max 12 hrs session
  • Disconnects on idle (90 min)
  • Pre-installed ML libraries
  • Google Drive integration
Colab Pro / Pro+
~$10–50 / mo
  • A100 / V100 GPU priority
  • Up to 52 GB RAM
  • 225 GB disk
  • 24 hrs session (Pro+)
  • Background execution (Pro+)
  • Fewer interruptions
  • Terminal access (Pro+)
Colab Enterprise
Custom
  • Vertex AI integration
  • BigQuery direct access
  • VPC networking support
  • Admin controls & audit logs
  • No session time limits
  • Private compute options
  • Google Workspace SSO
🎓
For students: The free tier is completely sufficient for every exercise in this course, including training Random Forest, KNN, and Decision Tree classifiers on the malware dataset. You only need to upgrade if your model training consistently exhausts the 12-hour session limit or if you begin training deep neural networks that require more than 12 GB of RAM.

From First-Year Students to Research Labs

Colab's combination of zero setup, free compute, and document-like format has made it the default working environment for an unusually broad community — from school students writing their first Python line to Google's own AI researchers publishing state-of-the-art models. Here is who uses it and why.

🎓
Students & Learners
The primary beneficiaries. No setup barrier means a student can go from "never written Python" to running a trained ML model in under one hour. Thousands of courses use Colab so every student starts from identical conditions regardless of their laptop.
📐
Data Scientists
Use Colab for exploratory data analysis, prototyping models, and creating shareable reports for stakeholders. The inline chart rendering and Markdown narration make Colab notebooks the standard format for communicating analytical findings.
🤖
ML / AI Researchers
Google Research and hundreds of academic teams publish their paper code as Colab notebooks with "Open in Colab" badges. Anyone can run a state-of-the-art model from a recent NeurIPS paper with one click — no cluster access required.
🏫
Educators & Instructors
Teachers distribute assignments as Colab notebooks — students complete cells and return the same file. The "teaching notebook" format (explanation + blank cells to fill in) is one of the most popular pedagogical tools in data science education today.
⚗️
Scientists & Researchers
Biologists, physicists, economists, and social scientists who need Python for analysis but are not professional programmers. Colab's narrative format suits scientific methodology: hypothesis → code → result → interpretation in one reproducible document.
🛠️
Independent Developers
Use free GPU time to fine-tune language models, generate images with Stable Diffusion, or test computer vision pipelines without paying for cloud compute. Colab is a popular "free tier" for GPU-intensive experiments that don't justify a monthly cloud bill.
📊
Business Analysts
Non-technical analysts who work with Python-savvy colleagues. They receive Colab notebooks as interactive reports — they can re-run cells to see updated results with new data, without needing to understand the code itself.
🔬
Kaggle Competitors
Competitive ML practitioners use Colab (alongside Kaggle's own notebooks) to train models on competition datasets. The free GPU access and ability to quickly share experiments with teammates makes it an essential tool in the competitive data science ecosystem.
📈
Scale: As of 2024, Google Colab hosts millions of active notebooks. It is used in courses at MIT, Stanford, Oxford, and universities across every continent. The @colab.research.google.com domain consistently ranks among the most-visited programming environments on the web.

When to Use Colab — and When Not To

Colab excels in specific scenarios. Knowing its limits prevents frustration when you choose it for the wrong job. Use this guide to pick the right tool every time.

✅ Choose Colab when…

You are learning Python or data science. Zero setup means you focus on concepts, not configuration. The notebook format encourages experimentation and makes it easy to revisit and understand your own work later.
You need GPU compute and don't want to pay. Training neural networks, fine-tuning transformers, or running computer vision pipelines on a free NVIDIA GPU is Colab's single greatest practical advantage.
You want to share reproducible analysis. A Colab notebook URL lets anyone run your exact analysis — same code, same library versions, same outputs. This is the gold standard for reproducible research and teaching.
You are prototyping a model or exploring data. Colab's interactive cell-by-cell execution is perfect for exploratory work where you iterate quickly, inspect intermediate results, and change direction often.

❌ Choose a Local Terminal instead when…

Your code runs longer than 12 hours. Training large models, processing huge datasets, or running long simulations will be interrupted by Colab's session limits. A local machine or dedicated cloud VM is needed.
Your data is confidential. Medical records, financial data, personally identifiable information, or any data under a privacy regulation (GDPR, HIPAA) should never be uploaded to Google's servers. Run locally.
You are building a production system. No application should be deployed from a Colab notebook. Convert your code to .py scripts, set up a proper environment, and deploy on a server or cloud function.
You need internet-free execution. Field research, secure government systems, or any scenario where internet access is unavailable or prohibited requires a local Python installation.

"Use Colab to ask the question. Use a terminal to ship the answer."

— A practical rule of thumb in production data science

Essential Colab Commands & Shortcuts

These are the most commonly used commands and keyboard shortcuts for working efficiently in Colab. Print this page and keep it beside you for your first few sessions.

ActionHow to do itNotes
Run current cellShift + EnterRuns cell and moves focus to next cell
Run cell (stay in cell)Ctrl + EnterRuns cell, cursor stays in same cell
Add code cell belowCtrl + M + BOr click + Code button in toolbar
Add text cell belowCtrl + M + MOr click + Text button
Delete a cellCtrl + M + DCannot undo — be careful
Run all cellsRuntime → Run AllRestarts kernel and runs top-to-bottom
Stop executionClick ■ stop buttonOr Runtime → Interrupt execution
Install a library!pip install librarynameRun in a code cell; takes effect immediately
Mount Google Drivefrom google.colab import drive; drive.mount('/content/drive')Then access files at /content/drive/MyDrive/
Upload a filefrom google.colab import files; files.upload()File picker appears inline
Download a filefrom google.colab import files; files.download('myfile.csv')Triggers browser download
Check GPU info!nvidia-smiShows GPU model, memory, and utilisation
Check Python version!python --versionAlso import sys; sys.version
List files in runtime!ls /content/The runtime filesystem is at /content/
Switch to GPU runtimeRuntime → Change runtime type → GPURestarts session — save variables beforehand
🚀
Get started in 30 seconds: Go to colab.research.google.com, sign in with your Google account, click New Notebook, type print("Hello, Colab!") in the first cell, and press Shift + Enter. You are running Python in the cloud.

How Colab Connects to the Wider Python World

Colab is not an island. It sits at the centre of a rich ecosystem of tools that data scientists, researchers, and engineers use every day. Understanding these connections transforms Colab from "a place to run Python" into a complete cloud data-science workbench.

Google Drive — Your Persistent Storage Layer

Every Colab session starts with a fresh runtime filesystem at /content/. When the session ends, anything stored there is lost. Google Drive is the solution: mount it in two lines and all your files, datasets, and saved models persist permanently across sessions.

drive_integration.ipynb
[ 1 ]
from google.colab import drive # Mount your entire Google Drive at /content/drive/ # A browser popup asks you to authorise access once drive.mount('/content/drive') # Now read any file from Drive as if it were local import pandas as pd df = pd.read_csv('/content/drive/MyDrive/data/malwares.csv') print(f"Loaded {len(df):,} rows from Drive")
Mounted at /content/drive Loaded 47,234 rows from Drive
[ 2 ]
import pickle # Save a trained model directly to Drive — it survives session resets model_path = '/content/drive/MyDrive/models/malware_rf.pkl' with open(model_path, 'wb') as f: pickle.dump(trained_model, f) print("✅ Model saved to Google Drive — safe even after session ends")
✅ Model saved to Google Drive — safe even after session ends

GitHub — Version Control for Notebooks

Colab has first-class GitHub support. You can open any public notebook from GitHub by simply replacing github.com with colab.research.google.com/github in the URL. Saving back to GitHub creates commits directly from the Colab UI. This workflow is standard in academic ML research: authors publish paper code to GitHub with an "Open in Colab" badge so anyone can reproduce results with one click, no setup required.

github_workflow.ipynb
[ 1 ]
# Clone any GitHub repository directly into your runtime !git clone https://github.com/username/my-ml-project.git # Change into the project directory import os os.chdir('/content/my-ml-project') # Install the project's dependencies from requirements.txt !pip install -r requirements.txt --quiet print("✅ Repository ready")
Cloning into 'my-ml-project'... ✅ Repository ready
[ 2 ]
# Save notebook back to GitHub (File → Save a copy in GitHub) # Or use git commands directly in a code cell: !git add results/experiment_01.ipynb !git commit -m "Add experiment 01 results — RF accuracy 99.2%" !git push origin main
[main abc1234] Add experiment 01 results — RF accuracy 99.2% 1 file changed, 847 insertions(+)

Google BigQuery — Querying Massive Datasets

BigQuery is Google's enterprise data warehouse, capable of querying terabytes of data with SQL in seconds. Colab integrates with BigQuery via the google-cloud-bigquery library and a built-in magic command. This combination is used by data analysts who need to pull large aggregated results from a data warehouse, then analyse and visualise them in a notebook — without ever exporting a CSV file.

bigquery_demo.ipynb
[ 1 ]
from google.colab import auth from google.cloud import bigquery # Authenticate with your Google account auth.authenticate_user() # Run a SQL query and load results straight into a DataFrame client = bigquery.Client(project='my-gcp-project') query = """ SELECT country, COUNT(*) as users FROM `bigquery-public-data.census_bureau_usa.population_by_zip_2010` GROUP BY country ORDER BY users DESC LIMIT 10 """ df = client.query(query).to_dataframe() print(df)
country users 0 US 3142459 1 PR 78765 ...

Hugging Face — Transformers in One Line

The Hugging Face transformers library gives you access to thousands of pre-trained AI models — BERT, GPT-2, Llama, Whisper, CLIP, and more — with a single pip install. Colab's free GPU runtime makes it practical to run inference on these large models without any hardware. This is how most students first experience large language models and computer vision transformers: a Colab notebook that downloads a model and runs it live.

huggingface_demo.ipynb
[ 1 ]
!pip install transformers --quiet from transformers import pipeline # Load a pre-trained sentiment analysis model from Hugging Face # Downloads ~250 MB to the Colab runtime — done in ~30 seconds on GPU classifier = pipeline("sentiment-analysis") result = classifier("Google Colab makes machine learning incredibly accessible!") print(result)
[{'label': 'POSITIVE', 'score': 0.9998}]

Kaggle Datasets — Data in Two Lines

Kaggle hosts over 200,000 public datasets. With the Kaggle API and your credentials file, you can download any dataset directly into your Colab runtime — no browser download, no file upload, just code.

kaggle_data.ipynb
[ 1 ]
from google.colab import files import os, json # Upload your kaggle.json API token (one-time step) files.upload() # select kaggle.json from your computer # Place credentials where the Kaggle CLI expects them os.makedirs('/root/.kaggle', exist_ok=True) !mv kaggle.json /root/.kaggle/ !chmod 600 /root/.kaggle/kaggle.json # Download the malware dataset directly into the runtime !kaggle datasets download -d username/dataset-malwares --unzip print("✅ Dataset downloaded and unzipped")
Downloading dataset-malwares.zip to /content ✅ Dataset downloaded and unzipped

The Colab Ecosystem at a Glance

IntegrationWhat it providesCommon use case
Google DrivePersistent file storage, CSV/image/model files survive session resetsLoad datasets, save model checkpoints, share outputs
Google SheetsRead/write spreadsheet data directly via gspread or the Sheets APINon-technical stakeholders update a sheet; Colab analyses it
BigQuerySQL queries against terabyte-scale data warehousesPull aggregated analytics data for visualisation or ML
GitHubClone repos, push notebooks, open notebooks via URL badgeReproducible research, assignment distribution, collaboration
Hugging Face10,000+ pre-trained NLP/vision/audio models via transformersText classification, translation, image captioning, speech-to-text
Kaggle200,000+ public datasets and competition data via APIDownload training data without leaving the notebook
Weights & BiasesExperiment tracking — logs metrics, hyperparameters, model artifactsCompare training runs, track accuracy across experiments
TensorBoardBuilt-in visualisation for neural network training — loss curves, histogramsMonitor deep learning training in real time
OpenCV / PILImage processing, loading, and transformation in-cellComputer vision preprocessing, augmentation pipelines
Gradio / StreamlitBuild interactive ML demos with a UI directly from ColabCreate a shareable demo app from a trained model in minutes
🔗
The bigger picture: Colab is Google's on-ramp to its entire cloud platform. Students who learn data science in Colab are only a few configuration steps away from running the same workflows on Google Cloud's Vertex AI, Dataflow, and BigQuery ML — enterprise-scale infrastructure that powers some of the world's largest data systems.

Errors Every New Colab User Hits — Solved

Most frustration with Colab comes from a small set of predictable misunderstandings about how sessions, runtimes, and the filesystem work. This section documents every common issue and its solution, so you spend time learning Python — not fighting the environment.

Mistake 1 — Running cells out of order

Unlike a Python script that always runs top-to-bottom, Colab lets you run any cell in any order. This is powerful but dangerous. If you run Cell 5 before Cell 2, and Cell 5 depends on a variable defined in Cell 2, you will get a NameError. Worse: you might get a silently wrong result if Cell 5 uses a stale variable from a previous run.

cell_order_mistake.ipynb
[ 3 ]← ran this FIRST by accident
# This cell uses 'model' — but model is defined in Cell 5 below predictions = model.predict(X_test)
NameError: name 'model' is not defined
[ 5 ]
# model is only created here — must run BEFORE Cell 3 from sklearn.ensemble import RandomForestClassifier model = RandomForestClassifier() model.fit(X_train, y_train)
RandomForestClassifier()
🔧
Fix: Always use Runtime → Run all before sharing or submitting a notebook. This restarts the kernel and runs every cell in order — guaranteeing your notebook works as a complete, self-contained document. Cell numbers in brackets show the execution order; [*] means currently running.

Mistake 2 — Variables lost after session reset

Colab sessions reset when: your browser tab is closed, you are idle for 90 minutes (free tier), the 12-hour session limit is reached, or you click Runtime → Disconnect and delete runtime. After a reset, the runtime is a completely fresh environment — all variables, installed packages, and files in /content/ are gone. This catches students off guard when they reopen a notebook the next day and get NameError on every cell.

⚠️
What is lost on reset: All variables and objects in memory · All !pip install installations · All files in /content/ that were not saved to Drive · The runtime's execution history (cell numbers reset to [ ]).
Fix: (1) Always save important files to Google Drive, not /content/. (2) Keep your !pip install and drive.mount() commands in the first few cells so re-running is fast. (3) After a reset, use Runtime → Run all to restore your working state in one click.

Mistake 3 — Uploading files that disappear on reset

Using the Files panel to upload a dataset feels convenient — until the session resets and the file is gone. Students who upload large CSV files (50 MB+) are particularly frustrated when they have to re-upload after every session.

Fix: Always put your data files in Google Drive and mount Drive in the first cell. One line of code is far faster than re-uploading a large file. For very large datasets, consider using Kaggle's API or wget/gdown to download directly into the runtime from a URL.

Mistake 4 — pip installs not persisting

You install a library with !pip install somelib, use it successfully, close the tab, and next session it is gone. Libraries installed with !pip install only persist for the current runtime session — they are not saved to your Google Drive.

persistent_installs.ipynb
[ 1 ]
# ✅ Best practice: install all non-standard libraries in the FIRST cell # so a single "Run all" after a reset restores everything automatically !pip install pefile xgboost shap gradio --quiet print("✅ All custom libraries installed")
✅ All custom libraries installed

Mistake 5 — Forgetting GPU is not always available

The free-tier GPU is shared among all Colab users. At peak times, Google may assign you a CPU-only runtime even if you requested GPU, or switch you mid-session. Always check your runtime type at the start of a session and verify before starting a long training job.

gpu_check.ipynb
[ 1 ]
import torch # Always verify GPU availability before a long training run if torch.cuda.is_available(): gpu_name = torch.cuda.get_device_name(0) gpu_mem = torch.cuda.get_device_properties(0).total_memory / 1e9 print(f"✅ GPU ready: {gpu_name} ({gpu_mem:.1f} GB VRAM)") else: print("⚠️ No GPU detected — go to Runtime → Change runtime type → GPU")
✅ GPU ready: Tesla T4 (15.8 GB VRAM)
[ 2 ]
# For scikit-learn models (non-deep learning), GPU is not needed # Random Forest, KNN, Decision Tree all run on CPU and train quickly # Only switch to GPU when using TensorFlow, PyTorch, or XGBoost with GPU support !nvidia-smi # detailed GPU info: model, memory usage, running processes
+-----------------------------------------------------------------------------+ | NVIDIA-SMI 525.105.17 Driver Version: 525.105.17 CUDA Version: 12.0 | | GPU Name: Tesla T4 | Temp: 35C | Mem: 384MiB / 15360MiB | +-----------------------------------------------------------------------------+

Quick Error Reference

Error / ProblemRoot CauseFix
NameError: name 'x' is not definedCell that defines x was not run yet, or session resetRun all cells from the top (Runtime → Run all)
ModuleNotFoundError: No module named 'pefile'Library not installed in this session (session reset cleared it)Re-run your !pip install cell at the top
FileNotFoundError: dataset.csv not foundFile was in /content/ which reset, or path is wrongMount Drive and use the Drive path, or re-upload
Session keeps disconnecting90-minute idle timeout on free tierKeep the tab active or upgrade to Pro; use Drive to checkpoint work
RAM full / session crashesDataset or model too large for free-tier 12 GB RAMUse chunked reading (pd.read_csv(..., chunksize=10000)), reduce model size, or upgrade to Pro
GPU not faster than CPUModel/data too small to benefit from GPU parallelismScikit-learn models run on CPU — GPU matters for neural networks with large batch sizes
KeyboardInterrupt mid-trainingCell was interrupted by idle timeout or manual stopCheckpoint model weights to Drive every N epochs so training can resume
Charts not showing inlineMissing plt.show() or wrong backendAdd %matplotlib inline to the top of your notebook (once per session)
Drive not mounted errorDrive mount was not re-run after session resetPut drive.mount('/content/drive') in Cell 1 and always run from top
Output cell shows [*] foreverCell is stuck in an infinite loop or very long computationClick the ■ stop button, then fix the loop logic before re-running

Test Your Understanding — Interactive Quiz

Answer the ten questions below to check how well you have absorbed this guide. Each question covers a key concept from Sections 1–8. Your score is shown at the end. No sign-in needed — this runs entirely in your browser.

Question 1 of 10

Everything You Need to Remember

Here is the complete picture in compact form — a reference card you can return to whenever you need a quick refresher.

TopicThe Key Point
What Colab isA free, browser-based Python notebook hosted on Google's servers. Built on Jupyter. No installation required. Saves to Google Drive as .ipynb files.
How it worksCode runs on Google's remote Linux VM, not your machine. Your browser is just the interface. Results stream back and render inline below each cell.
CellsTwo types: Code cells (run Python, shell commands with !) and Text cells (Markdown, LaTeX, images). Mix freely to create a narrative document.
Biggest advantage vs terminalFree GPU/TPU access + zero setup + inline output + real-time sharing. Removes every barrier to starting machine learning.
Biggest limitation vs terminalSessions reset (12-hour limit), no offline use, data uploaded to Google's servers (privacy concern), not suitable for production deployment.
When to use ColabLearning, prototyping, exploratory data analysis, model training (especially with GPU), teaching, sharing reproducible results, collaborative projects.
When to use terminalProduction code, long-running jobs, sensitive data, offline environments, automation/scheduling, professional software engineering workflows.
Persistence rule/content/ is temporary — always save important files to Google Drive. Libraries installed with !pip install also reset each session.
GPU ruleScikit-learn (Random Forest, KNN, etc.) runs on CPU — no GPU needed. GPU matters for TensorFlow/PyTorch neural networks. Always verify with !nvidia-smi.
Best practiceCell 1: install libraries. Cell 2: mount Drive. Cell 3: load data. Run all after every reset. Use Runtime → Run all before sharing.
Colab Free tier limitsNVIDIA T4 GPU (shared), 12.7 GB RAM, 12-hour sessions, 90-minute idle timeout. Sufficient for all introductory and intermediate ML coursework.
Who uses itStudents, data scientists, ML researchers, educators, scientists, independent developers, business analysts, Kaggle competitors.
🎯
The one-line summary: Google Colab gives you a professional Python + GPU environment, instantly, for free, in your browser — making it the most accessible entry point into data science and machine learning ever created. Its limitations (session resets, no offline access, privacy considerations) are all manageable once you understand them. Start with Colab; scale to a terminal when your project demands it.