{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "a1de5d6f",
   "metadata": {},
   "source": [
    "# Google Colab for Beginners: A Step-by-Step Guide\n",
    "\n",
    "Run cells in order. Optional interactive examples are marked and left as text."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9e66b724",
   "metadata": {},
   "source": [
    "## What is Google Colab?\n",
    "\n",
    "[Google Colaboratory](https://colab.research.google.com/) is a hosted Jupyter notebook service that lets you execute Python in a browser. The code runs on a remote machine rather than your own computer. A notebook combines executable code, explanations, equations, tables, and plots in one document.\n",
    "\n",
    "You do not need to install Python or purchase a GPU to begin. A Google account is needed for the normal notebook creation and saving workflow. Free computing resources are subject to availability and usage limits.\n",
    "\n",
    "[Download the companion notebook](/notebooks/google-colab-for-beginners.ipynb) and open it using File > Upload notebook in Colab. You can also follow the instructions below in a blank notebook.\n",
    "\n",
    "## 1. Create your first notebook\n",
    "\n",
    "Open [Google Colab](https://colab.research.google.com/), sign in, and choose New notebook (or File > New notebook). Click the notebook name at the top and rename it `colab_basics.ipynb`. The `.ipynb` extension identifies a Jupyter notebook.\n",
    "\n",
    "The toolbar includes controls for adding code and text cells, while the Files panel provides access to files in the runtime. The Connect button establishes a connection to a computing runtime. Interface labels may vary as Colab updates.\n",
    "\n",
    "## 2. Execute Python code\n",
    "\n",
    "A code cell contains instructions for Python. Enter the following in a code cell and click its play button or press Shift+Enter."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "fc81e1d9",
   "metadata": {},
   "outputs": [],
   "source": [
    "print(\"Hello, Google Colab!\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "35c83493",
   "metadata": {},
   "source": [
    "The output should read `Hello, Google Colab!`. Shift+Enter runs the current cell and moves to the next one; Ctrl+Enter runs the current cell without moving on.\n",
    "\n",
    "Variables store values that can be reused in later calculations."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4469dbf7",
   "metadata": {},
   "outputs": [],
   "source": [
    "x = 10\n",
    "y = 5\n",
    "print(x + y)\n",
    "print(x * y)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "577819dc",
   "metadata": {},
   "source": [
    "The expected outputs are 15 and 50. Python uses `=` for assignment and `**` for exponentiation."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "544c49a3",
   "metadata": {},
   "outputs": [],
   "source": [
    "def square(value):\n",
    "    return value ** 2\n",
    "\n",
    "print(square(6))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8fa91a66",
   "metadata": {},
   "source": [
    "A function packages reusable instructions. This example returns 36.\n",
    "\n",
    "## 3. Understand execution order\n",
    "\n",
    "Notebooks allow cells to run in any order. Variables remain in memory until they are overwritten or the runtime is restarted. The order of execution, not the visual order of cells, determines the current state."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b5f6cf4c",
   "metadata": {},
   "outputs": [],
   "source": [
    "x = 20\n",
    "print(x)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "10e94295",
   "metadata": {},
   "source": [
    "If you rerun the earlier calculation cell, it sets `x` back to 10. This is why a notebook can produce different results when cells are executed out of order. Use Runtime > Run all to check whether a notebook works from beginning to end after restarting the session.\n",
    "\n",
    "## 4. Add text and mathematical equations\n",
    "\n",
    "Use + Text to create a Markdown cell. Markdown is a lightweight formatting language. Paste the following into a text cell rather than a code cell."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "38ec672b",
   "metadata": {},
   "source": [
    "Optional example (copy into a new cell to run or edit):\n",
    "\n",
    "```markdown\n",
    "## My experiment\n",
    "\n",
    "**Objective:** Calculate the square of a number.\n",
    "\n",
    "- Define an input\n",
    "- Perform the calculation\n",
    "- Display the result\n",
    "\n",
    "The equation is $y = x^2$.\n",
    "\n",
    "$$y = x^2$$\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e9b53c63",
   "metadata": {},
   "source": [
    "Single dollar signs create inline equations; double dollar signs create displayed equations. Markdown cells document what your code does and why.\n",
    "\n",
    "## 5. Import and install libraries\n",
    "\n",
    "Libraries provide reusable functionality. NumPy handles numerical arrays, pandas handles tabular data, and Matplotlib produces plots. Colab commonly includes these packages already."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "afce2ea1",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import pandas as pd\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "print(np.__version__)\n",
    "print(pd.__version__)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "70f70df9",
   "metadata": {},
   "source": [
    "If a required package is missing, install it in a code cell using `%pip`. For example:"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d8676f8e",
   "metadata": {},
   "source": [
    "Optional example (copy into a new cell to run or edit):\n",
    "\n",
    "```python\n",
    "%pip install -q numpy pandas matplotlib\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8cc21eab",
   "metadata": {},
   "source": [
    "Run the imports again after installation. If Colab requests a runtime restart, restart and rerun the required cells. Packages installed during a session may disappear when the runtime is replaced.\n",
    "\n",
    "## 6. Create and visualize a dataset\n",
    "\n",
    "The following example creates a small table of numbers and their squares. No machine learning knowledge is needed."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a8e0c0a2",
   "metadata": {},
   "outputs": [],
   "source": [
    "values = np.arange(1, 11)\n",
    "df = pd.DataFrame({\"x\": values, \"y\": values ** 2})\n",
    "display(df)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "721a3635",
   "metadata": {},
   "source": [
    "The table contains ten rows, beginning with (1, 1) and ending with (10, 100). Now visualize the relationship."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "844dc3ad",
   "metadata": {},
   "outputs": [],
   "source": [
    "plt.plot(df[\"x\"], df[\"y\"], marker=\"o\")\n",
    "plt.xlabel(\"x\")\n",
    "plt.ylabel(\"x squared\")\n",
    "plt.title(\"A simple numerical relationship\")\n",
    "plt.grid(True)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cc1effd6",
   "metadata": {},
   "source": [
    "The curve rises increasingly quickly because the output is the square of the input.\n",
    "\n",
    "## 7. Work with files\n",
    "\n",
    "The Files panel lets you upload files from your computer. You can also use Python to save a dataset in the runtime's temporary storage."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cb07d152",
   "metadata": {},
   "outputs": [],
   "source": [
    "df.to_csv(\"/content/example.csv\", index=False)\n",
    "loaded = pd.read_csv(\"/content/example.csv\")\n",
    "display(loaded.head())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1fb12bc8",
   "metadata": {},
   "source": [
    "To download the generated file, run the following cell. Your browser may ask for permission to download it."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2001704a",
   "metadata": {},
   "source": [
    "Optional example (copy into a new cell to run or edit):\n",
    "\n",
    "```python\n",
    "from google.colab import files\n",
    "\n",
    "files.download(\"/content/example.csv\")\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9304780d",
   "metadata": {},
   "source": [
    "To upload a file programmatically, use the following cell and select a file when prompted."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e8c68829",
   "metadata": {},
   "source": [
    "Optional example (copy into a new cell to run or edit):\n",
    "\n",
    "```python\n",
    "from google.colab import files\n",
    "\n",
    "uploaded = files.upload()\n",
    "print(list(uploaded))\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ad732fba",
   "metadata": {},
   "source": [
    "Uploaded files are normally temporary. Do not assume that saving the notebook also saves its runtime files.\n",
    "\n",
    "## 8. Connect Google Drive\n",
    "\n",
    "Google Drive provides persistent storage for notebooks and datasets. Mounting Drive gives code in the notebook access to your authorized Drive files, so only do this in notebooks you trust."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "495326b6",
   "metadata": {},
   "outputs": [],
   "source": [
    "from google.colab import drive\n",
    "\n",
    "drive.mount(\"/content/drive\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8ef496d8",
   "metadata": {},
   "source": [
    "Follow the authorization prompts. Then create a dedicated folder and save the dataset there."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5cdc95ac",
   "metadata": {},
   "outputs": [],
   "source": [
    "from pathlib import Path\n",
    "\n",
    "folder = Path(\"/content/drive/MyDrive/ColabTutorials\")\n",
    "folder.mkdir(parents=True, exist_ok=True)\n",
    "df.to_csv(folder / \"example.csv\", index=False)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "322fee7f",
   "metadata": {},
   "source": [
    "The file should remain in Drive after the runtime disconnects. You can use File > Save a copy in Drive to save a notebook itself, and File > Download > Download .ipynb to keep a local copy.\n",
    "\n",
    "## 9. Select a computing runtime\n",
    "\n",
    "A CPU is sufficient for this entire beginner tutorial. GPUs accelerate many parallel numerical operations, while TPUs are specialized accelerators that require compatible software.\n",
    "\n",
    "To change hardware, open Runtime > Change runtime type, choose an available hardware accelerator, and save the selection. Changing runtime type may reset your session, so save important files first. Selecting a GPU does not automatically make ordinary Python code run on it.\n",
    "\n",
    "## 10. Troubleshoot common problems\n",
    "\n",
    "| Problem | Possible solution |\n",
    "|---|---|\n",
    "| NameError | Run the cell that defines the missing variable. |\n",
    "| ModuleNotFoundError | Install the missing package and import it. |\n",
    "| FileNotFoundError | Check the Files panel and the exact file path. |\n",
    "| Runtime disconnected | Reconnect, rerun setup cells, and restore saved files. |\n",
    "| Unexpected results | Restart the session and run cells in order. |\n",
    "\n",
    "When finished, save your notebook and use the runtime disconnect option if you no longer need the computing resources. Do not share notebooks containing passwords, API keys, or private data.\n",
    "\n",
    "## Practice exercises\n",
    "\n",
    "1. Change the dataset to contain integers from 1 to 20.\n",
    "2. Replace the square operation with a cube operation.\n",
    "3. Change the plot title and axis labels.\n",
    "4. Save the resulting dataset as a new CSV file.\n",
    "5. Restart the runtime and verify that the notebook can be executed again.\n",
    "\n",
    "## Next steps\n",
    "\n",
    "You now know how to create notebooks, execute Python, use libraries, visualize data, and manage files. Continue with [Advanced Google Colab](/articles/advanced-google-colab/) to learn about GPU computing, reproducibility, and larger projects.\n",
    "\n",
    "For additional information, see the [official Colab FAQ](https://research.google.com/colaboratory/faq.html)."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
