{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Python 101" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# AUTHOR" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "# Assoc. Prof. Dr. Piyabute Fuangkhon\n", "# Department of Computer Science\n", "# Vicent Mary School of Engineering, Science and Technology\n", "# Assumption University\n", "# Update: 09/09/2025" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# HELLO WORLD" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello World\n" ] } ], "source": [ "# Comments in Python\n", "\n", "# The '#' symbol at the beginning of a line indicates a comment. Comments are ignored by the Python interpreter and are used to explain code.\n", "\n", "print('Hello World') # This statement prints the string 'Hello World' to the console." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# MODULE 1 - DATA TYPE" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## DATA TYPE" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [], "source": [ "# Python Data Types Overview\n", "\n", "# Python supports several built-in data types. The major ones include:\n", "# 1. Number: `int`, `float`, `complex`\n", "# 2. String: `str`\n", "# 3. List: `list` (denoted by `[ ]` - **Mutable**)\n", "# 4. Tuple: `tuple` (denoted by `( )` - **Immutable**)\n", "# 5. Dictionary: `dict` (denoted by `{ }` - stores key/value pairs)\n", "# 6. Set: `set` (stores unique, unordered items)\n", "\n", "# Key characteristics:\n", "# - **List**: General purpose, ordered, mutable sequence that can grow or shrink.\n", "# - **Tuple**: Ordered, immutable sequence, useful for fixed collections of data and generally faster than lists.\n", "# - **Dictionary**: Unordered collection of `key:value` pairs, providing fast lookups by key.\n", "# - **Set**: Unordered collection of unique items, optimized for membership testing and mathematical set operations like union and intersection." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## ARITHMETIC" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Variable a = 100\n", "Variable b = 9\n", "--------------------\n", "a + b = 109\n", "a - b = 91\n", "a × b = 900\n", "a ÷ b = 11.11111111111111\n", "a // b = 11\n", "a % b = 1\n", "a ^ b = 1000000000000000000\n" ] } ], "source": [ "# Basic Arithmetic Operations in Python\n", "\n", "a = 100\n", "b = 9\n", "\n", "print(f'Variable a = {a}')\n", "print(f'Variable b = {b}')\n", "print('--------------------')\n", "\n", "# Addition\n", "print(f'a + b = {a + b}')\n", "\n", "# Subtraction\n", "print(f'a - b = {a - b}')\n", "\n", "# Multiplication\n", "print(f'a × b = {a * b}')\n", "\n", "# Division (floating-point result)\n", "print(f'a ÷ b = {a / b}')\n", "\n", "# Integer Division (floor division)\n", "print(f'a // b = {a // b}')\n", "\n", "# Modulus (remainder)\n", "print(f'a % b = {a % b}')\n", "\n", "# Exponentiation\n", "print(f'a ^ b = {a ** b}')" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Value of a = 1\n", "Value of b = 2\n", "--------------------\n", "a + b = 3\n", "a - b = -1\n" ] } ], "source": [ "# Assigning to Multiple Variables\n", "\n", "a, b = 1, 2\n", "c = a + b\n", "d = a - b\n", "\n", "print(f'Value of a = {a}')\n", "print(f'Value of b = {b}')\n", "print('--------------------')\n", "\n", "print(f'a + b = {c}')\n", "print(f'a - b = {d}')" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Default formatting:\n", "a -> b -> c: 3.4567 + 4 = 7.4567\n", "\n", "Formatting with two decimal points:\n", "a -> b -> c: 3.46 + 4.00 = 7.46\n", "\n", "Formatting with three decimal points and specified order:\n", "b -> a -> c: 4.000 + 3.457 = 7.457\n" ] } ], "source": [ "# Printing Floating-Point Numbers\n", "\n", "a = 3.4567\n", "b = 4\n", "c = a + b\n", "\n", "print('Default formatting:')\n", "print(f'a -> b -> c: {a} + {b} = {c}')\n", "\n", "print('\\nFormatting with two decimal points:')\n", "print(f'a -> b -> c: {a:.2f} + {b:.2f} = {c:.2f}')\n", "\n", "print('\\nFormatting with three decimal points and specified order:')\n", "print('b -> a -> c: {1:.3f} + {0:.3f} = {2:.3f}'.format(a, b, c))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## DATA TYPE - STRING" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Concatenation without a separator:\n", "DigitalBusiness\n", "Using f-string: DigitalBusiness\n", "Using sep parameter:DigitalBusiness\n", "\n", "Concatenation with a space separator:\n", "Digital Business\n", "Using f-string: Digital Business\n", "Using print default: Digital Business\n", "Using sep parameter: Digital Business\n" ] } ], "source": [ "# String Concatenation and Printing\n", "\n", "a = 'Digital'\n", "b = 'Business'\n", "\n", "print('Concatenation without a separator:')\n", "print(a + b)\n", "print(f'Using f-string: {a}{b}')\n", "print('Using sep parameter:', a, b, sep='')\n", "\n", "print('\\nConcatenation with a space separator:')\n", "print(a + ' ' + b)\n", "print(f'Using f-string: {a} {b}')\n", "print('Using print default:', a, b)\n", "print('Using sep parameter:', a, b, sep=' ')" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "My name is Piyabute Fuangkhon.\n", "My name is Piyabute Fuangkhon.\n", "My name is Fuangkhon Piyabute.\n", "My name is Piyabute Fuangkhon.\n", "My name is Piyabute Fuangkhon .\n", "My name isPiyabuteFuangkhon.\n" ] } ], "source": [ "# Printing a String Variable with Additional Text\n", "\n", "fname = 'Piyabute'\n", "lname = 'Fuangkhon'\n", "\n", "# Using f-strings (recommended for modern Python)\n", "print(f'My name is {fname} {lname}.')\n", "\n", "# Using the `format()` method\n", "print('My name is {} {}.'.format(fname, lname))\n", "\n", "# Using positional arguments with `format()`\n", "print('My name is {1} {0}.'.format(fname, lname))\n", "\n", "# Simple concatenation (less readable for complex strings)\n", "print('My name is ' + fname + ' ' + lname + '.')\n", "\n", "# Using multiple arguments to `print` (adds a space by default)\n", "print('My name is', fname, lname, '.')\n", "print('My name is', fname, lname, '.', sep='') # `sep` removes the default space" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Original strings and concatenation:\n", "a = ' Digital '\n", "b = 'Business'\n", "a + b = ' Digital Business'\n", "\n", "Removing whitespaces:\n", "a.strip() + b = 'DigitalBusiness'\n", "a.lstrip() + b = 'Digital Business'\n", "a.rstrip() + b = ' DigitalBusiness'\n" ] } ], "source": [ "# Removing Whitespace from Strings\n", "\n", "a = ' Digital '\n", "b = 'Business'\n", "\n", "print('Original strings and concatenation:')\n", "print(f\"a = '{a}'\")\n", "print(f\"b = '{b}'\")\n", "print(f\"a + b = '{a + b}'\")\n", "\n", "print('\\nRemoving whitespaces:')\n", "print(f\"a.strip() + b = '{a.strip() + b}'\") # Removes leading and trailing whitespace\n", "print(f\"a.lstrip() + b = '{a.lstrip() + b}'\") # Removes leading whitespace\n", "print(f\"a.rstrip() + b = '{a.rstrip() + b}'\") # Removes trailing whitespace" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "The term 'fantasy' is found at index: 34\n" ] } ], "source": [ "# Finding the Location of a Substring\n", "\n", "message = 'Harry Potter is a series of seven fantasy novels written by British author, J. K. Rowling. The novels chronicle the lives of a young wizard, Harry Potter, and his friends Hermione Granger and Ron Weasley, all of whom are students at Hogwarts School of Witchcraft and Wizardry.'\n", "\n", "# The `find()` method returns the index of the first occurrence of the substring. If not found, it returns -1.\n", "location = message.find('fantasy')\n", "\n", "print(f\"The term 'fantasy' is found at index: {location}\")" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "The keyword 'novel' appears 2 times.\n" ] } ], "source": [ "# Counting Occurrences of a Substring\n", "\n", "message = 'Harry Potter is a series of seven fantasy novels written by British author, J. K. Rowling. The novels chronicle the lives of a young wizard, Harry Potter, and his friends Hermione Granger and Ron Weasley, all of whom are students at Hogwarts School of Witchcraft and Wizardry.'\n", "\n", "# The `count()` method returns the number of non-overlapping occurrences of the substring.\n", "count = message.count('novel')\n", "\n", "print(f\"The keyword 'novel' appears {count} times.\")" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Original message:\n", "Harry Potter is a series of seven fantasy novels written by British author, J. K. Rowling. The novels chronicle the lives of a young wizard, Harry Potter, and his friends Hermione Granger and Ron Weasley, all of whom are students at Hogwarts School of Witchcraft and Wizardry.\n", "\n", "Uppercase message:\n", "HARRY POTTER IS A SERIES OF SEVEN FANTASY NOVELS WRITTEN BY BRITISH AUTHOR, J. K. ROWLING. THE NOVELS CHRONICLE THE LIVES OF A YOUNG WIZARD, HARRY POTTER, AND HIS FRIENDS HERMIONE GRANGER AND RON WEASLEY, ALL OF WHOM ARE STUDENTS AT HOGWARTS SCHOOL OF WITCHCRAFT AND WIZARDRY.\n" ] } ], "source": [ "# Converting a String to Uppercase\n", "\n", "message = 'Harry Potter is a series of seven fantasy novels written by British author, J. K. Rowling. The novels chronicle the lives of a young wizard, Harry Potter, and his friends Hermione Granger and Ron Weasley, all of whom are students at Hogwarts School of Witchcraft and Wizardry.'\n", "\n", "# The `upper()` method returns a new string with all characters converted to uppercase.\n", "message_upper = message.upper()\n", "\n", "print('Original message:')\n", "print(message)\n", "\n", "print('\\nUppercase message:')\n", "print(message_upper)" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Original message:\n", "Harry Potter is a series of seven fantasy novels written by British author, J. K. Rowling. The novels chronicle the lives of a young wizard, Harry Potter, and his friends Hermione Granger and Ron Weasley, all of whom are students at Hogwarts School of Witchcraft and Wizardry.\n", "\n", "Lowercase message:\n", "harry potter is a series of seven fantasy novels written by british author, j. k. rowling. the novels chronicle the lives of a young wizard, harry potter, and his friends hermione granger and ron weasley, all of whom are students at hogwarts school of witchcraft and wizardry.\n" ] } ], "source": [ "# Converting a String to Lowercase\n", "\n", "message = 'Harry Potter is a series of seven fantasy novels written by British author, J. K. Rowling. The novels chronicle the lives of a young wizard, Harry Potter, and his friends Hermione Granger and Ron Weasley, all of whom are students at Hogwarts School of Witchcraft and Wizardry.'\n", "\n", "# The `lower()` method returns a new string with all characters converted to lowercase.\n", "message_lower = message.lower()\n", "\n", "print('Original message:')\n", "print(message)\n", "\n", "print('\\nLowercase message:')\n", "print(message_lower)" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Original message:\n", "piyabutefng@au.edu\n", "\n", "Modified message:\n", "piyabutefng at au.edu\n" ] } ], "source": [ "# Replacing a Substring in a String\n", "\n", "message = 'piyabutefng@au.edu'\n", "\n", "# The `replace()` method returns a copy of the string with all occurrences of substring `old` replaced by `new`.\n", "message_new = message.replace('@', ' at ')\n", "\n", "print('Original message:')\n", "print(message)\n", "\n", "print('\\nModified message:')\n", "print(message_new)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## DATA TYPE - LIST [Square Bracket]" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [], "source": [ "# List documentation\n", "# Reference: https://www.w3schools.com/python/python_lists.asp" ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "The entire list a = [101, 102, 103, 104, 105]\n", "The first element (index 0) is: 101\n", "The second element (index 1) is: 102\n", "The type of variable a is: \n" ] } ], "source": [ "# Creating and Accessing a List\n", "\n", "a = [101, 102, 103, 104, 105]\n", "\n", "print(f'The entire list a = {a}')\n", "\n", "# Lists are zero-indexed. The first element is at index 0.\n", "print(f'The first element (index 0) is: {a[0]}')\n", "print(f'The second element (index 1) is: {a[1]}')\n", "\n", "# The `type()` function returns the data type of the variable.\n", "print(f'The type of variable a is: {type(a)}')\n" ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "The list a with mixed data types: [101, 'Hello', True]\n", "The type of variable a is: \n" ] } ], "source": [ "# Lists can contain elements of different data types\n", "\n", "a = [101, 'Hello', True]\n", "\n", "print(f'The list a with mixed data types: {a}')\n", "print(f'The type of variable a is: {type(a)}')\n" ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "List a = [101, 102, 103, 104, 105]\n", "Index of 103 is: 2\n", "Error: 106 is not in list\n" ] } ], "source": [ "# Finding the Index of an Element in a List\n", "\n", "a = [101, 102, 103, 104, 105]\n", "print(f'List a = {a}')\n", "\n", "# The `index()` method returns the first index of the specified value. It raises a ValueError if the value is not present.\n", "try:\n", " print(f'Index of 103 is: {a.index(103)}')\n", " print(f'Index of 106 is: {a.index(106)}') # This line will raise an error\n", "except ValueError as e:\n", " print(f'Error: {e}')" ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "List a = [101, 102, 103, 104, 105]\n", "Is 103 in a? -> True\n", "Is 106 in a? -> False\n" ] } ], "source": [ "# Checking for Membership in a List\n", "\n", "a = [101, 102, 103, 104, 105]\n", "print(f'List a = {a}')\n", "\n", "# The `in` operator returns `True` if the specified value is present in the list, otherwise `False`.\n", "print(f'Is 103 in a? -> {103 in a}')\n", "print(f'Is 106 in a? -> {106 in a}')" ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [ { "ename": "SyntaxError", "evalue": "unexpected character after line continuation character (439235313.py, line 6)", "output_type": "error", "traceback": [ "\u001b[0;36m Cell \u001b[0;32mIn[20], line 6\u001b[0;36m\u001b[0m\n\u001b[0;31m print(f'Index of element \\'D1\\' is: {a.index(\\'D1\\')}')\u001b[0m\n\u001b[0m ^\u001b[0m\n\u001b[0;31mSyntaxError\u001b[0m\u001b[0;31m:\u001b[0m unexpected character after line continuation character\n" ] } ], "source": [ "# Finding the Index of a String Element\n", "\n", "a = ['A1', 'B1', 'C1', 'D1', 'E1']\n", "print(f'List a = {a}')\n", "\n", "print(f'Index of element \\'D1\\' is: {a.index(\\'D1\\')}')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Modifying an Element in a List\n", "\n", "a = [101, 102, 103, 104, 105]\n", "print(f'Original list: {a}')\n", "\n", "# Assign a new value to an element at a specific index.\n", "a[1] = 999\n", "print(f'List after changing the second element (index 1) to 999: {a}')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Challenge: Replace the value of a specified number with 999\n", "\n", "def replace_value(lst, old_value, new_value):\n", " \"\"\"Replaces all occurrences of a value in a list with a new value.\"\"\"\n", " try:\n", " index_to_replace = lst.index(old_value)\n", " lst[index_to_replace] = new_value\n", " print(f'List after replacing the first occurrence of {old_value} with {new_value}: {lst}')\n", " except ValueError:\n", " print(f'{old_value} not found in the list.')\n", "\n", "my_list = [101, 102, 103, 104, 105]\n", "print(f'Original list: {my_list}')\n", "replace_value(my_list, 103, 999)\n", "replace_value(my_list, 106, 999)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Adding a New Element to a List\n", "\n", "a = [101, 102, 103, 104, 105]\n", "print(f'Original list: {a}')\n", "\n", "# The `append()` method adds an element to the end of the list.\n", "a.append(999)\n", "print(f'List after appending 999: {a}')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Inserting an Element at a Specific Position\n", "\n", "a = [101, 102, 103, 104, 105]\n", "print(f'Original List: {a}')\n", "\n", "# The `insert()` method adds an element at a specified index. `list.insert(index, element)`.\n", "a.insert(2, 888)\n", "print(f'Insert 888 at index 2: {a}')\n", "\n", "# Negative indices count from the end of the list. -1 is the last element, -2 is the second to last, etc.\n", "a.insert(-1, 999)\n", "print(f'Insert 999 at the second to last position (index -1): {a}')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Deleting Elements from a List\n", "\n", "a = [101, 102, 103, 104, 105, 106, 107, 108, 109, 110]\n", "print(f'Original list: {a}')\n", "\n", "# `remove()` removes the first occurrence of a specified value.\n", "a.remove(103)\n", "print(f'After removing 103: {a}')\n", "\n", "# `del` removes an item at a specified index.\n", "del a[1]\n", "print(f'After deleting element at index 1: {a}')\n", "\n", "# `pop()` removes and returns the element at a specified index. If no index is specified, it removes and returns the last item.\n", "popped_element = a.pop(1)\n", "print(f'After popping element at index 1: {a} (Popped value was: {popped_element})')\n", "\n", "popped_last = a.pop()\n", "print(f'After popping the last element: {a} (Popped value was: {popped_last})')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Challenge: Remove all elements of a specified value from a list\n", "\n", "my_list = [1, 2, 3, 2, 4, 2, 5]\n", "value_to_remove = 2\n", "\n", "print(f'Original list: {my_list}')\n", "\n", "while value_to_remove in my_list:\n", " my_list.remove(value_to_remove)\n", "\n", "print(f'List after removing all occurrences of {value_to_remove}: {my_list}')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Clearing and Deleting a List\n", "\n", "a = [101, 102, 103, 104, 105]\n", "print(f'Original list: {a}')\n", "\n", "# The `clear()` method removes all items from the list, making it empty.\n", "a.clear()\n", "print(f'After clearing the list: {a}')\n", "\n", "# The `del` statement removes the variable reference itself.\n", "del a\n", "\n", "try:\n", " print(f'Attempting to access the deleted list: {a}')\n", "except NameError:\n", " print(\"\\nThe list 'a' has been deleted and no longer exists.\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Looping Through a List\n", "\n", "a = [101, 102, 103, 104, 105]\n", "print(f'List a: {a}')\n", "\n", "# The `enumerate()` function provides both the index and the value for each element during a loop.\n", "for i, x in enumerate(a):\n", " print(f'Element at index {i} is: {x}')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Sorting a List\n", "\n", "a = [101, 103, 102, 105, 104]\n", "\n", "print(f'Original list: {a}')\n", "\n", "# The `sort()` method sorts the list in ascending order in-place.\n", "a.sort()\n", "print(f'Sorted in ascending order: {a}')\n", "\n", "# The `reverse=True` parameter sorts the list in descending order.\n", "a.sort(reverse=True)\n", "print(f'Sorted in descending order: {a}')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Converting List Elements to Uppercase\n", "\n", "a = ['Pineapple', 'Banana', 'Orange', 'Pumpkin', 'Onion']\n", "print(f'Original list: {a}')\n", "\n", "# A list comprehension is a concise way to create a new list by applying an expression to each item in an iterable.\n", "uppercase_list = [item.upper() for item in a]\n", "print(f'Uppercase list: {uppercase_list}')\n", "\n", "# Alternatively, modifying the list in-place using a `for` loop.\n", "for i in range(len(a)):\n", " a[i] = a[i].upper()\n", "print(f'Modified list (in-place): {a}')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Converting List Elements to Lowercase\n", "\n", "a = ['Pineapple', 'Banana', 'Orange', 'Pumpkin', 'Onion']\n", "print(f'Original list: {a}')\n", "\n", "# Using a list comprehension for a new list is often more readable and efficient.\n", "lowercase_list = [item.lower() for item in a]\n", "print(f'Lowercase list: {lowercase_list}')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Sorting a List of Strings\n", "\n", "a = ['Pineapple', 'Banana', 'Orange', 'Pumpkin', 'onion']\n", "\n", "print(f'Original list: {a}')\n", "\n", "# Case-sensitive sort: 'onion' comes after all uppercase words because 'O' (ASCII 79) < 'P' (80) and 'o' (111) > 'P' (80).\n", "a.sort()\n", "print(f'Case-sensitive sort: {a}')\n", "\n", "a = ['Pineapple', 'Banana', 'Orange', 'Pumpkin', 'onion']\n", "\n", "# Case-insensitive sort: The `key=str.lower` parameter tells the sort method to compare items based on their lowercase version.\n", "a.sort(key=str.lower)\n", "print(f'Case-insensitive sort: {a}')\n", "\n", "# Case-insensitive descending sort: Use `reverse=True` in addition to the `key`.\n", "a.sort(key=str.lower, reverse=True)\n", "print(f'Case-insensitive descending sort: {a}')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Reversing a List (In-place)\n", "\n", "a = ['Pineapple', 'Banana', 'Orange', 'Pumpkin', 'onion']\n", "print(f'Original list: {a}')\n", "\n", "# The `reverse()` method reverses the order of the list in-place without sorting it.\n", "a.reverse()\n", "print(f'Reversed list: {a}')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Copying a List\n", "\n", "a = [1, 2, 3, 4, 5]\n", "print(f'Original list a: {a}')\n", "\n", "# `b = a` copies the reference, so `a` and `c` point to the same object in memory.\n", "c = a\n", "\n", "# `b = a.copy()` creates a shallow copy, so `a` and `b` are independent lists.\n", "b = a.copy()\n", "print(f'Shallow copy b: {b}')\n", "print(f'Reference copy c: {c}')\n", "\n", "a[0] = 999\n", "\n", "print('\\nAfter changing the first element of a to 999:')\n", "print(f'a: {a}')\n", "print(f'b: {b} (unchanged)')\n", "print(f'c: {c} (changed, as it's the same object as a)')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Joining and Repeating Lists\n", "\n", "a = [101, 102, 103]\n", "b = [201, 202, 203]\n", "print(f'a = {a}')\n", "print(f'b = {b}')\n", "\n", "# Concatenation: `+` creates a new list by joining two lists.\n", "c = a + b\n", "print(f'c = a + b: {c}')\n", "\n", "# `extend()`: Adds the elements of an iterable (e.g., another list) to the end of the current list.\n", "d = a.copy() # Create a copy to avoid modifying the original list `a`\n", "d.extend(b)\n", "print(f'd.extend(b): {d}')\n", "\n", "# `append()`: Adds the entire iterable as a single element.\n", "e = a.copy()\n", "e.append(b)\n", "print(f'e.append(b): {e}')\n", "\n", "# Multiplication: `*` repeats the list a specified number of times.\n", "f = a * 2\n", "print(f'f = a * 2: {f}')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# DATA TYPE - LIST [Square Bracket] - STRING" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Tokenizing a String into a List of Words\n", "\n", "sentence = 'You are the salt of the earth and the light of the world!'\n", "print(f'Original string: {sentence}')\n", "\n", "# The `split()` method splits a string into a list of substrings based on a delimiter.\n", "# By default, it splits on any whitespace.\n", "words = sentence.split()\n", "print(f'List of words: {words}')\n", "print(f\"'earth' is in the list? -> {'earth' in words}\")\n", "\n", "print(f'Type of original string: {type(sentence)}')\n", "print(f'Type of word list: {type(words)}')\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Tokenizing a String with a Specific Delimiter\n", "\n", "csv_string = '430359,Piyabute,Fuangkhon,Full-time Lecturer,Digital Business Management,School of Management'\n", "print(f'Original string: {csv_string}')\n", "\n", "# Splitting the string by a comma ','\n", "data_list = csv_string.split(',')\n", "print(f\"List of elements after splitting by ',': {data_list}\")\n", "\n", "# Note: The delimiter matters. `split(' , ')` would not work here.\n", "# This demonstrates the importance of specifying the correct delimiter." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Splitting and Joining a String\n", "\n", "csv_string = '430359,Piyabute,Fuangkhon,Full-time Lecturer,Digital Business Management,School of Management'\n", "print(f'Original string: {csv_string}')\n", "\n", "# Split the string into a list using a comma as a delimiter.\n", "data_list = csv_string.split(',')\n", "print(f\"List from splitting by ',': {data_list}\")\n", "\n", "# Join the list elements back into a string using a pipe '|' as the new separator.\n", "pipe_string = '|'.join(data_list)\n", "print(f\"New string joined by '|': {pipe_string}\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Accessing Specific Elements of a List\n", "\n", "a = [9, 1, 8, 2, 7, 3, 6, 4, 5]\n", "print(f'List a: {a}')\n", "\n", "# Access the first element using index 0.\n", "print(f'First element: {a[0]}')\n", "\n", "# Access the last element using negative index -1.\n", "a = ['Physics', 'Chemistry', 91, 100]\n", "print(f'List a (mixed types): {a}')\n", "print(f'First element: {a[0]}')\n", "print(f'Last element: {a[-1]}')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Slicing a List to Get Consecutive Elements\n", "\n", "a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n", "print(f'Original list: {a}')\n", "\n", "# Slicing `[start:stop:step]` returns a new list.\n", "print(f'Elements from index 1 to the end: {a[1:]}')\n", "print(f'Elements from index 2 to the end: {a[2:]}')\n", "print(f'Elements from index 1 up to (but not including) index 3: {a[1:3]}')\n", "print(f'Elements from the beginning up to the second to last: {a[:-1]}')\n", "print(f'Elements from the beginning up to the third to last: {a[:-2]}')\n", "print(f'The last element: {a[-1:]}')\n", "print(f'The last two elements: {a[-2:]}')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# DATA TYPE - LIST [Square Bracket] - MATH" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Basic Mathematical Functions on a List\n", "\n", "a = [101, 102, 103, 104, 105, 105]\n", "print(f'List a: {a}')\n", "\n", "print(f'Sum of all elements: {sum(a)}')\n", "print(f'Minimum value: {min(a)}')\n", "print(f'Maximum value: {max(a)}')\n", "print(f'Number of elements: {len(a)}')\n", "print(f'Count of value 105: {a.count(105)}')\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# DATA TYPE - LIST [Square Bracket] - MATH numpy" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Statistical Calculations on a List using NumPy and SciPy\n", "\n", "# Import libraries\n", "import numpy\n", "from scipy import stats\n", "\n", "a = [101, 102, 103, 104, 105, 105, 105]\n", "print(f'List a: {a}')\n", "\n", "# Mean (average)\n", "print(f'Mean: {numpy.mean(a)}')\n", "\n", "# Median (middle value)\n", "print(f'Median: {numpy.median(a)}')\n", "\n", "# Mode (most frequent value)\n", "# `stats.mode()` returns a ModeResult object with the mode value and its count.\n", "mode_result = stats.mode(a)\n", "print(f'Mode result: {mode_result}')\n", "print(f'Mode value(s): {mode_result.mode[0]}')\n", "print(f'Mode count: {mode_result.count[0]}')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Summary of List Methods\n", "\n", "# `append()`: Adds an element to the end.\n", "# `clear()`: Removes all elements.\n", "# `copy()`: Returns a shallow copy.\n", "# `count()`: Returns the number of occurrences of a value.\n", "# `extend()`: Adds all elements of an iterable to the end.\n", "# `index()`: Returns the index of the first occurrence of a value.\n", "# `insert()`: Adds an element at a specific position.\n", "# `pop()`: Removes and returns the element at a specified position.\n", "# `remove()`: Removes the first item with a specified value.\n", "# `reverse()`: Reverses the order of the list in-place.\n", "# `sort()`: Sorts the list in-place." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# List Exercises\n", "# Visit: https://www.w3schools.com/python/exercise.asp?filename=exercise_lists1" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## DATA TYPE - TUPLE ( Parenthesis )" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Tuple Documentation\n", "# Reference: https://www.w3schools.com/python/python_tuples.asp\n", "\n", "# Tuples are immutable, meaning their elements cannot be changed after creation. To modify a tuple, you must convert it to a list, perform the changes, and then convert it back to a tuple." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Creating and Accessing a Tuple\n", "\n", "a = (101, 102, 103, 104, 105)\n", "\n", "print(f'The entire tuple a = {a}')\n", "print(f'The second element (index 1) is: {a[1]}')\n", "print(f'The type of variable a is: {type(a)}')\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Tuples can contain elements of different data types\n", "\n", "a = (101, 'Hello', True)\n", "print(f'Tuple a with mixed data types: {a}')\n", "print(f'The type of variable a is: {type(a)}')\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Finding the Index of a Specific Element in a Tuple\n", "\n", "a = (101, 102, 103, 104, 105)\n", "print(f'Tuple a: {a}')\n", "\n", "# The `index()` method works similarly to lists.\n", "print(f'Index of 103 is: {a.index(103)}')\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Finding the Index of a Specific String Element in a Tuple\n", "\n", "a = ('A1', 'B1', 'C1', 'D1', 'E1')\n", "print(f'Tuple a: {a}')\n", "\n", "print(f'Index of element \\'D1\\' is: {a.index(\\'D1\\')}')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Checking for Membership in a Tuple\n", "\n", "a = (101, 102, 103, 104, 105)\n", "print(f'Tuple a: {a}')\n", "\n", "print(f'Is 103 in a? -> {103 in a}')\n", "print(f'Is 106 in a? -> {106 in a}')\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Modifying a Tuple (Indirectly)\n", "\n", "a = (101, 102, 103, 104, 105)\n", "print(f'Original tuple: {a}')\n", "\n", "# To change an element, convert the tuple to a list.\n", "temp_list = list(a)\n", "print(f'Converted to list: {temp_list}')\n", "\n", "# Modify the list.\n", "temp_list[1] = 999\n", "print(f'Modified list: {temp_list}')\n", "\n", "# Convert the list back to a tuple and reassign.\n", "a = tuple(temp_list)\n", "print(f'Converted back to tuple: {a}')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Adding a New Element to a Tuple (Indirectly)\n", "\n", "a = (101, 102, 103, 104, 105)\n", "print(f'Original tuple: {a}')\n", "\n", "# Convert to list to add an element.\n", "temp_list = list(a)\n", "temp_list.append(999)\n", "print(f'List after appending: {temp_list}')\n", "\n", "# Convert back to tuple and reassign.\n", "a = tuple(temp_list)\n", "print(f'Tuple after adding an element: {a}')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Inserting an Element into a Tuple (Indirectly)\n", "\n", "a = (101, 102, 103, 104, 105)\n", "print(f'Original tuple: {a}')\n", "\n", "# Convert to list to insert an element.\n", "temp_list = list(a)\n", "\n", "temp_list.insert(2, 888)\n", "print(f'List after inserting 888 at index 2: {temp_list}')\n", "\n", "# Convert back to tuple.\n", "a = tuple(temp_list)\n", "print(f'Tuple after inserting an element: {a}')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Deleting a Specific Element from a Tuple (Indirectly)\n", "\n", "a = (101, 102, 103, 104, 105, 106, 107, 108, 109, 110)\n", "print(f'Original tuple: {a}')\n", "\n", "# Convert to a list to perform deletions.\n", "temp_list = list(a)\n", "temp_list.remove(103)\n", "print(f'List after removing 103: {temp_list}')\n", "\n", "# Use del and pop on the list.\n", "del temp_list[1]\n", "temp_list.pop(-1)\n", "print(f'List after more deletions: {temp_list}')\n", "\n", "# Convert back to a tuple.\n", "a = tuple(temp_list)\n", "print(f'Tuple after all deletions: {a}')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Clearing and Deleting a Tuple\n", "\n", "a = (101, 102, 103, 104, 105)\n", "print(f'Original tuple: {a}')\n", "\n", "# You cannot `clear()` a tuple because it's immutable. `del` is the only way to remove it entirely.\n", "del a\n", "\n", "try:\n", " print(f'Attempting to access the deleted tuple: {a}')\n", "except NameError:\n", " print(\"\\nThe tuple 'a' has been deleted and no longer exists.\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Unpacking a Tuple\n", "\n", "a = (101, 102, 103, 104, 105)\n", "print(f'Tuple a: {a}')\n", "\n", "# Unpacking assigns elements from the tuple to a corresponding number of variables.\n", "a1, a2, a3, a4, a5 = a\n", "\n", "print('Unpacked variables:')\n", "print(f'a1 = {a1}')\n", "print(f'a2 = {a2}')\n", "print(f'a3 = {a3}')\n", "print(f'a4 = {a4}')\n", "print(f'a5 = {a5}')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Looping Through a Tuple\n", "\n", "a = (101, 102, 103, 104, 105)\n", "print(f'Tuple a: {a}')\n", "\n", "# Use `enumerate()` to get both the index and the value.\n", "for i, x in enumerate(a):\n", " print(f'Element at index {i} is: {x}')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Sorting a Tuple (Indirectly)\n", "\n", "a = (101, 103, 102, 105, 104)\n", "print(f'Original tuple: {a}')\n", "\n", "# Convert to a list to sort.\n", "temp_list = list(a)\n", "temp_list.sort()\n", "print(f'Sorted list (ascending): {temp_list}')\n", "\n", "# Sort in descending order.\n", "temp_list.sort(reverse=True)\n", "print(f'Sorted list (descending): {temp_list}')\n", "\n", "# Convert back to a tuple.\n", "a = tuple(temp_list)\n", "print(f'New sorted tuple: {a}')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Sorting a Tuple of Strings (Indirectly)\n", "\n", "a = ('Pineapple', 'Banana', 'Orange', 'Pumpkin', 'onion')\n", "print(f'Original tuple: {a}')\n", "\n", "# Convert to a list to sort.\n", "temp_list = list(a)\n", "\n", "temp_list.sort() # Case-sensitive sort\n", "print(f'Case-sensitive sort: {temp_list}')\n", "\n", "temp_list = list(a) # Reset for the next sort\n", "temp_list.sort(key=str.lower) # Case-insensitive sort\n", "print(f'Case-insensitive sort: {temp_list}')\n", "\n", "temp_list.sort(key=str.lower, reverse=True) # Case-insensitive descending sort\n", "print(f'Case-insensitive descending sort: {temp_list}')\n", "\n", "a = tuple(temp_list)\n", "print(f'New sorted tuple: {a}')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Converting a Tuple to Uppercase (Indirectly)\n", "\n", "a = ('Pineapple', 'Banana', 'Orange', 'Pumpkin', 'onion')\n", "print(f'Original tuple: {a}')\n", "\n", "# Use a list comprehension to create a new list with uppercase strings, then convert to a tuple.\n", "new_list = [item.upper() for item in a]\n", "new_tuple = tuple(new_list)\n", "print(f'Uppercase tuple: {new_tuple}')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Converting a Tuple to Lowercase (Indirectly)\n", "\n", "a = ('Pineapple', 'Banana', 'Orange', 'Pumpkin', 'onion')\n", "print(f'Original tuple: {a}')\n", "\n", "# Use a generator expression with `tuple()` for efficiency.\n", "new_tuple = tuple(item.lower() for item in a)\n", "print(f'Lowercase tuple: {new_tuple}')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Reversing the Order of a Tuple (Indirectly)\n", "\n", "a = ('Pineapple', 'Banana', 'Orange', 'Pumpkin', 'onion')\n", "print(f'Original tuple: {a}')\n", "\n", "# The `reversed()` function returns an iterator that yields items in reverse order. It does not modify the original tuple.\n", "reversed_tuple = tuple(reversed(a))\n", "print(f'Reversed tuple: {reversed_tuple}')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Copying a Tuple\n", "\n", "a = (101, 102, 103, 104, 105)\n", "print(f'Original tuple a: {a}')\n", "\n", "# Because tuples are immutable, assigning one tuple to another creates a new reference to the same object.\n", "b = a\n", "print(f'Reference copy b: {b}')\n", "\n", "# To modify the content, a new tuple must be created.\n", "temp_list = list(a)\n", "temp_list[1] = 200\n", "a = tuple(temp_list)\n", "\n", "print('\\nAfter modifying tuple a:')\n", "print(f'a: {a}')\n", "print(f'b: {b} (unchanged as it refers to the original tuple object)')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Joining and Repeating Tuples\n", "\n", "a = (101, 102, 103)\n", "b = (201, 202, 203)\n", "print(f'a = {a}')\n", "print(f'b = {b}')\n", "\n", "# The `+` operator concatenates tuples to create a new tuple.\n", "c = a + b\n", "print(f'c = a + b: {c}')\n", "\n", "# The `*` operator repeats the tuple.\n", "d = c * 2\n", "print(f'd = c * 2: {d}')\n", "\n", "# Using augmented assignment `*= `.\n", "d *= 3\n", "print(f'd *= 3: {d}')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# DATA TYPE - TUPLE (Parenthesis) - MATH" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Basic Mathematical Functions on a Tuple\n", "\n", "a = (101, 102, 103, 104, 105, 105)\n", "print(f'Tuple a: {a}')\n", "\n", "# Built-in functions work on tuples just like on lists.\n", "print(f'Sum: {sum(a)}')\n", "print(f'Minimum value: {min(a)}')\n", "print(f'Maximum value: {max(a)}')\n", "print(f'Number of elements: {len(a)}')\n", "print(f'Count of 105: {a.count(105)}')\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Statistical Calculations on a Tuple\n", "\n", "# Import libraries\n", "import numpy\n", "from scipy import stats\n", "\n", "a = (101, 102, 103, 104, 105, 105, 105)\n", "print(f'Tuple a: {a}')\n", "\n", "# NumPy and SciPy functions work on tuples as well.\n", "print(f'Mean: {numpy.mean(a)}')\n", "print(f'Median: {numpy.median(a)}')\n", "\n", "mode_result = stats.mode(a)\n", "print(f'Mode value(s): {mode_result.mode}')\n", "print(f'Mode count: {mode_result.count}')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Summary of Tuple Methods\n", "\n", "# `count()`: Returns the number of times a specified value occurs.\n", "# `index()`: Returns the index of the first occurrence of a value." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Tuple Exercises\n", "# Visit: https://www.w3schools.com/python/python_tuples_exercises.asp" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## DATA TYPE - DICTIONARY { Braces }" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Dictionary Documentation\n", "# Reference: https://www.w3schools.com/python/python_dictionaries.asp\n", "\n", "# A dictionary stores data as `key:value` pairs. Keys must be unique and immutable (e.g., strings, numbers, or tuples). Values can be of any data type." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Creating and Accessing a Dictionary\n", "\n", "student_info = {'sid': 6010001, 'fname': 'Piyabute', 'lname': 'Fuangkhon', 'phone': '027232236', 'active': True}\n", "\n", "print(f'The entire dictionary: {student_info}')\n", "\n", "# Accessing values using their keys.\n", "print(f\"Student's first name: {student_info['fname']}\")\n", "print(f\"Student's phone number: {student_info.get('phone')}\") # Using `get()` is safer as it returns None if the key doesn't exist, preventing a KeyError.\n", "\n", "print(f'Type of the dictionary: {type(student_info)}')\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Creating a Dictionary from Lists\n", "\n", "keys = ['sid', 'fname', 'lname', 'phone', 'active']\n", "values1 = ['6010001', 'Piyabute', 'Fuangkhon', '027232236', True]\n", "values2 = ['6010002', 'Robert', 'John', '027232237', False]\n", "\n", "# The `zip()` function combines two lists, and `dict()` converts the resulting pairs into a dictionary.\n", "dict1 = dict(zip(keys, values1))\n", "dict2 = dict(zip(keys, values2))\n", "\n", "print(f'Dictionary 1: {dict1}')\n", "print(f'Dictionary 2: {dict2}')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Creating a Dictionary from a List of Tuples\n", "\n", "data_tuples = [\n", " ('sid', 6010001),\n", " ('fname', 'Piyabute'),\n", " ('lname', 'Fuangkhon'),\n", " ('phone', '027232236'),\n", " ('active', True)\n", "]\n", "\n", "print(f'List of tuples: {data_tuples}')\n", "\n", "# The `dict()` constructor can create a dictionary from an iterable of `(key, value)` pairs.\n", "my_dict = dict(data_tuples)\n", "print(f'Created dictionary: {my_dict}')\n", "print(f'Type of the new dictionary: {type(my_dict)}')\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Creating a Dictionary with `dict()` Constructor\n", "\n", "# Creating a dictionary directly with curly braces is the most common method.\n", "a = {'sid': 6010001, 'fname': 'Piyabute', 'lname': 'Fuangkhon', 'phone': '027232236', 'active': True}\n", "print(f'Dictionary a: {a}')\n", "\n", "# The `dict()` constructor can also be used to create a dictionary from another dictionary.\n", "b = dict(a)\n", "print(f'Dictionary b (copy of a): {b}')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Creating a Dictionary of Dictionaries (Nested Dictionary)\n", "\n", "students = {}\n", "\n", "students[0] = {'sid': 6010001, 'fname': 'Piyabute', 'lname': 'Fuangkhon', 'phone': '027232236', 'active': True}\n", "students[1] = {'sid': 6010002, 'fname': 'Robert', 'lname': 'Downey', 'phone': '023004543', 'active': True}\n", "students[2] = {'sid': 6010003, 'fname': 'Elon', 'lname': 'Musk', 'phone': '028888888', 'active': False}\n", "\n", "print('All student records:')\n", "print(students)\n", "\n", "print('\\nAccessing a specific record:')\n", "print(f\"Record for student at key 1: {students[1]}\")\n", "print(f\"First name of student at key 1: {students[1]['fname']}\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Listing all Keys in a Dictionary\n", "\n", "a = {'sid': 6010001, 'fname': 'Piyabute', 'lname': 'Fuangkhon', 'phone': '027232236', 'active': True}\n", "\n", "# The `keys()` method returns a view object of all the keys.\n", "print(f'Keys of the dictionary: {a.keys()}')\n", "\n", "# Looping through the keys is often done implicitly or with `.keys()`.\n", "print('\\nKeys in a loop:')\n", "for key in a:\n", " print(key)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Listing all Values in a Dictionary\n", "\n", "a = {'sid': 6010001, 'fname': 'Piyabute', 'lname': 'Fuangkhon', 'phone': '027232236', 'active': True}\n", "\n", "# The `values()` method returns a view object of all the values.\n", "print(f'Values of the dictionary: {a.values()}')\n", "\n", "# Looping through the values.\n", "print('\\nValues in a loop:')\n", "for value in a.values():\n", " print(value)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Listing all Items (Key-Value Pairs) in a Dictionary\n", "\n", "a = {'sid': 6010001, 'fname': 'Piyabute', 'lname': 'Fuangkhon', 'phone': '027232236', 'active': True}\n", "\n", "# The `items()` method returns a view object of all `(key, value)` pairs.\n", "print(f'Items of the dictionary: {a.items()}')\n", "\n", "print('\\nItems in a loop:')\n", "for key, value in a.items():\n", " print(f'{key}: {value}')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Checking for the Existence of a Key or Value\n", "\n", "a = {'sid': 6010001, 'fname': 'Piyabute', 'lname': 'Fuangkhon', 'phone': '027232236', 'active': True}\n", "\n", "search_key = 'fname'\n", "if search_key in a:\n", " print(f\"The key '{search_key}' exists in the dictionary.\")\n", "else:\n", " print(f\"The key '{search_key}' does not exist.\")\n", "\n", "search_value = 'Piyabute'\n", "if search_value in a.values():\n", " print(f\"\\nThe value '{search_value}' exists in the dictionary.\")\n", "else:\n", " print(f\"\\nThe value '{search_value}' does not exist.\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Finding the index of a specific string element\n", "# Dictionaries do not have an `index()` method like lists or tuples because they are unordered. Access is by key only." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Changing the Value of an Element in a Dictionary\n", "\n", "a = {'sid': 6010001, 'fname': 'Piyabute', 'lname': 'Fuangkhon', 'phone': '027232236', 'active': True}\n", "print(f'Original dictionary: {a}')\n", "\n", "# Change a value by assigning to a key.\n", "a['active'] = False\n", "print(f\"\\nAfter changing 'active' to False: {a}\")\n", "\n", "# The `update()` method can be used to update existing key-value pairs.\n", "a.update({'phone': '023004543'})\n", "print(f\"\\nAfter updating 'phone' to '023004543': {a}\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Adding and Updating Elements in a Dictionary\n", "\n", "a = {'sid': 6010001, 'fname': 'Piyabute', 'lname': 'Fuangkhon', 'phone': '027232236', 'active': True}\n", "print(f'Original dictionary: {a}')\n", "\n", "# Adding a new key-value pair.\n", "a['address'] = '88 Moo 8 Bangna-Trad K.M.26'\n", "print(f\"\\nAfter adding 'address': {a}\")\n", "\n", "# Using `update()` to add a new key-value pair.\n", "a.update({'district': 'Hua Mak'})\n", "print(f\"\\nAfter adding 'district': {a}\")\n", "\n", "# `update()` can also change an existing value.\n", "a.update({'district': 'Bang Sao Thong'})\n", "print(f\"\\nAfter updating 'district': {a}\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Deleting an Element from a Dictionary\n", "\n", "a = {'sid': 6010001, 'fname': 'Piyabute', 'lname': 'Fuangkhon', 'phone': '027232236', 'active': True}\n", "print(f'Original dictionary: {a}')\n", "\n", "# The `del` statement removes a key-value pair by key.\n", "del a['phone']\n", "print(f\"\\nAfter deleting 'phone': {a}\")\n", "\n", "# The `popitem()` method removes and returns the last inserted item (key-value pair).\n", "last_item = a.popitem()\n", "print(f\"\\nAfter popping the last item: {a}\")\n", "print(f'Popped item was: {last_item}')\n", "print(f'Type of the popped item: {type(last_item)}')\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Clearing and Deleting a Dictionary\n", "\n", "a = {'sid': 6010001, 'fname': 'Piyabute', 'lname': 'Fuangkhon', 'phone': '027232236', 'active': True}\n", "print(f'Original dictionary: {a}')\n", "\n", "# The `clear()` method empties the dictionary.\n", "a.clear()\n", "print(f\"\\nAfter clearing the dictionary: {a}\")\n", "\n", "# The `del` statement removes the dictionary variable itself.\n", "del a\n", "\n", "try:\n", " print(f'Attempting to access the deleted dictionary: {a}')\n", "except NameError:\n", " print(\"\\nThe dictionary 'a' has been deleted and no longer exists.\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Looping Through a Dictionary\n", "\n", "a = {'sid': 6010001, 'fname': 'Piyabute', 'lname': 'Fuangkhon', 'phone': '027232236', 'active': True}\n", "\n", "print('Looping through items:')\n", "for key, value in a.items():\n", " print(f'Key: {key}, Value: {value}')\n", "\n", "print('\\nLooping through keys:')\n", "for key in a.keys():\n", " print(f'Key: {key}, Value: {a[key]}')\n", "\n", "print('\\nLooping through values:')\n", "for value in a.values():\n", " print(f'Value: {value}')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Looping Through a List of Dictionaries\n", "\n", "students = [\n", " {'sid': 6010001, 'fname': 'Piyabute'},\n", " {'sid': 6010002, 'fname': 'Robert'},\n", " {'sid': 6010003, 'fname': 'Elon'}\n", "]\n", "\n", "print('Individual dictionary elements:')\n", "for i, student in enumerate(students):\n", " print(f'students[{i}] = {student}')\n", "\n", "search_key = 'fname'\n", "search_value = 'Robert'\n", "\n", "print(f\"\\nChecking for key '{search_key}':\")\n", "for i, student in enumerate(students):\n", " if search_key in student:\n", " print(f\"'{search_key}' is in students[{i}]: Yes\")\n", "\n", "print(f\"\\nChecking for value '{search_value}':\")\n", "for i, student in enumerate(students):\n", " if search_value in student.values():\n", " print(f\"'{search_value}' is in students[{i}]: Yes\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Sorting a Dictionary\n", "\n", "a = {6010003: 'Elon', 6010002: 'Robert', 6010001: 'Piyabute'}\n", "\n", "print(f'Original dictionary: {a}')\n", "\n", "# `sorted()` returns a list of `(key, value)` tuples. We use a `lambda` function to specify the sorting key.\n", "sorted_by_keys = sorted(a.items(), key=lambda item: item[0])\n", "print('\\nSorted by keys:')\n", "for item in sorted_by_keys:\n", " print(item)\n", "\n", "sorted_by_values = sorted(a.items(), key=lambda item: item[1])\n", "print('\\nSorted by values:')\n", "for item in sorted_by_values:\n", " print(item)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Sorting a Dictionary in Reverse Order\n", "\n", "a = {6010003: 'Elon', 6010002: 'Robert', 6010001: 'Piyabute'}\n", "\n", "# Sort by keys in reverse order.\n", "sorted_by_keys_rev = sorted(a.items(), key=lambda item: item[0], reverse=True)\n", "print('Sorted by keys (reverse):')\n", "for item in sorted_by_keys_rev:\n", " print(item)\n", "\n", "# Sort by values in reverse order.\n", "sorted_by_values_rev = sorted(a.items(), key=lambda item: item[1], reverse=True)\n", "print('\\nSorted by values (reverse):')\n", "for item in sorted_by_values_rev:\n", " print(item)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Sorting a List of Dictionaries\n", "\n", "list_of_dicts = [\n", " {'sid': 6010003, 'fname': 'Elon'},\n", " {'sid': 6010002, 'fname': 'Robert'},\n", " {'sid': 6010001, 'fname': 'Piyabute'}\n", "]\n", "\n", "print('Original list of dictionaries:')\n", "for d in list_of_dicts:\n", " print(d)\n", "\n", "# Sort the list based on the value of the 'sid' key in each dictionary.\n", "sorted_list = sorted(list_of_dicts, key=lambda item: item['sid'])\n", "\n", "print('\\nSorted list by key \\'sid\\':')\n", "for item in sorted_list:\n", " print(item)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Copying a Dictionary\n", "\n", "a = {'sid': 6010001, 'fname': 'Piyabute', 'active': True}\n", "print(f'Original dictionary a: {a}')\n", "\n", "# Using `copy()` creates a new dictionary object (shallow copy).\n", "b = a.copy()\n", "print(f'Copied dictionary b: {b}')\n", "\n", "# Modify the copied dictionary.\n", "b['active'] = False\n", "\n", "print('\\nAfter modifying b:')\n", "print(f'a: {a} (unchanged)')\n", "print(f'b: {b} (modified)')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Creating and Looping through a Nested Dictionary\n", "\n", "myfriend = {\n", " 6010001: {'name': 'Vasa', 'year': 2000},\n", " 6010002: {'name': 'Pisal', 'year': 2010},\n", " 6010003: {'name': 'Sumate', 'year': 2021}\n", "}\n", "\n", "print('Looping through outer keys:')\n", "for key in myfriend:\n", " print(f'Key: {key}')\n", "\n", "print('\\nLooping through outer values (inner dictionaries):')\n", "for value in myfriend.values():\n", " print(f'Value: {value}')\n", "\n", "print('\\nLooping through outer key-value pairs:')\n", "for key, value in myfriend.items():\n", " print(f'Key: {key}, Value: {value}')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Creating a Nested Dictionary from Separate Dictionaries\n", "\n", "friend1 = {'name': 'Vasa', 'year': 2000}\n", "friend2 = {'name': 'Pisal', 'year': 2010}\n", "friend3 = {'name': 'Sumate', 'year': 2021}\n", "\n", "myfriend = {6010001: friend1, 6010002: friend2, 6010003: friend3}\n", "\n", "print('Looping through keys and values of the nested dictionary:')\n", "for student_id, student_info in myfriend.items():\n", " print(f'Student ID: {student_id}, Info: {student_info}')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Summary of Dictionary Methods\n", "\n", "# `clear()`: Removes all elements.\n", "# `copy()`: Returns a shallow copy.\n", "# `fromkeys()`: Creates a new dictionary from an iterable of keys.\n", "# `get()`: Returns the value for a specified key (or `None`).\n", "# `items()`: Returns a view object of key-value pairs.\n", "# `keys()`: Returns a view object of all keys.\n", "# `pop()`: Removes and returns the value for a specified key.\n", "# `popitem()`: Removes and returns the last inserted key-value pair.\n", "# `setdefault()`: Returns the value of the key, and inserts the key with a specified value if it does not exist.\n", "# `update()`: Updates the dictionary with key-value pairs from another dictionary or an iterable of pairs.\n", "# `values()`: Returns a view object of all values." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Dictionary Exercises\n", "# Visit: https://www.w3schools.com/python/python_dictionaries_exercises.asp" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## DATA TYPE - SET" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Set Documentation\n", "# Reference: https://www.w3schools.com/python/python_sets.asp\n", "\n", "# A set is an unordered collection of unique elements. It is mutable, but its elements must be immutable.\n", "# Sets are defined with curly braces `{}` but unlike dictionaries, they do not have key-value pairs." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Creating a Set\n", "\n", "# Duplicate values are automatically removed upon creation.\n", "a = {'red', 'green', 'blue', 'blue'}\n", "print(f'Set a: {a}')\n", "\n", "# Looping through a set prints the unique elements in an arbitrary order.\n", "print('\\nElements in the set:')\n", "for x in a:\n", " print(x)\n", "\n", "print(f'Type of the variable a: {type(a)}')\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Checking for Membership in a Set\n", "\n", "a = {101, 102, 103, 104, 105}\n", "print(f'Set a: {a}')\n", "\n", "# Membership testing with `in` is highly efficient for sets.\n", "print(f'Is 103 in a? -> {103 in a}')\n", "print(f'Is 106 in a? -> {106 in a}')\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Adding a New Element to a Set\n", "\n", "a = {101, 102, 103, 104, 105}\n", "print(f'Original set: {a}')\n", "\n", "# The `add()` method adds a single element to the set.\n", "a.add(106)\n", "print(f'After adding 106: {a}')\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Updating a Set with Multiple Elements\n", "\n", "a = {101, 102, 103, 104, 105}\n", "print(f'Original set: {a}')\n", "\n", "# The `update()` method adds elements from an iterable (like another set, list, or tuple).\n", "a.update({106, 107})\n", "print(f'After updating with {106, 107}: {a}')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Updating a Set with Elements from Another Set\n", "\n", "a = {101, 102, 103, 104, 105}\n", "b = {888, 999}\n", "print(f'Set a: {a}')\n", "print(f'Set b: {b}')\n", "\n", "a.update(b)\n", "print(f'After updating a with elements from b: {a}')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Updating a Set from Different Iterables\n", "\n", "my_set = {101, 102}\n", "my_list = [103, 104]\n", "my_tuple = (105, 106)\n", "my_dict = {107: 'value', 108: 'another'}\n", "\n", "print(f'Original set: {my_set}')\n", "\n", "my_set.update(my_list)\n", "print(f'After updating with a list: {my_set}')\n", "\n", "my_set.update(my_tuple)\n", "print(f'After updating with a tuple: {my_set}')\n", "\n", "# When updating from a dictionary, the keys are used by default.\n", "my_set.update(my_dict)\n", "print(f'After updating with dictionary keys: {my_set}')\n", "\n", "# To update with values, you need to explicitly call `d.values()`.\n", "my_set.update(my_dict.values())\n", "print(f'After updating with dictionary values: {my_set}')\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Removing an Element from a Set\n", "\n", "a = {101, 102, 103, 104, 105}\n", "print(f'Original set: {a}')\n", "\n", "# The `remove()` method removes a specified element. It raises a KeyError if the element is not found.\n", "try:\n", " a.remove(103)\n", " print(f'After removing 103: {a}')\n", " a.remove(999)\n", "except KeyError as e:\n", " print(f'Error: {e}')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Clearing and Deleting a Set\n", "\n", "a = {101, 102, 103, 104, 105}\n", "print(f'Original set: {a}')\n", "\n", "# `clear()` empties the set.\n", "a.clear()\n", "print(f'After clearing: {a}')\n", "\n", "# `del` removes the set variable entirely.\n", "del a\n", "\n", "try:\n", " print(a)\n", "except NameError:\n", " print(\"\\nThe set 'a' no longer exists.\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### DATA TYPE - SET - MATHEMATICS" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Mathematical Functions on a Set\n", "\n", "a = {101, 103, 104, 102, 106, 105}\n", "print(f'Set a: {a}')\n", "\n", "print(f'Sum of all elements: {sum(a)}')\n", "print(f'Minimum value: {min(a)}')\n", "print(f'Maximum value: {max(a)}')\n", "print(f'Number of elements: {len(a)}')\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### DATA TYPE - SET - OPERATIONS" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Set Subset Test\n", "\n", "a = {101, 102, 103, 104, 105, 106}\n", "b = {101, 102, 103}\n", "\n", "print(f'Set a: {a}')\n", "print(f'Set b: {b}')\n", "\n", "# `issubset()` checks if all elements of one set are in another.\n", "print(f'Is b a subset of a? -> {b.issubset(a)}')\n", "print(f'Is a a subset of b? -> {a.issubset(b)}')\n", "\n", "# The `<=` operator is an alternative syntax for `issubset()`.\n", "print(f'Is b <= a? -> {b <= a}')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Set Superset Test\n", "\n", "a = {101, 102, 103, 104, 105, 106}\n", "b = {101, 102, 103}\n", "\n", "print(f'Set a: {a}')\n", "print(f'Set b: {b}')\n", "\n", "# `issuperset()` checks if a set contains all elements of another set.\n", "print(f'Is a a superset of b? -> {a.issuperset(b)}')\n", "print(f'Is b a superset of a? -> {b.issuperset(a)}')\n", "\n", "# The `>=` operator is an alternative syntax for `issuperset()`.\n", "print(f'Is a >= b? -> {a >= b}')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Set Union\n", "\n", "a = {101, 102, 103, 104, 105, 106}\n", "b = {777, 888, 999}\n", "print(f'Set a: {a}')\n", "print(f'Set b: {b}')\n", "\n", "# The `union()` method returns a new set with all elements from both sets.\n", "union_result = a.union(b)\n", "print(f'Union of a and b: {union_result}')\n", "\n", "# The `|` operator is an alternative syntax for `union()`.\n", "c = a | b\n", "print(f'a | b: {c}')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Set Intersection\n", "\n", "a = {101, 102, 103, 104, 105, 106}\n", "b = {101, 102, 103, 777, 888, 999}\n", "print(f'Set a: {a}')\n", "print(f'Set b: {b}')\n", "\n", "# The `intersection()` method returns a new set with elements common to both sets.\n", "intersection_result = a.intersection(b)\n", "print(f'Intersection of a and b: {intersection_result}')\n", "\n", "# The `&` operator is an alternative syntax for `intersection()`.\n", "c = a & b\n", "print(f'a & b: {c}')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Set Difference\n", "\n", "a = {101, 102, 103, 104, 105, 106}\n", "b = {101, 102, 103, 777, 888, 999}\n", "print(f'Set a: {a}')\n", "print(f'Set b: {b}')\n", "\n", "# The `difference()` method returns a new set with elements from the first set that are not in the second.\n", "difference_result = a.difference(b)\n", "print(f'Elements in a but not in b: {difference_result}')\n", "\n", "# The `-` operator is an alternative syntax for `difference()`.\n", "c = a - b\n", "print(f'a - b: {c}')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Set Symmetric Difference\n", "\n", "a = {101, 102, 103, 104, 105, 106}\n", "b = {101, 102, 103, 777, 888, 999}\n", "print(f'Set a: {a}')\n", "print(f'Set b: {b}')\n", "\n", "# The `symmetric_difference()` method returns a new set with elements that are in either set, but not in both.\n", "sym_diff_result = a.symmetric_difference(b)\n", "print(f'Symmetric difference of a and b: {sym_diff_result}')\n", "\n", "# The `^` operator is an alternative syntax for `symmetric_difference()`.\n", "c = a ^ b\n", "print(f'a ^ b: {c}')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# In-place Set Operations\n", "\n", "a = {101, 102, 103, 104, 105, 106}\n", "b = {101, 102, 103, 777, 888, 999}\n", "u = {102, 103, 105}\n", "\n", "print(f'Initial set a: {a}')\n", "\n", "# `difference_update()` removes elements from `a` that are also in `b`.\n", "a.difference_update(b)\n", "print(f'After a.difference_update(b): {a}')\n", "\n", "# `intersection_update()` keeps only the elements that are in both `a` and `u`.\n", "a.intersection_update(u)\n", "print(f'After a.intersection_update(u): {a}')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Practical Example of Set Operations\n", "\n", "engineers = {'John', 'Jane', 'Jack', 'Janice'}\n", "managers = {'Jane', 'Jack', 'Susan', 'Zack'}\n", "programmers = {'Jack', 'Sam', 'Susan', 'Janice'}\n", "\n", "print(f'Engineers: {engineers}')\n", "print(f'Managers: {managers}')\n", "print(f'Programmers: {programmers}')\n", "\n", "# Union (`|`) finds all unique employees across all roles.\n", "all_employees = engineers | managers | programmers\n", "print(f'\\nAll employees: {all_employees}')\n", "\n", "# Intersection (`&`) finds employees who are both engineers and managers.\n", "eng_and_mgr = engineers & managers\n", "print(f'Engineers who are also managers: {eng_and_mgr}')\n", "\n", "# Difference (`-`) finds engineers who are NOT managers.\n", "eng_but_not_mgr = engineers - managers\n", "print(f'Engineers who are not managers: {eng_but_not_mgr}')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Sorting a Set\n", "# Sets are inherently unordered. To sort a set, you must convert it to a list first.\n", "\n", "a = {101, 103, 102, 105, 104}\n", "print(f'Original set (unordered): {a}')\n", "\n", "# Use the built-in `sorted()` function, which returns a new sorted list.\n", "sorted_list = sorted(a)\n", "print(f'Sorted list from the set: {sorted_list}')\n", "\n", "# If you need a sorted tuple, use `tuple(sorted(a))`." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Summary of Set Methods\n", "\n", "# `add()`: Adds an element.\n", "# `clear()`: Removes all elements.\n", "# `copy()`: Returns a shallow copy.\n", "# `difference()`: Returns a new set with elements only in the first set.\n", "# `difference_update()`: Removes elements from this set that are also in others.\n", "# `discard()`: Removes an element if it is present.\n", "# `intersection()`: Returns a new set with elements common to all sets.\n", "# `intersection_update()`: Keeps only the common elements.\n", "# `isdisjoint()`: Returns `True` if two sets have no elements in common.\n", "# `issubset()`: Returns `True` if another set contains this set.\n", "# `issuperset()`: Returns `True` if this set contains another set.\n", "# `pop()`: Removes and returns an arbitrary element.\n", "# `remove()`: Removes a specified element (raises an error if not found).\n", "# `symmetric_difference()`: Returns a new set with elements in either set, but not both.\n", "# `symmetric_difference_update()`: Updates the set with the symmetric difference.\n", "# `union()`: Returns a new set containing all elements from all sets.\n", "# `update()`: Adds elements from other iterables." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Set Exercises\n", "# Visit: https://www.w3schools.com/python/python_sets_exercises.asp" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## DATA TYPE - CONVERSION" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Converting a List to a Set\n", "\n", "a = [1, 2, 3, 4, 5, 6, 6] # Note the duplicate 6\n", "print(f'Original list: {a}')\n", "print(f'Type of a: {type(a)}')\n", "\n", "# Converting to a set automatically removes duplicates.\n", "s = set(a)\n", "print(f'Converted to set: {s}')\n", "print(f'Type of s: {type(s)}')\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Converting a Tuple to a Set\n", "\n", "a = (1, 2, 3, 4, 5, 6)\n", "print(f'Original tuple: {a}')\n", "print(f'Type of a: {type(a)}')\n", "\n", "s = set(a)\n", "print(f'Converted to set: {s}')\n", "print(f'Type of s: {type(s)}')\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Converting a Dictionary to a Set\n", "\n", "a = {1: 'A', 2: 'B', 3: 'C'}\n", "print(f'Original dictionary: {a}')\n", "print(f'Type of a: {type(a)}')\n", "\n", "# Converting a dictionary directly to a set results in a set of its keys.\n", "s_keys = set(a)\n", "print(f'Converted to a set of keys: {s_keys}')\n", "print(f'Type of s_keys: {type(s_keys)}')\n", "\n", "# To get a set of values, you must explicitly use the `.values()` method.\n", "s_values = set(a.values())\n", "print(f'Converted to a set of values: {s_values}')\n", "print(f'Type of s_values: {type(s_values)}')\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Converting a String to an Integer\n", "\n", "a = '10'\n", "print(f'Original string: {a}')\n", "print(f'Type of a: {type(a)}')\n", "\n", "b = int(a)\n", "print(f'Converted to integer: {b}')\n", "print(f'Type of b: {type(b)}')\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Converting a String to a Float\n", "\n", "a = '10.1'\n", "print(f'Original string: {a}')\n", "print(f'Type of a: {type(a)}')\n", "\n", "b = float(a)\n", "print(f'Converted to float: {b}')\n", "print(f'Type of b: {type(b)}')\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Conditional Conversion from String to Number\n", "\n", "a = '10.1'\n", "print(f'Original string: {a}')\n", "\n", "# A simple check for a decimal point can determine the appropriate conversion.\n", "if '.' in a:\n", " b = float(a)\n", " print(f'Converted to float: {b}')\n", " print(f'Type of b: {type(b)}')\n", "else:\n", " c = int(a)\n", " print(f'Converted to integer: {c}')\n", " print(f'Type of c: {type(c)}')\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Converting an Integer to a String\n", "\n", "a = 10\n", "print(f'Original integer: {a}')\n", "print(f'Type of a: {type(a)}')\n", "\n", "b = str(a)\n", "print(f'Converted to string: {b}')\n", "print(f'Type of b: {type(b)}')\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Converting a Float to a String\n", "\n", "a = 10.1\n", "print(f'Original float: {a}')\n", "print(f'Type of a: {type(a)}')\n", "\n", "b = str(a)\n", "print(f'Converted to string: {b}')\n", "print(f'Type of b: {type(b)}')\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Listing all Supported Methods for a Class\n", "\n", "# The `dir()` function returns a list of valid attributes for an object, including methods and properties.\n", "\n", "# 1. Integer\n", "print('--- Methods for Integer ---')\n", "my_int = 10\n", "print(f'Value: {my_int}, Type: {type(my_int)}')\n", "print(dir(my_int))\n", "\n", "# 2. Float\n", "print('\\n--- Methods for Float ---')\n", "my_float = 10.1\n", "print(f'Value: {my_float}, Type: {type(my_float)}')\n", "print(dir(my_float))\n", "\n", "# 3. String\n", "print('\\n--- Methods for String ---')\n", "my_string = '10.1'\n", "print(f'Value: {my_string}, Type: {type(my_string)}')\n", "print(dir(my_string))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# MODULE 2 - OPERATORS" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## OPERATORS - ARITHMETIC OPERATORS" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Operators Documentation\n", "# Reference: https://www.w3schools.com/python/python_operators.asp" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Arithmetic Operators\n", "\n", "a = 15\n", "b = 2\n", "\n", "print(f'a = {a}, b = {b}')\n", "\n", "print(f'Addition (a + b): {a + b}')\n", "print(f'Subtraction (a - b): {a - b}')\n", "print(f'Multiplication (a * b): {a * b}')\n", "print(f'Division (a / b): {a / b}')\n", "print(f'Floor Division (a // b): {a // b}')\n", "print(f'Modulus (a % b): {a % b}')\n", "print(f'Exponentiation (a ** b): {a ** b}')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## OPERATORS - COMPOUND ARITHMETIC OPERATORS" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Addition Assignment Operator (`+=`)\n", "\n", "a = 15\n", "b = 5\n", "\n", "print(f'Initial a = {a}, b = {b}')\n", "\n", "a += b # Equivalent to: a = a + b\n", "print(f'After a += b, a = {a}')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Subtraction Assignment Operator (`-=`)\n", "\n", "a = 15\n", "b = 5\n", "\n", "print(f'Initial a = {a}, b = {b}')\n", "\n", "a -= b # Equivalent to: a = a - b\n", "print(f'After a -= b, a = {a}')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Multiplication Assignment Operator (`*=`)\n", "\n", "a = 15\n", "b = 5\n", "\n", "print(f'Initial a = {a}, b = {b}')\n", "\n", "a *= b # Equivalent to: a = a * b\n", "print(f'After a *= b, a = {a}')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Division Assignment Operator (`/=`)\n", "\n", "a = 15\n", "b = 5\n", "\n", "print(f'Initial a = {a}, b = {b}')\n", "\n", "a /= b # Equivalent to: a = a / b\n", "print(f'After a /= b, a = {a}')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## OPERATORS - LOGICAL OPERATORS" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Comparison Operator: Less Than (`<`)\n", "\n", "a = 5\n", "b = 5\n", "\n", "print(f'a = {a}, b = {b}')\n", "result = a < b\n", "print(f'Is a strictly less than b? -> {result}')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Comparison Operator: Less Than or Equal To (`<=`)\n", "\n", "a = 5\n", "b = 5\n", "\n", "print(f'a = {a}, b = {b}')\n", "result = a <= b\n", "print(f'Is a less than or equal to b? -> {result}')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Comparison Operator: Greater Than (`>`)\n", "\n", "a = 5\n", "b = 5\n", "\n", "print(f'a = {a}, b = {b}')\n", "result = a > b\n", "print(f'Is a strictly greater than b? -> {result}')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Comparison Operator: Greater Than or Equal To (`>=`)\n", "\n", "a = 5\n", "b = 5\n", "\n", "print(f'a = {a}, b = {b}')\n", "result = a >= b\n", "print(f'Is a greater than or equal to b? -> {result}')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Comparison Operator: Equal To (`==`)\n", "\n", "a = 5\n", "b = 5\n", "\n", "print(f'a = {a}, b = {b}')\n", "result = a == b\n", "print(f'Is a equal to b? -> {result}')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Comparison Operator: Not Equal To (`!=`)\n", "\n", "a = 5\n", "b = 5\n", "\n", "print(f'a = {a}, b = {b}')\n", "result = a != b\n", "print(f'Is a not equal to b? -> {result}')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Logical Operator: AND\n", "\n", "a = True\n", "b = False\n", "\n", "print(f'a = {a}, b = {b}')\n", "\n", "# `and` returns `True` only if both operands are `True`.\n", "print(f'a and b -> {a and b}')\n", "\n", "# The `&` operator is a bitwise AND, but can be used with booleans. `and` is generally preferred for clarity in logical expressions.\n", "print(f'a & b -> {a & b}')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Logical Operator: OR\n", "\n", "a = True\n", "b = False\n", "\n", "print(f'a = {a}, b = {b}')\n", "\n", "# `or` returns `True` if at least one of the operands is `True`.\n", "print(f'a or b -> {a or b}')\n", "\n", "# The `|` operator is a bitwise OR, but can be used with booleans. `or` is generally preferred for clarity in logical expressions.\n", "print(f'a | b -> {a | b}')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Logical Operator: NOT\n", "\n", "a = True\n", "\n", "print(f'a = {a}')\n", "\n", "# `not` inverts the boolean value.\n", "result = not a\n", "print(f'not a -> {result}')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## OPERATORS - MEMBERSHIP" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Membership Operator `in` with a List\n", "\n", "a = [101, 102]\n", "b = 101\n", "\n", "print(f'List a: {a}, Element b: {b}')\n", "\n", "result = b in a\n", "print(f'Is {b} in {a}? -> {result}')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Membership Operator `in` with a Tuple\n", "\n", "a = (101, 102)\n", "b = 101\n", "\n", "print(f'Tuple a: {a}, Element b: {b}')\n", "\n", "result = b in a\n", "print(f'Is {b} in {a}? -> {result}')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Membership Operator `in` with a Set\n", "\n", "a = {101, 102}\n", "b = 101\n", "\n", "print(f'Set a: {a}, Element b: {b}')\n", "\n", "result = b in a\n", "print(f'Is {b} in {a}? -> {result}')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Membership Operator `not in` with a List\n", "\n", "a = [101, 102]\n", "b = 101\n", "\n", "print(f'List a: {a}, Element b: {b}')\n", "\n", "result = b not in a\n", "print(f'Is {b} not in {a}? -> {result}')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Membership Operator `not in` with a Tuple\n", "\n", "a = (101, 102)\n", "b = 101\n", "\n", "print(f'Tuple a: {a}, Element b: {b}')\n", "\n", "result = b not in a\n", "print(f'Is {b} not in {a}? -> {result}')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Membership Operator `not in` with a Set\n", "\n", "a = {101, 102}\n", "b = 101\n", "\n", "print(f'Set a: {a}, Element b: {b}')\n", "\n", "result = b not in a\n", "print(f'Is {b} not in {a}? -> {result}')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## OPERATORS - IDENTITY" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Identity Operator `is` with Numbers\n", "\n", "a = 1\n", "b = 1\n", "c = 2\n", "\n", "print(f'a = {a}, b = {b}, c = {c}')\n", "\n", "# `is` checks if two variables refer to the exact same object in memory.\n", "print(f'b is a -> {b is a}') # For small integers, Python often caches them, so `is` returns True.\n", "print(f'c is a -> {c is a}')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Identity Operator `is not` with Numbers\n", "\n", "a = 1\n", "b = 1\n", "c = 2\n", "\n", "print(f'a = {a}, b = {b}, c = {c}')\n", "\n", "print(f'b is not a -> {b is not a}')\n", "print(f'c is not a -> {c is not a}')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Identity Operator `is` with Strings\n", "\n", "a = \"hello\"\n", "b = \"hello\"\n", "c = \"Hello\"\n", "\n", "print(f'a = \"{a}\", b = \"{b}\", c = \"{c}\"')\n", "\n", "# Python's string interning can cause identical string literals to refer to the same object.\n", "print(f'b is a -> {b is a}')\n", "print(f'c is a -> {c is a}') # `c` is not the same object because of the capital 'H'." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## OPERATORS - PRECEDENCE" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Operator Precedence Rules\n", "\n", "# The order of operations in Python is similar to mathematics:\n", "# 1. Parentheses `()`\n", "# 2. Exponentiation `**`\n", "# 3. Multiplication `*`, Division `/`, Floor Division `//`, Modulus `%`\n", "# 4. Addition `+`, Subtraction `-`\n", "\n", "a = 3\n", "b = 2\n", "c = 1\n", "\n", "print(f'a = {a}, b = {b}, c = {c}')\n", "\n", "print(f'a + b - c: {a + b - c}')\n", "print(f'a * b - c: {a * b - c}')\n", "print(f'a + b * c: {a + b * c}')\n", "print(f'(a + b) * c: {(a + b) * c}')\n", "print(f'a + (b * c): {a + (b * c)}')\n", "print(f'a * b ** c: {a * b ** c}')\n", "print(f'(a * b) ** c: {(a * b) ** c}')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# MODULE 3 - CONTROL STRUCTURES" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## CONTROL STRUCTURES - IF-ELSE / IF-ELIF-ELSE" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Conditional Statements Syntax\n", "\n", "# `if` is followed by one or more optional `elif` and an optional `else`.\n", "# The indentation is crucial and defines the code block for each condition.\n", "\n", "if condition1:\n", " # code to execute if condition1 is true\n", " pass\n", "elif condition2:\n", " # code to execute if condition1 is false and condition2 is true\n", " pass\n", "else:\n", " # code to execute if all preceding conditions are false\n", " pass" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# `if-else` Example\n", "\n", "a = 1\n", "b = 2\n", "\n", "if a > b:\n", " print('a is greater than b')\n", "else:\n", " print('a is not greater than b')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# `if-elif-else` Example\n", "\n", "a = 1\n", "b = 2\n", "\n", "if a > b:\n", " print('a is greater than b')\n", "elif a == b:\n", " print('a equals b')\n", "else:\n", " print('a is less than b')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# `if-else` with User Input\n", "\n", "try:\n", " order = float(input('What is the order amount: '))\n", " if order > 100:\n", " discount = 25\n", " else:\n", " discount = 0\n", " print(f'Discount = {discount}')\n", "except ValueError:\n", " print('Invalid input. Please enter a numerical value.')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## CONTROL STRUCTURES - TERNARY OPERATOR" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Ternary Operator (Conditional Expression)\n", "\n", "# The syntax is `value_if_true if condition else value_if_false`.\n", "try:\n", " order = float(input('What is the order amount: '))\n", " discount = 25 if order > 100 else 0\n", " print(f'Discount = {discount}')\n", "except ValueError:\n", " print('Invalid input. Please enter a numerical value.')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Challenge: Grade Evaluation with `if-elif-else`\n", "\n", "grade = input('What is your grade? ').upper() # Convert to uppercase for case-insensitive comparison\n", "\n", "if grade == 'A':\n", " print('Excellent!')\n", "elif grade == 'B':\n", " print('Well done!')\n", "elif grade == 'C':\n", " print('Work harder')\n", "else:\n", " print(\"I don't know your grade\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## CONTROL STRUCTURES - WHILE LOOP" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# `while` loop syntax\n", "\n", "while condition:\n", " # code to execute while the condition is true\n", " # Remember to update the loop control variable to avoid infinite loops\n", " pass" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# `while` loop Example\n", "\n", "try:\n", " loop_limit = int(input('Enter the number of loops: '))\n", " count = 1\n", "\n", " print('Begin loop')\n", " while count <= loop_limit:\n", " print(f'Inside loop: count = {count}')\n", " count += 1\n", "\n", " print('End loop')\n", "except ValueError:\n", " print('Invalid input. Please enter an integer.')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Challenge: Create a guessing game with a `while` loop\n", "\n", "import random\n", "\n", "secret_number = random.randint(1, 10)\n", "guess = 0\n", "\n", "print('Guess a number between 1 and 10.')\n", "while guess != secret_number:\n", " try:\n", " guess = int(input('Enter your guess: '))\n", " if guess > secret_number:\n", " print('Too high!')\n", " elif guess < secret_number:\n", " print('Too low!')\n", " except ValueError:\n", " print('Invalid input. Please enter an integer.')\n", "\n", "print(f'Congratulations! The number was {secret_number}.')\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## CONTROL STRUCTURES - FOR-LOOP" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# `for` loop syntax with `range()`\n", "\n", "# `range(stop)`: generates numbers from 0 to `stop - 1`.\n", "# `range(start, stop)`: generates numbers from `start` to `stop - 1`.\n", "# `range(start, stop, step)`: generates numbers with a specified increment `step`.\n", "\n", "for variable in iterable:\n", " # code to execute for each item in the iterable\n", " pass" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# `for` loop with `range()`\n", "\n", "try:\n", " loop_limit = int(input('Enter the number of loops: '))\n", " print('Begin loop')\n", "\n", " for i in range(1, loop_limit + 1):\n", " print(f'Inside loop: i = {i}')\n", "\n", " print('End loop')\n", "except ValueError:\n", " print('Invalid input. Please enter an integer.')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Appending to a list within a `for` loop\n", "\n", "try:\n", " loop_limit = int(input('Enter the number of loops: '))\n", " my_list = []\n", "\n", " print('Begin loop')\n", "\n", " for i in range(1, loop_limit + 1):\n", " my_list.append(i)\n", " print(f'List inside loop: {my_list}')\n", "\n", " print('End loop')\n", "except ValueError:\n", " print('Invalid input. Please enter an integer.')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Challenge: Print a multiplication table using nested `for` loops\n", "\n", "try:\n", " table_size = int(input('Enter the size of the multiplication table: '))\n", " for i in range(1, table_size + 1):\n", " for j in range(1, table_size + 1):\n", " print(f'{i} * {j} = {i * j}')\n", "except ValueError:\n", " print('Invalid input. Please enter an integer.')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# MODULE 4 - FUNCTIONS" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## FUNCTIONS" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Functions are reusable blocks of code that perform a specific task.\n", "# They can take inputs (arguments) and return outputs (return values).\n", "\n", "# A function is defined using the `def` keyword, followed by the function name, parentheses `()`, and a colon `:`. Arguments are placed inside the parentheses." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Function Syntax\n", "\n", "def function_name(argument1, argument2, ...):\n", " \"\"\"Docstring: Brief explanation of what the function does.\"\"\"\n", " # Code block\n", " result = # calculation\n", " return result\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Function with one argument and one return value\n", "\n", "def powertwo(x):\n", " return x * x\n", "\n", "try:\n", " n = int(input('Enter a number: '))\n", " result = powertwo(n)\n", " print(f'The square of {n} is {result}')\n", "except ValueError:\n", " print('Invalid input. Please enter an integer.')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Challenge: Taxi Fare Calculation\n", "\n", "def calculate_taxi_fare(distance_km, booking_fee=35, starting_price=35, cost_per_km=6.5):\n", " \"\"\"Calculates taxi fare based on distance and standard rates.\"\"\"\n", " return booking_fee + starting_price + (distance_km * cost_per_km)\n", "\n", "try:\n", " distance = float(input('Enter the distance in km: '))\n", " fare = calculate_taxi_fare(distance)\n", " print(f'The total taxi fare is: {fare:.2f} Baht')\n", "except ValueError:\n", " print('Invalid input. Please enter a numerical distance.')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Function with one argument and multiple return values (as a tuple)\n", "\n", "def power23(x):\n", " return (x * x, x * x * x)\n", "\n", "try:\n", " n = int(input('Enter a number: '))\n", " square, cube = power23(n) # Unpacking the returned tuple into two variables\n", " print(f'The square and cube of {n} are {square} and {cube}.')\n", "except ValueError:\n", " print('Invalid input. Please enter an integer.')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Challenge: Grocery Purchase Calculation\n", "\n", "def calculate_grocery_costs(order_amount):\n", " \"\"\"Calculates discount and tax for a grocery order.\"\"\"\n", " discount = 25 if order_amount > 200 else 0\n", " order_after_discount = order_amount - discount\n", " tax = 0.07 * order_after_discount\n", " return discount, tax\n", "\n", "try:\n", " order_total = float(input('Enter the total order amount: '))\n", " discount_value, tax_value = calculate_grocery_costs(order_total)\n", " print(f'Discount: {discount_value:.2f}')\n", " print(f'Tax: {tax_value:.2f}')\n", "except ValueError:\n", " print('Invalid input. Please enter a numerical value.')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Function with two arguments and one return value\n", "\n", "def add(x, y):\n", " return x + y\n", "\n", "try:\n", " m = int(input('Enter a number #1: '))\n", " n = int(input('Enter a number #2: '))\n", " result = add(m, n)\n", " print(f'{m} + {n} = {result}')\n", "except ValueError:\n", " print('Invalid input. Please enter integers.')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Function with Default Argument Values\n", "\n", "def rect(a=3, b=5):\n", " \"\"\"Calculates the area of a rectangle with optional side lengths.\"\"\"\n", " return a * b\n", "\n", "print(f'Area with default values: {rect()}')\n", "print(f'Area with custom values (2, 3): {rect(2, 3)}')\n", "print(f'Area with keyword arguments (a=4, b=6): {rect(a=4, b=6)}')\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Function with Variable-Length Arguments (`*args`)\n", "\n", "def custom_sum(*numbers):\n", " \"\"\"Returns the sum of all provided arguments.\"\"\"\n", " total = 0\n", " for num in numbers:\n", " total += num\n", " return total\n", "\n", "print(f'Sum of (1, 2, 3): {custom_sum(1, 2, 3)}')\n", "print(f'Sum of (1, 2, 3, 4, 5): {custom_sum(1, 2, 3, 4, 5)}')\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Challenge: Minimum Value Function with Variable Arguments\n", "\n", "def find_min(*args):\n", " \"\"\"Finds the minimum value among a variable number of arguments.\"\"\"\n", " if not args:\n", " return None\n", " min_val = args[0]\n", " for item in args[1:]:\n", " if item < min_val:\n", " min_val = item\n", " return min_val\n", "\n", "print(f'Minimum of (5, 2, 8, 1, 9): {find_min(5, 2, 8, 1, 9)}')\n", "print(f'Minimum of (100, 50, 200): {find_min(100, 50, 200)}')\n", "\n", "# Alternatively, use the built-in `min()` function, which is more efficient.\n", "print(f'Using built-in min(): {min(5, 2, 8, 1, 9)}')\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## FUNCTIONS - LAMBDA" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Lambda Functions Documentation\n", "# Reference: https://www.w3schools.com/python/python_lambda.asp\n", "\n", "# A `lambda` function is a small anonymous function defined with the `lambda` keyword. It can have any number of arguments but only one expression. It is often used when a simple, single-expression function is needed for a short period, especially as an argument to a higher-order function like `map()`, `filter()`, or `sorted()`.\n", "\n", "lambda arguments: expression\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Creating a Lambda Function\n", "\n", "# Define a lambda function to calculate the square of a number.\n", "f = lambda x: x**2\n", "\n", "print(f'The square of 10 is: {f(10)}')\n", "\n", "# The equivalent `def` function:\n", "def square(x):\n", " return x**2\n", "\n", "print(f'The square of 10 using a regular function is: {square(10)}')\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Challenge: Convert a `def` function to a `lambda` function\n", "\n", "# Original function\n", "def f(x, y):\n", " return 10*x + y\n", "\n", "print(f'Result of f(2, 3) using def: {f(2, 3)}')\n", "\n", "# The lambda equivalent\n", "g = lambda x, y: 10 * x + y\n", "\n", "print(f'Result of g(2, 3) using lambda: {g(2, 3)}')\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## FUNCTIONS - MAP" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# `map()` Function Documentation\n", "# Reference: https://www.w3schools.com/python/ref_func_map.asp\n", "\n", "# The `map()` function applies a given function to each item of an iterable (like a list or tuple) and returns a map object, which is an iterator.\n", "\n", "map(function, iterable)\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Using `map()` with a Lambda Function\n", "\n", "numbers = [1, 2, 3, 4, 5]\n", "square = lambda x: x**2\n", "\n", "print(f'Original list: {numbers}')\n", "\n", "squared_numbers_map = map(square, numbers)\n", "\n", "# The map object must be converted to a list to be printed.\n", "squared_numbers_list = list(squared_numbers_map)\n", "\n", "print(f'List of squared numbers: {squared_numbers_list}')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Challenge: Using `map()` with multiple iterables\n", "\n", "x_list = [0, 1, 2, 3]\n", "y_list = [2, 4, 6, 8]\n", "\n", "# A lambda function can take multiple arguments.\n", "combine_func = lambda x, y: 10 * x + y\n", "\n", "# When `map()` is given multiple iterables, it passes one item from each iterable to the function.\n", "result_map = map(combine_func, x_list, y_list)\n", "result_list = list(result_map)\n", "\n", "print(f'x list: {x_list}')\n", "print(f'y list: {y_list}')\n", "print(f'Combined result: {result_list}')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# MODULE 5 - MODULES (LIBRARY)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Modules Introduction\n", "\n", "# A module is a Python file that contains a set of related functions, classes, and variables. It allows for code organization and reusability.\n", "\n", "# Common ways to import a module:\n", "# 1. `import module_name`: Imports the entire module. You must use `module_name.function()` to access its contents.\n", "# 2. `import module_name as alias`: Imports the module with an abbreviated name. You use `alias.function()`.\n", "# 3. `from module_name import function1, function2`: Imports specific functions into the current namespace, allowing you to call them directly.\n", "# 4. `from module_name import *`: Imports all functions and variables from the module into the current namespace. This is generally discouraged as it can lead to naming conflicts.\n", "\n", "# The Python Standard Library includes many useful modules like `math`, `random`, `statistics`, `os`, `sys`, and `datetime`." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Importing an entire library\n", "\n", "import math\n", "\n", "# To use a function from the math module, you must prefix it with `math.`\n", "result = math.sin(0.5)\n", "print(f'math.sin(0.5) -> {result}')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Importing a library with an alias\n", "\n", "import math as m\n", "\n", "# Now you can use `m.sin()` instead of `math.sin()`.\n", "result = m.sin(0.5)\n", "print(f'm.sin(0.5) -> {result}')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Importing all names from a library\n", "\n", "from math import *\n", "\n", "# Functions can be called directly without the `math.` prefix.\n", "result = sin(0.5)\n", "print(f'sin(0.5) -> {result}')\n", "\n", "# This can be confusing, as it's not immediately clear where `sin` comes from. For this reason, `from math import *` is often avoided in professional code." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# The difference between `import module` and `from module import *`\n", "\n", "# `import module` is generally preferred because it keeps the current namespace clean and makes it explicit which module a function or variable belongs to. This prevents potential name clashes and improves code readability.\n", "\n", "import math\n", "print('Using import math:', math.sqrt(16))\n", "\n", "from math import sqrt\n", "print('Using from math import sqrt:', sqrt(16))\n", "\n", "# With `from math import *`, it is unclear where `sqrt` originated from.\n", "# Imagine a scenario where two different modules define a function named `log`. A wildcard import would make it difficult to determine which version is being called." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Importing selected names from a library\n", "\n", "from math import sin, pi\n", "\n", "# You can now use `sin` and `pi` directly, but not other functions from the math module like `cos`.\n", "print(f'The sine of pi/2 is: {sin(pi/2)}')\n", "\n", "try:\n", " print(f'The cosine of 0 is: {cos(0)}')\n", "except NameError as e:\n", " print(f'Error: {e}. The `cos` function was not imported.')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## MODULES - MATH" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Using the `math` library's constants\n", "\n", "import math\n", "\n", "print(f'Value of pi: {math.pi}')\n", "print(f'Value of e: {math.e}')\n", "print(f'Positive infinity: {math.inf}')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Using the sine function from `math`\n", "\n", "import math\n", "\n", "try:\n", " n = float(input('Enter a number (in radians): '))\n", " result = math.sin(n)\n", " print(f'sin({n}) = {result}')\n", "except ValueError:\n", " print('Invalid input. Please enter a numerical value.')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Using the cosine function from `math`\n", "\n", "import math\n", "\n", "try:\n", " n = float(input('Enter a number (in radians): '))\n", " result = math.cos(n)\n", " print(f'cos({n}) = {result}')\n", "except ValueError:\n", " print('Invalid input. Please enter a numerical value.')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Converting degrees to radians\n", "\n", "import math\n", "\n", "try:\n", " n = float(input('Enter a degree value: '))\n", " radians = math.radians(n)\n", " print(f'{n} degrees is equal to {radians} radians.')\n", "except ValueError:\n", " print('Invalid input. Please enter a numerical value.')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Computing a base-2 logarithm\n", "\n", "import math\n", "\n", "try:\n", " n = float(input('Enter a number: '))\n", " result = math.log(n, 2)\n", " print(f'log2({n}) = {result}')\n", "except ValueError:\n", " print('Invalid input. Please enter a positive numerical value.')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Computing a logarithm with a custom base\n", "\n", "import math\n", "\n", "try:\n", " m = float(input('Enter a number: '))\n", " n = float(input('Enter a base value: '))\n", " result = math.log(m, n)\n", " print(f'log{n}({m}) = {result}')\n", "except ValueError:\n", " print('Invalid input. Please enter positive numerical values for both number and base.')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Computing a factorial\n", "\n", "import math\n", "\n", "try:\n", " n = int(input('Enter a non-negative integer: '))\n", " result = math.factorial(n)\n", " print(f'{n}! = {result}')\n", "except ValueError:\n", " print('Invalid input. Please enter a non-negative integer.')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Computing the greatest common divisor (GCD)\n", "\n", "import math\n", "\n", "try:\n", " m = int(input('Enter a number #1: '))\n", " n = int(input('Enter a number #2: '))\n", " result = math.gcd(m, n)\n", " print(f'The GCD of {m} and {n} is {result}')\n", "except ValueError:\n", " print('Invalid input. Please enter integers.')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Computing a square root\n", "\n", "import math\n", "\n", "try:\n", " n = float(input('Enter a non-negative number: '))\n", " result = math.sqrt(n)\n", " print(f'The square root of {n} is {result}')\n", "except ValueError:\n", " print('Invalid input. Please enter a non-negative number.')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Computing floor and ceil functions\n", "\n", "import math\n", "\n", "try:\n", " n = float(input('Enter a number with decimal points: '))\n", " \n", " print(f'Original number: {n}')\n", " print(f'Rounded (round): {round(n)}') # `round()` rounds to the nearest even number for .5 cases\n", " print(f'Rounded down (floor): {math.floor(n)}')\n", " print(f'Rounded up (ceil): {math.ceil(n)}')\n", "except ValueError:\n", " print('Invalid input. Please enter a numerical value.')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## MODULES - RANDOM" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# The `random` module provides functions for generating random numbers and performing random selections.\n", "\n", "# `random.seed()` is optional. When you provide a seed, the sequence of random numbers will be reproducible." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Generating a random float from 0 to 1\n", "\n", "import random\n", "\n", "print('Generating five random floats:')\n", "for _ in range(5):\n", " print(random.random())" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Generating a random integer from a range (exclusive end)\n", "\n", "import random\n", "\n", "try:\n", " m = int(input('Enter a starting number: '))\n", " n = int(input('Enter an ending number: '))\n", " \n", " print(f'Generating five random integers in range [{m}, {n}):')\n", " for _ in range(5):\n", " print(random.randrange(m, n))\n", "\n", " print(f'\\nGenerating five random odd numbers in range [{m}, {n}):')\n", " for _ in range(5):\n", " # The third argument is the step value.\n", " print(random.randrange(m, n, 2))\n", "except ValueError:\n", " print('Invalid input. Please enter integers.')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Generating a random integer from a range (inclusive end)\n", "\n", "import random\n", "\n", "try:\n", " m = int(input('Enter a starting number: '))\n", " n = int(input('Enter an ending number: '))\n", " \n", " print(f'Generating five random integers in range [{m}, {n}]:')\n", " for _ in range(5):\n", " print(random.randint(m, n))\n", "except ValueError:\n", " print('Invalid input. Please enter integers.')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Generating a random float with uniform distribution\n", "\n", "import random\n", "\n", "try:\n", " m = float(input('Enter a starting number: '))\n", " n = float(input('Enter an ending number: '))\n", " \n", " print(f'Generating five random floats with uniform distribution in range [{m}, {n}]')\n", " for _ in range(5):\n", " print(random.uniform(m, n))\n", "except ValueError:\n", " print('Invalid input. Please enter numerical values.')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Generating a random float with Gaussian (normal) distribution\n", "\n", "import random\n", "\n", "try:\n", " mu = float(input('Enter the mean (mu): '))\n", " sigma = float(input('Enter the standard deviation (sigma): '))\n", " \n", " print('Generating five random floats with Gaussian distribution:')\n", " for _ in range(5):\n", " print(random.gauss(mu, sigma))\n", "except ValueError:\n", " print('Invalid input. Please enter numerical values.')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Selecting a random item from a sequence\n", "\n", "import random\n", "\n", "possible_pets = ['bat', 'cat', 'dog', 'fish']\n", "\n", "print(f'List of possible pets: {possible_pets}')\n", "\n", "print('Generating five random pet choices:')\n", "for _ in range(5):\n", " print(random.choice(possible_pets))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Shuffling a sequence in-place\n", "\n", "import random\n", "\n", "cards = ['Jack', 'Queen', 'King', 'Ace']\n", "\n", "print(f'Original list of cards: {cards}')\n", "\n", "print('Generating five shuffled lists:')\n", "for _ in range(5):\n", " random.shuffle(cards)\n", " print(cards)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## MODULES - STATISTICS" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# The `statistics` module provides functions for calculating common mathematical statistics of numeric data.\n", "# Reference: https://www.w3schools.com/python/module_statistics.asp" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Calculating the mean (average)\n", "\n", "import statistics\n", "\n", "x = [1, 2, 3, 4, 5, 6]\n", "\n", "print(f'List of values: {x}')\n", "print(f'The mean is: {statistics.mean(x)}')\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Calculating the median\n", "\n", "import statistics\n", "\n", "x = [1, 2, 3, 4, 5, 6]\n", "\n", "print(f'List of values: {x}')\n", "print(f'The median is: {statistics.median(x)}')\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Calculating the population variance\n", "\n", "import statistics\n", "\n", "x = [1, 2, 3, 4, 5, 6]\n", "\n", "print(f'List of values: {x}')\n", "print(f'The variance is: {statistics.pvariance(x)}') # pvariance for population variance\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Calculating the standard deviation\n", "\n", "import statistics\n", "\n", "x = [1, 2, 3, 4, 5, 6]\n", "\n", "print(f'List of values: {x}')\n", "print(f'The standard deviation is: {statistics.pstdev(x)}') # pstdev for population standard deviation\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## MODULES - DATE & TIME" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# The `datetime` module provides classes for manipulating dates and times.\n", "# Reference: https://www.w3schools.com/python/python_datetime.asp" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Displaying the current date and time components\n", "\n", "from datetime import datetime\n", "\n", "now = datetime.now()\n", "\n", "print(f'Full timestamp: {now}')\n", "print(f'Date: {now.date()}')\n", "print(f'Time: {now.time()}')\n", "print(f'Year: {now.year}')\n", "print(f'Month: {now.month}')\n", "print(f'Day: {now.day}')\n", "print(f'Hour: {now.hour}')\n", "print(f'Minute: {now.minute}')\n", "print(f'Second: {now.second}')\n", "print(f'Microsecond: {now.microsecond}')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## MODULES - FILE AND URL" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Assignment" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Opening a file from a URL\n", "\n", "import urllib.request\n", "\n", "url = \"https://piyabute.com/data/research/iris.data.csv\"\n", "\n", "try:\n", " with urllib.request.urlopen(url) as file:\n", " for line in file:\n", " decoded_line = line.decode(\"utf-8\").strip()\n", " print(decoded_line)\n", "except Exception as e:\n", " print(f'An error occurred: {e}')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Reading a local file\n", "\n", "file_path = \"iris.data.csv\"\n", "\n", "try:\n", " with open(file_path, \"r\") as my_file:\n", " content = my_file.read()\n", " print('File content:')\n", " print(content)\n", "\n", " content_list = content.split(\"\\n\") # Split by newline to get lines as list\n", " print('\\nContent as a list of lines:')\n", " print(content_list)\n", "except FileNotFoundError:\n", " print(f'Error: The file {file_path} was not found.')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "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.12.3" } }, "nbformat": 4, "nbformat_minor": 4 }