{ "cells": [ { "cell_type": "markdown", "id": "4fce71d6", "metadata": {}, "source": [ "# Python Basics - 01. Introduction & Variables\n", "\n", "Welcome to the beginner's guide to Python! In this notebook, we'll explore the foundational concepts of Python programming, including how to output data, define variables, and work with basic data types like integers, floating-point numbers, strings, and booleans." ] }, { "cell_type": "markdown", "id": "33de7062", "metadata": { "language": "markdown" }, "source": [ "## Download Notebook\n", "\n", "{download}`Download this notebook <01_introduction.ipynb>`\n" ] }, { "cell_type": "markdown", "id": "7ac743bd", "metadata": {}, "source": [ "## 1. Hello World\n", "\n", "Let's start with the classic 'Hello, World!' program. In Python, you can use the built-in `print()` function to display text or variable contents on the screen." ] }, { "cell_type": "code", "execution_count": null, "id": "1b00daa5", "metadata": {}, "outputs": [], "source": [ "print(\"Hello, World!\")\n", "print(\"Welcome to Python programming.\")" ] }, { "cell_type": "markdown", "id": "39313a66", "metadata": {}, "source": [ "## 2. Variables & Data Types\n", "\n", "Python is a **dynamically-typed** language, which means you do not need to explicitly declare a variable's type. The type is inferred when the value is assigned. Common basic data types include:\n", "- **int**: Whole numbers.\n", "- **float**: Decimal numbers.\n", "- **str**: A sequence of characters (text), enclosed in single or double quotes.\n", "- **bool**: Represents True or False values." ] }, { "cell_type": "code", "execution_count": null, "id": "24ded0cf", "metadata": {}, "outputs": [], "source": [ "x = 10 # Integer (int)\n", "y = 3.14 # Floating-point number (float)\n", "name = \"Alice\" # String (str)\n", "is_student = True # Boolean (bool)\n", "\n", "print(f\"Value of x: {x}, Type: {type(x)}\")\n", "print(f\"Value of y: {y}, Type: {type(y)}\")\n", "print(f\"Value of name: {name}, Type: {type(name)}\")\n", "print(f\"Is student? {is_student}, Type: {type(is_student)}\")" ] }, { "cell_type": "markdown", "id": "5e7a8b98", "metadata": {}, "source": [ "## 3. Basic Arithmetic Operations\n", "\n", "Python supports all standard mathematical operations out of the box. Notice the difference between standard division `/` and floor division `//`." ] }, { "cell_type": "code", "execution_count": null, "id": "0ea691e0", "metadata": {}, "outputs": [], "source": [ "a = 15\n", "b = 4\n", "\n", "print(f\"{a} + {b} = {a + b}\") # Addition\n", "print(f\"{a} - {b} = {a - b}\") # Subtraction\n", "print(f\"{a} * {b} = {a * b}\") # Multiplication\n", "print(f\"{a} / {b} = {a / b}\") # True Division (returns a float)\n", "print(f\"{a} // {b} = {a // b}\") # Floor Division (discards the fractional part)\n", "print(f\"{a} % {b} = {a % b}\") # Modulo (remainder of division)\n", "print(f\"{a} ** 2 = {a ** 2}\") # Exponentiation (power of)" ] }, { "cell_type": "markdown", "id": "267a14d6", "metadata": {}, "source": [ "## 4. String Manipulation\n", "\n", "Strings in Python are powerful and flexible. You can extract subsections via 'slicing', determine their length, or change their casing." ] }, { "cell_type": "code", "execution_count": null, "id": "12459c3d", "metadata": {}, "outputs": [], "source": [ "text = \"Python Programming\"\n", "print(f\"Original text: '{text}'\")\n", "print(f\"Length of the string: {len(text)}\")\n", "print(f\"Uppercase: {text.upper()}\")\n", "print(f\"Lowercase: {text.lower()}\")\n", "\n", "# String slicing: text[start:stop] -> extracts characters from 'start' up to, but not including, 'stop'\n", "print(f\"First 6 characters: {text[0:6]}\")" ] }, { "cell_type": "markdown", "id": "0c5b10af", "metadata": {}, "source": [ "## 5. Formatted Strings (f-strings)\n", "\n", "When reading data from files, you often need clean output formatting.\n", "Python f-strings make it easy to embed variables and control number formatting directly inside strings.\n", "\n", "Common patterns:\n", "- `f\"Name: {name}\"` for variable interpolation.\n", "- `f\"{value:.2f}\"` for fixed decimal places.\n", "- `f\"{num:>6}\"` for width and alignment." ] }, { "cell_type": "code", "execution_count": null, "id": "3452b07c", "metadata": {}, "outputs": [], "source": [ "# Example: formatting output from file-like records\n", "records = [\n", " {\"name\": \"Alice\", \"score\": 95.2345},\n", " {\"name\": \"Bob\", \"score\": 88.5},\n", " {\"name\": \"Cara\", \"score\": 100}\n", "]\n", "\n", "print(\"Simple interpolation:\")\n", "for item in records:\n", " print(f\"Name: {item['name']}, Score: {item['score']}\")\n", "\n", "print(\"\\nDecimal formatting (2 digits):\")\n", "for item in records:\n", " print(f\"Name: {item['name']}, Score: {item['score']:.2f}\")\n", "\n", "print(\"\\nAligned table output:\")\n", "print(f\"{'Name':<10} {'Score':>8}\")\n", "print(\"-\" * 19)\n", "for item in records:\n", " print(f\"{item['name']:<10} {item['score']:>8.2f}\")\n", "\n", "# Bonus: zero-padding numbers\n", "for idx in range(1, 4):\n", " print(f\"Record ID: {idx:03d}\")" ] }, { "cell_type": "markdown", "id": "599c783a", "metadata": {}, "source": [ "## 6. Type Conversion, Identity, and Mutability\n", "\n", "### Type Conversion\n", "Python allows explicit conversion between common types with constructors like `int()`, `float()`, and `str()`.\n", "\n", "### Identity vs Equality\n", "- `==` checks whether values are equal.\n", "- `is` checks whether two variables reference the same object in memory.\n", "\n", "### Mutable vs Immutable\n", "- Immutable: `int`, `float`, `str`, `tuple`.\n", "- Mutable: `list`, `dict`, `set`.\n", "\n", "Understanding this difference helps you avoid bugs when passing objects into functions." ] }, { "cell_type": "code", "execution_count": null, "id": "bc798f41", "metadata": {}, "outputs": [], "source": [ "# Type conversion examples\n", "# raw_age is a string coming from user input or text files.\n", "raw_age = \"21\"\n", "# int() converts text digits into an integer value.\n", "age = int(raw_age)\n", "\n", "height_text = \"175.5\"\n", "# float() converts decimal text into a float number.\n", "height = float(height_text)\n", "\n", "# Numeric operations now work because types are converted.\n", "print(age + 1)\n", "print(height / 10)\n", "\n", "# str() converts number back to string for concatenation.\n", "print(str(age) + \" years old\")\n", "\n", "# Equality vs identity\n", "# == compares values.\n", "# is compares whether two variables point to the exact same object.\n", "a = [1, 2, 3]\n", "b = [1, 2, 3]\n", "c = a\n", "\n", "print(a == b) # True: same content\n", "print(a is b) # False: different list objects\n", "print(a is c) # True: same object reference\n", "\n", "# Mutability demo\n", "# Lists are mutable, so alias and items point to one shared object.\n", "items = [\"A\", \"B\"]\n", "alias = items\n", "alias.append(\"C\")\n", "print(items) # Also changed because alias modifies the same list" ] } ], "metadata": { "language_info": { "name": "python" } }, "nbformat": 4, "nbformat_minor": 5 }