{ "cells": [ { "cell_type": "markdown", "id": "3213a9fe", "metadata": {}, "source": [ "# 1. 🐍 Introduction to Python: Basics\n", "\n", "![Status](https://img.shields.io/static/v1.svg?label=Status&message=Finished&color=green)\n", "\n", "**Filled notebook:** \n", "[![View filled on Github](https://img.shields.io/static/v1.svg?logo=github&label=Repo&message=View%20On%20Github&color=lightgrey)](https://github.com/bfortuno/Surgical-Phase-Recognition/blob/main/docs/tutorial_notebooks/tutorial1/python_basics_1.ipynb)\n", "[![Open filled In Collab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/bfortuno/Surgical-Phase-Recognition/blob/main/docs/tutorial_notebooks/tutorial1/python_basics_1.ipynb) \n", "**Author:** Benjamin I. Fortuno\n", "\n", "**📌 Learning Objectives:**\n", "- Understand Python fundamentals\n", "- Work with lists and dictionaries\n", "- Read and process CSV files\n", "- Compute basic statistics" ] }, { "cell_type": "code", "execution_count": null, "id": "45f5ecc8", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Not running on CoLab\n" ] } ], "source": [ "# Setup the environment for the tutorial notebook to run on CoLab\n", "# This script will clone the repository and change the working directory to the tutorial notebook directory\n", "if 'google.colab' in str(get_ipython()):\n", " print('Running on CoLab')\n", " !git clone https://github.com/bfortuno/Surgical-Phase-Recognition.git # Clone the repository\n", " %cd Surgical-Phase-Recognition/docs/tutorial_notebooks/tutorial1\n", "else:\n", " print('Not running on CoLab')" ] }, { "cell_type": "markdown", "id": "2d885f5e", "metadata": {}, "source": [ "## **1 Python Basics**\n", "### **1.1 Variables & Data Types**\n", "\n", "In Python, variables store values. Let's look at some common data types:" ] }, { "cell_type": "code", "execution_count": 3, "id": "df8880d6", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "10 3.14 Hello, AI! True\n" ] } ], "source": [ "# Integer\n", "a = 10\n", "\n", "# Float\n", "b = 3.14\n", "\n", "# String\n", "c = 'Hello, AI!'\n", "\n", "# Boolean\n", "d = True\n", "\n", "# Print values\n", "print(a, b, c, d)" ] }, { "cell_type": "markdown", "id": "9e0d95e8", "metadata": {}, "source": [ "👉 **Task**: Try defining your own variables and print them." ] }, { "cell_type": "markdown", "id": "70481563", "metadata": {}, "source": [ "### **1.2 Conditionals and Loops**\n", "\n", "**If-else statements** allow decision-making:" ] }, { "cell_type": "code", "execution_count": 4, "id": "2226bbcb", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Positive number\n" ] } ], "source": [ "x = 5\n", "if x > 0:\n", " print('Positive number')\n", "else:\n", " print('Negative number')" ] }, { "cell_type": "markdown", "id": "c43eb7b1", "metadata": {}, "source": [ "Loops allow us to execute a block of code multiple times. Python has two main types of loops: \n", "1. **`for` loop** – Used when the number of iterations is known.\n", "2. **`while` loop** – Used when the number of iterations depends on a condition.\n", "\n", "---\n", "\n", "### 🌀 For Loop\n", "\n", "```python\n", "# For loop\n", "for i in range(5):\n", " print(i)\n", "```\n", "#### 🔍 Explanation:\n", "- `range(5)` generates numbers from **0 to 4** (not including 5).\n", "- The loop runs **5 times**, each time printing the current value of `i`.\n", "- The loop automatically increments `i` in each iteration.\n", "\n", "#### ⚠️ Things to Be Careful About:\n", "- **Indexing Issues**: `range(n)` starts from **0** and goes up to **n-1**, not `n`.\n", "- **Skipping Values**: To loop from **1 to 5**, use `range(1, 6)`.\n", " ```python\n", " for i in range(1, 6): # Generates 1, 2, 3, 4, 5\n", " print(i)\n", " ```\n", "- **Step Size**: Use a third argument for step size.\n", " ```python\n", " for i in range(0, 10, 2): # Prints even numbers 0, 2, 4, 6, 8\n", " print(i)\n", " ```\n", "\n", "---\n", "\n", "### 🔄 While Loop\n", "```python\n", "# While loop\n", "count = 0\n", "while count < 3:\n", " print('Count:', count)\n", " count += 1\n", "```\n", "#### 🔍 Explanation:\n", "- The loop **executes as long as** `count < 3`.\n", "- The variable `count` starts at **0** and increases by **1** in each iteration.\n", "- When `count == 3`, the loop condition (`count < 3`) becomes **False**, and the loop stops.\n", "\n", "#### ⚠️ Things to Be Careful About:\n", "- **Infinite Loops**: If `count` is not incremented inside the loop, it will run forever.\n", " ```python\n", " while True: # ⚠️ Infinite loop\n", " print(\"This will run forever!\")\n", " ```\n", "- **Proper Condition**: Ensure the loop will eventually stop. A faulty condition may cause the program to hang.\n", "- **Changing Condition Inside the Loop**: If the value of `count` is not updated properly, the loop may behave unexpectedly." ] }, { "cell_type": "code", "execution_count": 5, "id": "6f49372f", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0\n", "1\n", "2\n", "3\n", "4\n", "Count: 0\n", "Count: 1\n", "Count: 2\n" ] } ], "source": [ "# For loop\n", "for i in range(5):\n", " print(i)\n", "\n", "# While loop\n", "count = 0\n", "while count < 3:\n", " print('Count:', count)\n", " count += 1" ] }, { "cell_type": "markdown", "id": "76cfd4d6", "metadata": {}, "source": [ "👉 **Task**: Modify the loops to print numbers from 1 to 10." ] }, { "cell_type": "markdown", "id": "8860a99a", "metadata": {}, "source": [ "## **2 Functions in Python**\n", "\n", "Functions help organize code into reusable blocks:" ] }, { "cell_type": "code", "execution_count": 6, "id": "429a0748", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "8\n" ] } ], "source": [ "def add_numbers(x, y):\n", " return x + y\n", "\n", "print(add_numbers(3, 5))" ] }, { "cell_type": "markdown", "id": "b18cd385", "metadata": {}, "source": [ "👉 **Task**: Write a function that multiplies two numbers." ] }, { "cell_type": "markdown", "id": "7b931b8a", "metadata": {}, "source": [ "## **3 Lists and Dictionaries**\n", "\n", "### **3.1 Lists (Arrays in Python)**" ] }, { "cell_type": "code", "execution_count": 7, "id": "7def08b5", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1\n", "1\n", "2\n", "3\n", "4\n", "5\n" ] } ], "source": [ "numbers = [1, 2, 3, 4, 5]\n", "\n", "# Access elements\n", "print(numbers[0])\n", "\n", "# Loop through list\n", "for num in numbers:\n", " print(num)" ] }, { "cell_type": "markdown", "id": "4c32749a", "metadata": {}, "source": [ "### **3.2 Dictionaries (Key-Value Pairs)**" ] }, { "cell_type": "code", "execution_count": 8, "id": "be9573f4", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Alice\n" ] } ], "source": [ "student = {'name': 'Alice', 'age': 22, 'grade': 'A'}\n", "\n", "print(student['name']) # Output: Alice" ] }, { "cell_type": "markdown", "id": "68086a57", "metadata": {}, "source": [ "👉 **Task**: Create a dictionary storing information about yourself and print it." ] }, { "cell_type": "markdown", "id": "e73c2fb3", "metadata": {}, "source": [ "## **4 File Handling & CSV Processing**\n", "\n", "Let's read a CSV file using Python!" ] }, { "cell_type": "code", "execution_count": 9, "id": "7999fee6", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['Time', 'Temperature (C)']\n", "['08:00', '22.5']\n", "['09:00', '24.1']\n", "['10:00', '25.3']\n", "['11:00', '26.7']\n", "['12:00', '27.8']\n" ] } ], "source": [ "import csv\n", "\n", "# Read a CSV file\n", "with open('data1.csv', 'r') as file:\n", " reader = csv.reader(file)\n", " for row in reader:\n", " print(row)" ] }, { "cell_type": "markdown", "id": "1c847f9b", "metadata": {}, "source": [ "Now, let's compute basic statistics:" ] }, { "cell_type": "code", "execution_count": 10, "id": "096da635", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " Math Science English\n", "Student \n", "Alice 85 89 75\n", "Bob 90 85 80\n", "Charlie 78 80 85\n", "David 92 95 90\n", "Eve 88 90 78\n" ] } ], "source": [ "import pandas as pd\n", "\n", "# Load CSV into a DataFrame, considering first row as header and first column as index\n", "df = pd.read_csv('data2.csv', header=0, index_col=0)\n", "\n", "# Display DataFrame head\n", "print(df.head())" ] }, { "cell_type": "code", "execution_count": 11, "id": "e93a2c1c", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Mean: Math 86.6\n", "Science 87.8\n", "English 81.6\n", "dtype: float64\n", "Max: Math 92\n", "Science 95\n", "English 90\n", "dtype: int64\n", "Min: Math 78\n", "Science 80\n", "English 75\n", "dtype: int64\n" ] } ], "source": [ "# Compute statistics\n", "print('Mean:', df.mean())\n", "print('Max:', df.max())\n", "print('Min:', df.min())" ] }, { "cell_type": "markdown", "id": "e35949a4", "metadata": {}, "source": [ "👉 **Task**: Load a CSV file and compute its mean, max, and min values." ] }, { "cell_type": "code", "execution_count": null, "id": "b5968fc4", "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "id": "b448b029", "metadata": {}, "source": [ "## **Final Task**\n", "1. Read a CSV file called `Surgical-deepnet.csv`\n", "2. Compute the mean, max, and min of each column.\n", "3. Print the results.\n", "\n", "💡 **Hint**: Use Pandas (`pd.read_csv()`) for easy CSV handling." ] }, { "cell_type": "markdown", "id": "b99dcbf0", "metadata": {}, "source": [] } ], "metadata": { "kernelspec": { "display_name": "trien_project", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.10.6" } }, "nbformat": 4, "nbformat_minor": 5 }