{ "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", "# Enter a symbol # at the beginning of any line to make it a comment\n", "# For example, the following line is a comment:\n", "# Type print('Hello World')\n", "\n", "# When you remove the # symbol, the line becomes executable code\n", "# Press Enter to enter a new line\n", "# Press Shift+Enter to run each block of code\n", "\n", "# Let's demonstrate it with a simple print statement\n", "print('Hello World') # This line is not a comment and will be executed" ] }, { "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\n", "\n", "# Python supports six major data types:\n", "\n", "# 1. Number\n", "# 2. String\n", "# 3. List** `[ Bracket ]` - Mutable\n", "# 4. Tuple `( Parenthesis )` - Immutable\n", "# 5. Dictionary `{ Braces }`\n", "# 6. Set**\n", "\n", "# List\n", "# - General purpose\n", "# - Most widely used data structure\n", "# - Can grow and shrink in size as needed\n", "# - Sequence type\n", "# - Sortable\n", "\n", "# Tuple\n", "# - Immutable (cannot be changed after creation)\n", "# - Useful for fixed data\n", "# - Faster than lists\n", "# - Sequence type\n", "\n", "# Dictionary\n", "# - Consists of key/value pairs\n", "# - Acts like an associative array, similar to Java's HashMap\n", "# - Unordered\n", "\n", "# Set\n", "# - Stores non-duplicate items\n", "# - Provides very fast access compared to lists\n", "# - Supports mathematical set operations like union and intersection\n", "# - Unordered\n", "\n", "# For more Python tips and tricks, you can visit [this link](https://arilamstein.com/blog/2020/04/22/using-python-to-cheat-at-scrabble/)." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## ARTIHMETIC" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Variable a = 100\n", "Variable b = 9\n", "a + b = 109\n", "a - b = 91\n", "a + b = 109 , a - b = 91\n", "a × b = 900\n", "a ÷ b = 11.11111111111111\n", "a div b = 11\n", "a mod b = 1\n", "a ^ b = 1000000000000000000\n" ] } ], "source": [ "# Introduction to Basic Arithmetic Operations in Python\n", "\n", "# Step 1: Create two variables and assign values to them\n", "a = 100 # Assign 100 to the variable 'a'\n", "b = 9 # Assign 9 to the variable 'b'\n", "\n", "# Step 2: Perform Basic Arithmetic Operations\n", "output_add = a + b # Addition\n", "output_sub = a - b # Subtraction\n", "output_mul = a * b # Multiplication\n", "output_divi = a / b # Division\n", "output_div = a // b # Integer Division (floor division)\n", "output_mod = a % b # Modulus (remainder)\n", "output_exp = a ** b # Exponentiation\n", "\n", "# Step 3: Print the Results\n", "\n", "# Print individual variables\n", "print('Variable a =', a)\n", "print('Variable b =', b)\n", "\n", "# Print the results of arithmetic operations\n", "print('a + b =', output_add) # Addition\n", "print('a - b =', output_sub) # Subtraction\n", "print('a + b =', output_add, ', a - b =', output_sub) # Printing multiple results in one line\n", "\n", "# Print multiplication and division results without extra spaces\n", "print('a × b =', output_mul) # Multiplication\n", "print('a ÷ b =', output_divi) # Division\n", "\n", "# Print division results (integer division and modulus)\n", "print('a div b =', output_div) # Integer Division (floor division)\n", "print('a mod b =', output_mod) # Modulus (remainder)\n", "\n", "# Print the result of exponentiation\n", "print('a ^ b =', output_exp) # Exponentiation\n" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Value of c = 3\n", "Value of d = -1\n" ] } ], "source": [ "# Assigning Numbers to Multiple Variables in a Single Statement\n", "\n", "# Step 1: Assign values to variables a and b\n", "a, b = 1, 2 # Assign 1 to variable 'a' and 2 to variable 'b'\n", "\n", "# Step 2: Perform Arithmetic Operations\n", "# Calculate the sum of a and b and assign it to variable c\n", "c = a + b\n", "\n", "# Calculate the difference of a and b and assign it to variable d\n", "d = a - b\n", "\n", "# Step 3: Print the Results\n", "\n", "# Print the values of variables c and d\n", "print('Value of c =', c)\n", "print('Value of d =', d)" ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "scrolled": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "a → b → c: 3.4567 + 4 = 7.4567\n", "b → a → c: 4 + 3.4567 = 7.4567\n", "a → b → c: 3.46 + 4.00 = 7.46\n", "b → a → c: 4.000 + 3.457 = 7.457\n" ] } ], "source": [ "# Printing Floating-Point Numbers in Various Formats\n", "\n", "# Step 1: Define floating-point variables\n", "a = 3.4567\n", "b = 4\n", "c = a + b\n", "\n", "# Step 2: Print in Different Formats\n", "\n", "# Default formatting: Print all decimal points in the default order (as is)\n", "print('a → b → c: {} + {} = {}'.format(a, b, c)) # Default formatting\n", "\n", "# Specifying the order of variables: Print numbers in a specific order\n", "print('b → a → c: {1} + {0} = {2}'.format(a, b, c)) # Specifying the order of variables\n", "\n", "# Formatting with two decimal points: Print numbers with a specific number of decimal points (0 = actual decimal digits, 2 = two decimal points)\n", "print('a → b → c: {:0.2f} + {:0.2f} = {:0.2f}'.format(a, b, c)) # Formatting with two decimal points\n", "\n", "# Formatting with three decimal points: Print numbers in a specific order with a specific number of decimal points\n", "print('b → a → c: {1:0.3f} + {0:0.3f} = {2:0.3f}'.format(a, b, c)) # Formatting with three decimal points" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## DATA TYPE - STRING" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Concatenation without separator:\n", "DigitalBusiness\n", "Digital Business\n", "DigitalBusiness\n", "c = DigitalBusiness\n", "a+b = DigitalBusiness\n", "\n", "Concatenation with space separator:\n", "Digital Business\n", "Digital Business\n", "c = Digital Business\n", "a+b = DigitalBusiness\n" ] } ], "source": [ "# Working with Strings and Concatenation\n", "\n", "# Step 1: Assign strings to variables\n", "a = 'Digital'\n", "b = 'Business'\n", "\n", "# Step 2: Concatenate Strings and Print the Results\n", "\n", "# Concatenate two strings without a separator\n", "c = a + b\n", "print('Concatenation without separator:')\n", "print(c) # Output: 'DigitalBusiness'\n", "print(a, b) # Output: 'Digital Business'\n", "print(a, b, sep='') # Output: 'DigitalBusiness'\n", "print('c = ', c, sep='') # Output: 'c = DigitalBusiness'\n", "print('a+b = ', a + b, sep='') # Output: 'a+b = DigitalBusiness'\n", "\n", "# Concatenate two strings with a space separator\n", "c = a + ' ' + b\n", "print('\\nConcatenation with space separator:')\n", "print(c) # Output: 'Digital Business'\n", "print(a, b) # Output: 'Digital Business'\n", "print('c = ', c, sep='') # Output: 'c = Digital Business'\n", "print('a+b = ', a + b, sep='') # Output: 'a+b = Digital Business'" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Printing a String Variable with Additional Text\n", "\n", "# Step 1: Define string variables\n", "fname = 'Piyabute'\n", "lname = 'Fuangkhon'\n", "\n", "# Step 2: Print the Name in Different Formats\n", "\n", "# Format 1: Using multiple print statements to display the name\n", "print('My name is', fname, lname)\n", "\n", "# Format 2: Concatenating variables and removing spaces with 'sep' parameter\n", "print('My name is ', fname, ' ', lname, sep='')\n", "\n", "# Format 3: Using string formatting with curly braces {}\n", "print('My name is {} {}'.format(fname, lname))\n", "\n", "# Format 4: Using string formatting with indices {0} and {1}\n", "print('My name is {1} {0}'.format(fname, lname))\n", "\n", "# Adding a period at the end of the name\n", "\n", "# Format 5: Using multiple print statements to display the name with a period\n", "print('My name is', fname, lname, '.')\n", "\n", "# Format 6: Concatenating variables and removing spaces with 'sep' parameter, and adding a period\n", "print('My name is ', fname, ' ', lname, '.', sep='')\n", "\n", "# Format 7: Using string formatting with curly braces {} and adding a period\n", "print('My name is {} {}.'.format(fname, lname))\n", "\n", "# Format 8: Using string formatting with indices {0} and {1}, and adding a period\n", "print('My name is {1} {0}.'.format(fname, lname))\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Removing Whitespace from Strings\n", "\n", "# Step 1: Define string variables with whitespaces\n", "a = ' Digital '\n", "b = 'Business'\n", "\n", "# Step 2: Print the original strings and their concatenation\n", "print('Original strings and concatenation:')\n", "print('a =', a) # Output: ' Digital '\n", "print('b =', b) # Output: 'Business'\n", "print('a+b =', a + b) # Output: ' Digital Business'\n", "\n", "# Step 3: Remove Whitespaces\n", "\n", "# Remove all whitespaces (leading and trailing)\n", "c = a.strip()\n", "print('\\na.strip() =', c + b) # Output: 'DigitalBusiness'\n", "\n", "# Remove trailing whitespaces\n", "c = a.rstrip()\n", "print('a.rstrip() =', c + b) # Output: ' DigitalBusiness'\n", "\n", "# Remove leading whitespaces\n", "c = a.lstrip()\n", "print('a.lstrip() =', c + b) # Output: 'Digital Business'" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Finding the Location of a Specific Term in a String\n", "\n", "# Step 1: Define the input string\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", "# Step 2: Find the location of the term 'fantasy' in the string\n", "location = message.find('fantasy')\n", "\n", "# Step 3: Print the result\n", "print(\"'fantasy' is found at the location\", location) # Output: 'fantasy' is found at the location 34, startimg from 0" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Counting the Number of Occurrences of a Keyword in a String\n", "\n", "# Step 1: Define the input string\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", "# Step 2: Count the number of occurrences of the keyword 'novel' in the string\n", "count = message.count('novel')\n", "\n", "# Step 3: Print the result\n", "print(\"'novel' appears\", count, 'times') # Output: 'novel' appears 2 times" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Converting a String to Uppercase\n", "\n", "# Step 1: Define the input string\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", "# Step 2: Convert the string to uppercase\n", "message_upper = message.upper()\n", "\n", "# Step 3: Print the original and uppercase strings\n", "print('Original message:')\n", "print('message =', message) # Output: Original string\n", "print('\\nUppercase message:')\n", "print('message.upper() →', message_upper) # Output: Uppercase string" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Converting a String to Lowercase\n", "\n", "# Step 1: Define the input string\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", "# Step 2: Convert the string to lowercase\n", "message_lower = message.lower()\n", "\n", "# Step 3: Print the original and lowercase strings\n", "print('Original message:')\n", "print('message =', message) # Output: Original string\n", "print('\\nLowercase message:')\n", "print('message.lower() →', message_lower) # Output: Lowercase string" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Replacing a Character in a String\n", "\n", "# Step 1: Define the input string\n", "message = 'piyabutefng@au.edu'\n", "\n", "# Step 2: Replace the '@' character with ' at ' in the string\n", "message_new = message.replace('@', ' at ')\n", "\n", "# Step 3: Print the original and modified strings\n", "print('Original message:')\n", "print('message =', message) # Output: Original string\n", "print('\\nModified message:')\n", "print('message.replace(\"@\", \" at \") →', message_new) # Output: Modified string" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## DATA TYPE - LIST [Square Bracket]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# https://www.w3schools.com/python/python_lists.asp" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Create a List and Read Specific Elements\n", "\n", "# Step 1: Create a list\n", "a = [101, 102, 103, 104, 105]\n", "\n", "# Step 2: Print the entire list\n", "print('a = ', a)\n", "\n", "# Step 3: Read the first element of the list (The first element is at index 0)\n", "print('a[0] →', a[0])\n", "\n", "# Step 4: Read the second element of the list (The second element is at index 1)\n", "print('a[1] →', a[1])\n", "\n", "# Step 5: Print the data type of the variable (It should show 'list')\n", "print('type(a) →', type(a))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Assign Values with Different Types to a List\n", "\n", "# Step 1: Create a list with values of different types\n", "a = [101, 'Hello', True]\n", "\n", "# Step 2: Print the list\n", "print('a =', a)\n", "\n", "# Step 3: Print the data type of the variable (It should show 'list')\n", "print('type(a) →', type(a))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Find the Index of a Specific Element (Numerical Type)\n", "\n", "# Step 1: Create a list\n", "a = [101, 102, 103, 104, 105]\n", "\n", "# Step 2: Print the list\n", "print('a =', a)\n", "\n", "# Step 3: Find the index of the element 103 (The first element is at index 0, not 1)\n", "print('a.index(103) →', a.index(103))\n", "#print('a.index(106) →', a.index(106))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Find if a Specific Value is in a List\n", "\n", "# Step 1: Create a list\n", "a = [101, 102, 103, 104, 105]\n", "\n", "# Step 2: Print the list\n", "print('a =', a)\n", "\n", "# Step 3: Check if 103 is in the list\n", "print('103 is in a →', 103 in a)\n", "\n", "# Step 4: Check if 106 is in the list\n", "print('106 is in a →', 106 in a)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Find the Index of a Specific Element (String Type)\n", "\n", "# Step 1: Create a list of strings\n", "a = ['A1', 'B1', 'C1', 'D1', 'E1']\n", "\n", "# Step 2: Print the list\n", "print('a =', a)\n", "\n", "# Step 3: Find the index of 'D1' (The first element is at index 0, not 1)\n", "print(\"a.index('D1') →\", a.index('D1'))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Change the Values of an Element in a List\n", "\n", "# Step 1: Create a list\n", "a = [101, 102, 103, 104, 105]\n", "\n", "# Step 2: Print the original list\n", "print('a =', a)\n", "\n", "# Step 3: Change the second element of the list to 999\n", "a[1] = 999\n", "print('a[1]=999 →', a)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Challenge\n", "# Replace the value of a specified number with 999" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Add a New Element to the End of the List\n", "\n", "# Step 1: Create a list\n", "a = [101, 102, 103, 104, 105]\n", "\n", "# Step 2: Print the original list\n", "print('a =', a)\n", "\n", "# Step 3: Append the list with the value 999\n", "a.append(999)\n", "print('a.append(999) →', a)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Insert an Element into a List at a Specific Location\n", "\n", "# Step 1: Create a list\n", "a = [101, 102, 103, 104, 105]\n", "\n", "# Step 2: Print the original list\n", "print('Original List:', a)\n", "\n", "# Step 3: Insert the value 888 at the third index\n", "a.insert(2, 888) # The insert method inserts 888 at index 2 (third position).\n", "print('Insert 888 at index 2:', a)\n", "\n", "# Step 4: Insert the value 999 at the second last position (negative index begins from the end)\n", "a.insert(-1, 999) # The negative index -1 represents the second last position.\n", "print('Insert 999 at second last position:', a)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Delete a Specific Element from a List\n", "\n", "# Step 1: Create a list\n", "a = [101, 102, 103, 104, 105, 106, 107, 108, 109, 110]\n", "print('Original list (a):', a)\n", "\n", "# Step 2: Delete the value 103 using a.remove()\n", "a.remove(103)\n", "print('After removing 103 (a.remove(103)):', a)\n", "\n", "# Step 3: Delete the index 1 (Delete the value 102) using del\n", "del a[1]\n", "print('After deleting index 1 (del a[1]):', a)\n", "\n", "# Step 4: Delete the last index (Delete the value 110) using del\n", "del a[-1]\n", "print('After deleting the last index (del a[-1]):', a)\n", "\n", "# Step 5: Delete the index 1 (Delete the value 104) using a.pop(1)\n", "a.pop(1)\n", "print('After popping index 1 (a.pop(1)):', a)\n", "\n", "# Step 7: Delete the last index (Delete the value 109) using a.pop(-1)\n", "a.pop(-1)\n", "print('After popping the last index (a.pop(-1)):', a)\n", "\n", "# Step 8: Delete the last index (Delete the value 108) using a.pop() and store it in variable a_pop\n", "a_pop = a.pop()\n", "\n", "print('After popping the last index and storing it in b (a_pop = a.pop()):', a, '( a_pop =', a_pop,')')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Challenge\n", "# Remove all elements of the specified value in the list" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "scrolled": true }, "outputs": [], "source": [ "# Clear a List and Delete a List\n", "\n", "# Step 1: Create a list\n", "a = [101, 102, 103, 104, 105]\n", "print('Original list (a):', a)\n", "\n", "# Step 2: Clear all elements in the list (a becomes an empty list)\n", "a.clear()\n", "print('After clearing the list (a.clear()):', a)\n", "\n", "# Step 3: Delete the list 'a' itself\n", "del a\n", "\n", "# Step 4: Check if 'a' exists in the local namespace\n", "if 'a' in locals():\n", " print(\"'a' still exists in the local namespace.\")\n", "else:\n", " print(\"'a' no longer exists in the local namespace.\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Loop a list\n", "\n", "# Step 1: Create a list of integers\n", "a = [101, 102, 103, 104, 105]\n", "print('a =', a)\n", "\n", "# Step 2: Loop through the elements of the list 'a' using the 'enumerate' function\n", "# 'enumerate' provides both the index ('i') and the element ('x') in each iteration\n", "for i, x in enumerate(a):\n", "# print('a[{}] = {}'.format(i, x))\n", " print(f'a[{i}] = {x}')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Sort a list\n", "\n", "# Step 1: Create a list of integers\n", "a = [101, 103, 102, 105, 104]\n", "\n", "# Step 2: Display the original list\n", "print('Original list (a):', a)\n", "\n", "# Step 3: Sort the list in ascending order\n", "a.sort()\n", "print('Sorted in ascending order:', a)\n", "\n", "# Step 4: Sort the list in descending order\n", "a.sort(reverse=True)\n", "print('Sorted in descending order:', a)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Convert the list to uppercase\n", "\n", "# Step 1: Create a list of strings\n", "a = ['Pineapple', 'Banana', 'Orange', 'Pumpkin', 'Onion']\n", "\n", "# Step 2: Display the original list\n", "print('Original list (a):', a)\n", "\n", "# Step 3: Convert each element in the list to uppercase using a for loop\n", "for i in range(len(a)):\n", " a[i] = a[i].upper()\n", "\n", "# Step 4: Display the modified list\n", "print('Uppercase list (a):', a)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Convert the list to lowercase\n", "\n", "# Step 1: Create a list of strings\n", "a = ['Pineapple', 'Banana', 'Orange', 'Pumpkin', 'Onion']\n", "\n", "# Step 2: Display the original list\n", "print('Original list (a):', a)\n", "\n", "# Step 3: Convert each element in the list to lowercase using a for loop\n", "for i in range(len(a)):\n", " a[i] = a[i].lower()\n", "\n", "# Step 4: Display the modified list in lowercase\n", "print('Lowercase list (a):', a)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Sort a list (String)\n", "\n", "# Step 1: Create a list of strings\n", "a = ['Pineapple', 'Banana', 'Orange', 'Pumpkin', 'onion']\n", "\n", "# Step 2: Display the original list\n", "print('a =', a)\n", "\n", "# Step 3: Sort a list (case sensitive) (Notice 'onion' and 'Orange')\n", "# ASCII A..Za..z\n", "a.sort()\n", "print('a.sort() →', a)\n", "\n", "# Step 4: Sort a list (case insensitive) (Notice 'onion' and 'Orange')\n", "a.sort(key=str.lower)\n", "print('a.sort(key=str.lower) →', a)\n", "\n", "# Step 5: Sort a list in descending order (case insensitive) (Notice 'onion' and 'Orange')\n", "a.sort(key=str.lower, reverse=True)\n", "print('a.sort(key=str.lower, reverse=True) →', a)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Reverse the order of a list (No sorting!)\n", "\n", "# Step 1: Create a list of strings\n", "a = ['Pineapple', 'Banana', 'Orange', 'Pumpkin', 'onion']\n", "\n", "# Step 2: Display the original list\n", "print('a =', a)\n", "\n", "# Step 3: Reverse the order of the list\n", "a.reverse()\n", "print('a.reverse() →', a)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Copy a list\n", "\n", "# Step 1: Create a list 'a'\n", "a = [1, 2, 3, 4, 5]\n", "print('a =', a)\n", "\n", "# Step 2: Copy 'a' to 'b' by values (Changing 'a' does not change 'b')\n", "# b = a[:] # Python 2\n", "# b = list(a) # Python 3\n", "b = a.copy() # Python 3\n", "print('b = a.copy() →', b)\n", "\n", "# Step 3: Copy 'a' to 'c' by pointer (Changing 'a' also changes 'c')\n", "c = a # Python 3\n", "print('c = a →', a)\n", "\n", "# Step 4: Change the value of the first element of 'a'\n", "a[0] = 999\n", "print('a[0]=999 → 999')\n", "print('a =', a) # 'a' and 'c' are the same list\n", "print('b =', b) # 'b' is a different list\n", "print('c =', c) # 'a' and 'c' are the same list" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Join two lists\n", "\n", "# Step 1: Create two lists 'a' and 'b'\n", "a = [101, 102, 103, 104, 105]\n", "b = [201, 202, 203, 204]\n", "print('a =', a)\n", "print('b =', b)\n", "\n", "# Step 2: Join 'a' with 'b' into 'c'\n", "c = a + b\n", "print('c = a+b →', c)\n", "\n", "# Step 3: Join 'a' with 'b' (append 'a' with each element of 'b')\n", "a.extend(b)\n", "print('a.extend(b) →', a)\n", "\n", "# Step 4: Join 'a' with the whole 'b' as a new element of 'c'\n", "c = a.copy()\n", "print('c = a.copy() →', c)\n", "c.append(b)\n", "print('c.append(b) →', c)\n", "\n", "# Step 5: Double the list 'c'\n", "d = c * 2\n", "print('d = c*2 →', d)\n", "\n", "# Step 6: Duplicate 'c' by concatenating it with itself\n", "e = c\n", "e = e + e\n", "print('e = e+e →', e)\n", "\n", "# Step 7: Duplicate 'c' using the *= operator\n", "e = c\n", "e *= 2\n", "print('e *= 2 →', e)\n", "\n", "# Step 8: Triple the list 'd'\n", "d *= 3\n", "print('d *= 3 →', d)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# DATA TYPE - LIST [Square Bracket] - STRING" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Tokenize terms - Extract words from a string into a list\n", "\n", "# Step 1: Define a string 'a'\n", "a = 'You are the salt of the earth and the light of the world!'\n", "print('a =', a)\n", "\n", "# Step 2: Extract words from 'a' by splitting it using whitespace\n", "b = a.split()\n", "print('b = a.split() →', b) # Tokens\n", "print(\"'earth' in b →\", 'earth' in b)\n", "print('type(a) →', type(a))\n", "print('type(b) →', type(b))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Tokenize terms - Extract words from a string into a list by a specific keyword\n", "\n", "# Step 1: Define a CSV-like string 'a'\n", "a = '430359,Piyabute,Fuangkhon,Full-time Lecturer,Digital Business Management,School of Management'\n", "print('a =', a)\n", "\n", "# Step 2: Extract words by ','\n", "b = a.split(',') # Tokens (whitespaces are included)\n", "print('a.split(',') →', b)\n", "\n", "# Step 3: Extract words by ' , ' (whitespaces do matter!)\n", "b = a.split(' , ')\n", "print(\"a.split(' , ') →\", b) # Tokens" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Split a string into a list and join the list elements (Replace , with |)\n", "\n", "# Step 1: Define a CSV-like string 'a'\n", "a = '430359,Piyabute,Fuangkhon,Full-time Lecturer,Digital Business Management,School of Management'\n", "print('a =', a)\n", "\n", "# Step 2: Split the string into a list using ','\n", "b = a.split(',')\n", "print(\"a.split(',') →\", b) # Tokens\n", "\n", "# Step 3: Join the list elements, separated by '|'\n", "c = '|'.join(b)\n", "print(\"'|'.join(b) →\", c)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Print a specific element in the list\n", "\n", "# Step 1: Define a list 'a'\n", "a = [9, 1, 8, 2, 7, 3, 6, 4, 5]\n", "print('a =', a)\n", "\n", "# Step 2: Print the first element in the list\n", "print('a[0] →', a[0]) # the first element\n", "\n", "# Step 3: Print the last element in the list\n", "a = ['Physics', 'Chemistry', 91, 100] # Mixed strings with numbers\n", "print('a =', a)\n", "print('a[0] →', a[0]) # the last element\n", "print('a[-1] →', a[-1]) # the last element" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Print consecutive elements in the list (The first element is at index 0, not 1)\n", "\n", "# Step 1: Define a list 'a'\n", "a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n", "print('a =', a)\n", "\n", "# Step 2: Print elements starting from index 1 to the end\n", "print('a[1:] →', a[1:])\n", "\n", "# Step 3: Print elements starting from index 2 to the end\n", "print('a[2:] →', a[2:])\n", "\n", "# Step 4: Print elements starting from index 1 and stopping before index 3\n", "print('a[1:3] →', a[1:3])\n", "\n", "# Step 5: Print elements starting from index 0 and ending at the second last index\n", "print('a[:-1] →', a[:-1])\n", "\n", "# Step 6: Print elements starting from index 0 and ending at the third last index\n", "print('a[:-2] →', a[:-2])\n", "\n", "# Step 7: Print elements starting from the last index to the end\n", "print('a[-1:] →', a[-1:])\n", "\n", "# Step 8: Print elements starting from the second last index to the end\n", "print('a[-2:] →', 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": [ "# Math on a list\n", "\n", "# Step 1: Define a list 'a'\n", "a = [101, 102, 103, 104, 105, 105]\n", "print('a =', a)\n", "\n", "# Step 2: Calculate the summation of all elements in the list using sum()\n", "print('sum(a) →', sum(a))\n", "\n", "# Step 3: Find the minimum value in the list using min()\n", "print('min(a) →', min(a))\n", "\n", "# Step 4: Find the maximum value in the list using max()\n", "print('max(a) →', max(a))\n", "\n", "# Step 5: Get the number of elements in the list using len()\n", "print('len(a) →', len(a))\n", "\n", "# Step 6: Count the number of occurrences of a specific value (e.g., count 105)\n", "print('a.count(105) →', a.count(105))" ] }, { "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": [ "# Math on a list\n", "\n", "# Step 1: Import the necessary libraries\n", "import numpy\n", "from scipy import stats\n", "\n", "# Step 2: Define a list 'a'\n", "a = [101, 102, 103, 104, 105, 105, 105]\n", "print('a =', a)\n", "\n", "# Step 3: Calculate the mean of the list using numpy.mean()\n", "print('numpy.mean(a) →', numpy.mean(a))\n", "\n", "# Step 4: Calculate the median of the list using numpy.median()\n", "print('numpy.median(a) →', numpy.median(a))\n", "\n", "# Step 5: Calculate the mode of the list using stats.mode()\n", "mode_result = stats.mode(a)\n", "print('stats.mode(a) →', mode_result)\n", "print('stats.mode(a)[0] →', mode_result[0]) # Mode value(s)\n", "print('stats.mode(a)[1] →', mode_result[1]) # Number of occurrences" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# List Methods\n", "\n", "# append() Adds an element at the end of the list\n", "# clear() Removes all the elements from the list\n", "# copy() Returns a copy of the list\n", "# count() Returns the number of elements with the specified value\n", "# extend() Add the elements of a list (or any iterable), to the end of the current list\n", "# index() Returns the index of the first element with the specified value\n", "# insert() Adds an element at the specified position\n", "# pop() Removes the element at the specified position\n", "# remove() Removes the item with the specified value\n", "# reverse() Reverses the order of the list\n", "# sort() Sorts the list" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# List Exercise\n", "# 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": [ "# https://www.w3schools.com/python/python_tuples.asp\n", "\n", "# Tuple is unchangeable or immutable. To change a tuple, convert a tulple to a list and convert it back to a tuple" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Create a tuple and read a specific element\n", "\n", "# Step 1: Create a tuple 'a'\n", "a = (101, 102, 103, 104, 105)\n", "\n", "# Step 2: Print the tuple\n", "print('a =', a)\n", "\n", "# Step 3: Read the second element of the tuple (The first element is at index 0, not 1)\n", "print('a[1] →', a[1])\n", "\n", "# Step 4: Print the type of the variable 'a'\n", "print('type(a) →', type(a))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Assign values with different types to a tuple\n", "\n", "# Step 1: Create a tuple 'a' with values of different types\n", "a = (101, 'Hello', True)\n", "print('a =', a)\n", "\n", "# Step 2: Print the type of the variable 'a'\n", "print('type(a) →', type(a))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Find the index of a specific element\n", "\n", "# Step 1: Create a tuple 'a'\n", "a = (101, 102, 103, 104, 105)\n", "print('a =', a)\n", "\n", "# Step 2: Find the index of the element 103 (The first element is at index 0, not 1)\n", "print('a.index(103) →', a.index(103))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Find the index of a specific string element\n", "\n", "# Step 1: Create a tuple 'a'\n", "a = ('A1', 'B1', 'C1', 'D1', 'E1')\n", "print('a =', a)\n", "\n", "# Step 2: Find the index of the element 'D1' (The first element is at index 0, not 1)\n", "print(\"a.index('D1') →\", a.index('D1'))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Find if a specific value is in a tuple\n", "\n", "# Step 1: Create a tuple 'a'\n", "a = (101, 102, 103, 104, 105)\n", "print('a =', a)\n", "\n", "# Step 2: Check if the value 103 is in the tuple 'a'\n", "print('103 in a =', 103 in a)\n", "\n", "# Step 3: Check if the value 106 is in the tuple 'a'\n", "print('106 in a =', 106 in a)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Change the value of an element of a tuple\n", "# CANNOT change the values of an element of a tuple. Alternatively, convert a tuple into a list and convert it back to a tuple.\n", "\n", "# Step 1: Create a tuple 'a'\n", "a = (101, 102, 103, 104, 105)\n", "print('a =', a)\n", "\n", "# Step 2: Convert the tuple 'a' to a list 'b'\n", "b = list(a)\n", "print('list(a) →', b)\n", "\n", "# Step 3: Change the second element of the list 'b' to 999\n", "print('b =', b)\n", "b[1] = 999\n", "print('b[1]=999 →', b)\n", "\n", "# Step 4: Convert the list 'b' back to a tuple 'a'\n", "a = tuple(b)\n", "print('tuple(b) →', a)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Add a new element to a tuple\n", "# CANNOT add a new element to a tuple. Alternatively, convert a tuple into a list and convert it back to a tuple.\n", "\n", "# Step 1: Create a tuple 'a'\n", "a = (101, 102, 103, 104, 105)\n", "print('a =', a)\n", "\n", "# Step 2: Convert the tuple 'a' to a list 'b'\n", "b = list(a)\n", "print('list(a) →', b)\n", "\n", "# Step 3: Append the list 'b' with the value 999\n", "print('b =', b)\n", "b.append(999)\n", "print('b.append(999) →', b)\n", "\n", "# Step 4: Convert the list 'b' back to a tuple 'a'\n", "a = tuple(b)\n", "print('tuple(b) →', a)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "scrolled": true }, "outputs": [], "source": [ "# Insert a tuple with a new element\n", "# CANNOT insert a tuple with a new element. Alternatively, convert a tuple into a list and convert it back to a tuple.\n", "\n", "# Step 1: Create a tuple 'a'\n", "a = (101, 102, 103, 104, 105)\n", "print('a =', a)\n", "\n", "# Step 2: Convert the tuple 'a' to a list 'b'\n", "b = list(a)\n", "print('list(a) →', b)\n", "\n", "# Step 3: Insert the value 888 at the third index\n", "print('b =', b)\n", "b.insert(2, 888)\n", "print('b.insert(2,888) →', b)\n", "\n", "# Step 4: Insert the value 999 at the second last position\n", "b.insert(-1, 999)\n", "print('b.insert(-1,999) →', b)\n", "\n", "# Step 5: Convert the list 'b' back to a tuple 'a'\n", "a = tuple(b)\n", "print('tuple(b) →', a)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Delete a specific element from a tuple\n", "# CANNOT delete a specific element from a tuple. Alternatively, convert a tuple into a list and convert it back to a tuple.\n", "\n", "# Step 1: Create a tuple 'a'\n", "a = (101, 102, 103, 104, 105, 106, 107, 108, 109, 110)\n", "print('a =', a)\n", "\n", "# Step 2: Convert the tuple 'a' to a list 'b'\n", "b = list(a)\n", "print('list(a) →', b)\n", "\n", "# Step 3: Delete the element 103 from the list 'b'\n", "print('b =', b)\n", "b.remove(103)\n", "print('b.remove(103) →', b)\n", "\n", "# Step 4: Delete the element at index 1 (Remove 102)\n", "print('b =', b)\n", "del b[1]\n", "print('del b[1] →', b)\n", "\n", "# Step 5: Delete the last element (Remove 110)\n", "print('b =', b)\n", "del b[-1]\n", "print('del b[-1] →', b)\n", "\n", "# Step 6: Delete the element at index 1 again (Remove 104)\n", "print('b =', b)\n", "b.pop(1)\n", "print('b.pop(1) →', b)\n", "\n", "# Step 7: Delete the last element again (Remove 109)\n", "print('b =', b)\n", "b.pop(-1)\n", "print('b.pop(-1) →', b)\n", "\n", "# Step 8: Convert the list 'b' back to a tuple 'a'\n", "a = tuple(b)\n", "print('tuple(b) →', a)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Clear a tuple and delete a tuple\n", "# Cannot clear a tuple, but delete a tuple\n", "\n", "# Step 1: Create a tuple 'a'\n", "a = (101, 102, 103, 104, 105)\n", "print('a =', a)\n", "\n", "# Step 2: Delete the tuple 'a'\n", "del a\n", "\n", "# Step 3: Check if 'a' exists in the local or global namespace\n", "if 'a' in locals(): # You can also use 'globals()' to check the global namespace\n", " print(\"'a' does exist\")\n", "else:\n", " print(\"'a' does not exist\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Unpack a tuple into variables\n", "\n", "# Step 1: Create a tuple 'a'\n", "a = (101, 102, 103, 104, 105)\n", "print('a =', a)\n", "\n", "# Step 2: Unpack the tuple 'a' into 5 variables\n", "(a1, a2, a3, a4, a5) = a\n", "print('(a1, a2, a3, a4, a5) = a')\n", "print('a1 =', a1)\n", "print('a2 =', a2)\n", "print('a3 =', a3)\n", "print('a4 =', a4)\n", "print('a5 =', a5)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Loop a tuple\n", "\n", "# Step 1: Create a tuple 'a'\n", "a = (101, 102, 103, 104, 105)\n", "print('a =', a)\n", "\n", "# Step 2: Loop through the elements of the tuple 'a' using 'enumerate'\n", "# 'enumerate' provides both the index ('i') and the element ('x') in each iteration\n", "for i, x in enumerate(a):\n", " print('a[{}] = {}'.format(i, x))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Sort a tuple\n", "# CANNOT sort a tuple. Alternatively, convert a tuple into a list and convert it back to a tuple.\n", "\n", "# Step 1: Create a tuple 'a'\n", "a = (101, 103, 102, 105, 104)\n", "print('a =', a)\n", "\n", "# Step 2: Convert the tuple 'a' to a list 'b'\n", "b = list(a)\n", "print('list(a) →', b)\n", "\n", "# Step 3: Sort the list 'b' in ascending order\n", "b.sort()\n", "print('b.sort() →', b)\n", "\n", "# Step 4: Sort the list 'b' in descending order\n", "b.sort(reverse=True) # 'True' is case-sensitive\n", "print('b.sort(reverse=True) →', b)\n", "\n", "# Step 5: Convert the list 'b' back to a tuple 'a'\n", "a = tuple(b)\n", "print('tuple(b) →', a)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Sort a tuple (String)\n", "\n", "# Step 1: Create a tuple 'a' with strings\n", "a = ('Pineapple', 'Banana', 'Orange', 'Pumpkin', 'onion')\n", "print('a =', a)\n", "\n", "# Step 2: Convert the tuple 'a' to a list 'b'\n", "b = list(a)\n", "print('list(a) →', b)\n", "\n", "# Step 3: Sort the list 'b' in ascending order (case-sensitive)\n", "b.sort()\n", "print('b.sort() →', b)\n", "\n", "# Step 4: Sort the list 'b' in ascending order (case-insensitive)\n", "b.sort(key=str.lower)\n", "print('b.sort(key=str.lower) →', b)\n", "\n", "# Step 5: Sort the list 'b' in descending order (case-insensitive)\n", "b.sort(key=str.lower, reverse=True)\n", "print('b.sort(key=str.lower,reverse=True) →', b)\n", "\n", "# Step 6: Convert the list 'b' back to a tuple 'a'\n", "a = tuple(b)\n", "print('tuple(b) →', a)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Convert the tuple to uppercase\n", "# CANNOT convert the tuple to uppercase. Alternatively, convert a tuple into a list and convert it back to a tuple.\n", "\n", "# Step 1: Create a tuple 'a' with strings\n", "a = ('Pineapple', 'Banana', 'Orange', 'Pumpkin', 'onion')\n", "print('a =', a)\n", "\n", "# Step 2: Convert the tuple 'a' to a list 'b'\n", "b = list(a)\n", "print('list(a) →', b)\n", "\n", "# Step 3: Convert each element in the list 'b' to uppercase using a for loop\n", "for i in range(len(b)):\n", " b[i] = b[i].upper()\n", "print('b[i].upper() →', b)\n", "\n", "# Step 4: Convert the list 'b' back to a tuple 'a'\n", "a = tuple(b)\n", "print('tuple(b) →', a)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Convert the tuple to lowercase\n", "# CANNOT convert the tuple to lowercase. Alternatively, convert a tuple into a list and convert it back to a tuple.\n", "\n", "# Step 1: Create a tuple 'a' with strings\n", "a = ('Pineapple', 'Banana', 'Orange', 'Pumpkin', 'onion')\n", "print('a =', a)\n", "\n", "# Step 2: Convert the tuple 'a' to a list 'b'\n", "b = list(a)\n", "print('list(a) →', b)\n", "\n", "# Step 3: Convert each element in the list 'b' to lowercase using a for loop\n", "for i in range(len(b)):\n", " b[i] = b[i].lower()\n", "print('b[i].lower() →', b)\n", "\n", "# Step 4: Convert the list 'b' back to a tuple 'a'\n", "a = tuple(b)\n", "print('tuple(b) →', a)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Reverse the order of a tuple (No sorting!)\n", "# CANNOT reverse the order of a tuple. Alternatively, convert a tuple into a list and convert it back to a tuple.\n", "\n", "# Step 1: Create a tuple 'a' with strings\n", "a = ('Pineapple', 'Banana', 'Orange', 'Pumpkin', 'onion')\n", "print('a =', a)\n", "\n", "# Step 2: Convert the tuple 'a' to a list 'b'\n", "b = list(a)\n", "print('list(a) →', b)\n", "\n", "# Step 3: Reverse the order of the list 'b'\n", "b.reverse()\n", "print('b.reverse() →', b)\n", "\n", "# Step 4: Convert the list 'b' back to a tuple 'a'\n", "a = tuple(b)\n", "print('tuple(b) →', a)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Copy a tuple\n", "\n", "# Step 1: Create a tuple 'a'\n", "a = (101, 102, 103, 104, 105)\n", "print('a =', a)\n", "\n", "# Step 2: Copy the reference of 'a' to 'b' (both 'a' and 'b' point to the same tuple)\n", "b = a\n", "print('b =', b)\n", "\n", "# Step 3: Change the value of the tuple 'a' by converting it to a list, modifying it, and converting it back to a tuple\n", "a = list(a)\n", "a[1] = 200\n", "a = tuple(a)\n", "\n", "# Step 4: Confirm that 'a' and 'b' are separate tuples\n", "print('a =', a)\n", "print('b =', b)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Join two tuples\n", "\n", "# Step 1: Create two tuples 'a' and 'b'\n", "a = (101, 102, 103, 104, 105)\n", "b = (201, 202, 203, 204)\n", "print('a =', a)\n", "print('b =', b)\n", "\n", "# Step 2: Join tuple 'a' with tuple 'b' to create a new tuple 'c'\n", "c = a + b\n", "print('c =', c)\n", "\n", "# Step 3: Double the tuple 'c' (repeat its elements)\n", "d = c * 2\n", "print('d =', d)\n", "\n", "# Step 4: Triple the tuple 'd' (repeat its elements)\n", "d *= 3\n", "print('d =', d)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# DATA TYPE - TUPLE (Parenthesis) - MATH" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Math on a tuple\n", "\n", "# Step 1: Create a tuple 'a' with integer values\n", "a = (101, 102, 103, 104, 105, 105)\n", "print('a =', a)\n", "\n", "# Step 2: Calculate the summation of elements in the tuple using 'sum()'\n", "print('sum(a) →', sum(a))\n", "\n", "# Step 3: Find the minimum value in the tuple using 'min()'\n", "print('min(a) →', min(a))\n", "\n", "# Step 4: Find the maximum value in the tuple using 'max()'\n", "print('max(a) →', max(a))\n", "\n", "# Step 5: Determine the number of elements in the tuple using 'len()'\n", "print('len(a) →', len(a))\n", "\n", "# Step 6: Count the number of occurrences of the term '105' in the tuple\n", "print('a.count(105) →', a.count(105))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Math on a tuple\n", "\n", "# Step 1: Import the NumPy library\n", "import numpy\n", "\n", "# Create a tuple 'a' with integer values\n", "a = (101, 102, 103, 104, 105, 105, 105)\n", "print('a =', a)\n", "\n", "# Step 2: Calculate the mean of elements in the tuple using 'numpy.mean()'\n", "print('numpy.mean(a) →', numpy.mean(a))\n", "\n", "# Step 3: Calculate the median of elements in the tuple using 'numpy.median()'\n", "print('numpy.median(a) →', numpy.median(a))\n", "\n", "# Step 4: Import the stats module from SciPy library\n", "from scipy import stats\n", "\n", "# Step 5: Calculate the mode of elements in the tuple using 'stats.mode()'\n", "print('stats.mode(a) →', stats.mode(a))\n", "\n", "# Step 6: Access the maximum occurrence value from the mode result\n", "print('stats.mode(a)[0] →', stats.mode(a)[0]) # Max occurrence\n", "\n", "# Step 7: Access the number of occurrences of the mode value\n", "print('stats.mode(a)[1] →', stats.mode(a)[1]) # No. of occurrences" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Tuple Methods\n", "\n", "# count() Returns the number of times a specified value occurs in a tuple\n", "# index() Searches the tuple for a specified value and returns the position of where it was found" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Tuple Exercise\n", "# 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": [ "# https://www.w3schools.com/python/python_dictionaries.asp\n", "\n", "# A dictionary is a list of keys. Each key is associated with a value.\n", "# key:value is called element.\n", "# Each key is separated from its value by a colon (:).\n", "# The elements are separated by commas, and the whole thing is enclosed in curly braces." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Create a dictionary and read a specific element\n", "\n", "# Step 1: Create a dictionary 'a' with various key-value pairs\n", "a = {'sid': 6010001, 'fname': 'Piyabute', 'lname': 'Fuangkhon', 'phone': '027232236', 'active': True}\n", "\n", "# Step 2: Print the entire dictionary 'a'\n", "print('a =', a)\n", "\n", "# Step 3: Print the dictionary as a list of key-value pairs using 'items()'\n", "print('a.items() =', a.items())\n", "\n", "# Step 4: Print the dictionary with one row per attribute\n", "for key, value in a.items():\n", " print(\"key,':',value →\", key, ':', value)\n", "\n", "# Step 5: Print the first name of a student by accessing the 'fname' key\n", "print(\"a['fname'] →\", a['fname'])\n", "\n", "# Step 6: Print the phone number of a student by accessing the 'phone' key\n", "print(\"a['phone'] →\", a['phone'])\n", "\n", "# Step 7: Print the type of the variable 'a'\n", "print('type(a) →', type(a))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Create a dictionary from two lists\n", "\n", "# Step 1: Create two lists 'a' and 'b' with keys and values respectively for the first dictionary\n", "a = ['sid', 'fname', 'lname', 'phone', 'active']\n", "b = ['6010001', 'Piyabute', 'Fuangkhon', '027232236', True]\n", "\n", "# Create two lists 'a' and 'c' with keys and values respectively for the second dictionary\n", "c = ['6010002', 'Robert', 'John', '027232237', False]\n", "\n", "print('a =', a)\n", "print('b =', b)\n", "print('c =', c)\n", "\n", "# Step 2: Create the first dictionary 'd' by zipping 'a' and 'b'\n", "d = dict(zip(a, b))\n", "print('dict(zip(a,b)) →', d)\n", "\n", "# Step 3: Create the second dictionary 'e' by zipping 'a' and 'c'\n", "e = dict(zip(a, c))\n", "print('dict(zip(a,c)) →', e)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Create a dictionary from tuples\n", "\n", "# Step 1: Create tuples 'a' through 'e', each containing a key-value pair\n", "a = ('sid', 6010001)\n", "b = ('fname', 'Piyabute')\n", "c = ('lname', 'Fuangkhon')\n", "d = ('phone', '027232236')\n", "e = ('active', True)\n", "\n", "print('a =', a)\n", "print('b =', b)\n", "print('c =', c)\n", "print('d =', d)\n", "print('e =', e)\n", "\n", "# Step 2: Create a dictionary 'f' by passing a list of tuples\n", "f = dict([a, b, c, d, e])\n", "print('dict([a,b,c,d,e]) →', f)\n", "print('type(f) =', type(f))\n", "\n", "# Step 3: Create a list 'g' containing the same tuples\n", "g = [a, b, c, d, e]\n", "print('[a,b,c,d,e] =', g)\n", "print('type(g) =', type(g))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Create a dictionary - dict → tuple → dict # RECHECK!\n", "\n", "# Step 1: Create a dictionary 'a' directly\n", "a = {'sid': 6010001, 'fname': 'Piyabute', 'lname': 'Fuangkhon', 'phone': '027232236', 'active': True}\n", "print('a =', a)\n", "\n", "# Step 2: Create a dictionary 'b' using the 'dict' constructor and passing another dictionary as an argument\n", "b = dict({'sid': 6010001, 'fname': 'Piyabute', 'lname': 'Fuangkhon', 'phone': '027232236', 'active': True})\n", "print('b =', b)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Create a dictionary with multiple rows (records)\n", "\n", "# Step 1: Create a dictionary 'a' with multiple records\n", "a = {}\n", "\n", "# Add the first record to 'a'\n", "a[0] = {'sid': 6010001, 'fname': 'Piyabute', 'lname': 'Fuangkhon', 'phone': '027232236', 'active': True}\n", "\n", "# Add the second record to 'a'\n", "a[1] = {'sid': 6010002, 'fname': 'Robert', 'lname': 'Downey', 'phone': '023004543', 'active': True}\n", "\n", "# Add the third record to 'a'\n", "a[2] = {'sid': 6010003, 'fname': 'Elon', 'lname': 'Musk', 'phone': '028888888', 'active': False}\n", "\n", "# Step 2: Print the first record in 'a'\n", "print('a[0] =', a[0], '\\n') # \\n is a new line escape sequence\n", "\n", "# Print the second record in 'a'\n", "print('a[1] =', a[1], '\\n') # \\n is a new line escape sequence\n", "\n", "# Print the third record in 'a'\n", "print('a[2] =', a[2], '\\n') # \\n is a new line escape sequence\n", "\n", "# Step 3: Print the entire 'a' dictionary\n", "print('a =', a, '\\n') # \\n is a new line escape sequence\n", "\n", "# Step 4: Print the second row of a dictionary (record)\n", "print('a[1] =', a[1])\n", "print(\"'fname' =\", a[1]['fname'])" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# List all the keys (attributes) in a dictionary\n", "\n", "# Step 1: Create a dictionary 'a'\n", "a = {'sid': 6010001, 'fname': 'Piyabute', 'lname': 'Fuangkhon', 'phone': '027232236', 'active': True}\n", "\n", "# Step 2: List all the keys in the dictionary 'a'\n", "print('a.keys() =', a.keys())\n", "\n", "# Step 3: Iterate through the keys and print them\n", "for x in a.keys():\n", " print(x)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# List all the values in a dictionary\n", "\n", "# Step 1: Create a dictionary 'a'\n", "a = {'sid': 6010001, 'fname': 'Piyabute', 'lname': 'Fuangkhon', 'phone': '027232236', 'active': True}\n", "\n", "# Step 2: List all the values in the dictionary 'a'\n", "print('a.values() =', a.values())\n", "\n", "# Step 3: Iterate through the values and print them\n", "for x in a.values():\n", " print(x)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# List all the elements in a dictionary\n", "\n", "# Step 1: Create a dictionary 'a'\n", "a = {'sid': 6010001, 'fname': 'Piyabute', 'lname': 'Fuangkhon', 'phone': '027232236', 'active': True}\n", "\n", "# Step 2: Iterate through the key-value pairs and print them\n", "for x, y in a.items():\n", " print(x, y)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Check if a key and a value do exist\n", "\n", "# Step 1: Create a dictionary 'a'\n", "a = {'sid': 6010001, 'fname': 'Piyabute', 'lname': 'Fuangkhon', 'phone': '027232236', 'active': True}\n", "\n", "# Step 2: Check if 'fname' key exists\n", "findkey = 'fname'\n", "if findkey in a.keys():\n", " print(\"'\", findkey, \"' in a.keys() → Yes, '\", findkey, \"' is one of the keys in this dictionary.\", sep=\"\")\n", "else:\n", " print(\"'\", findkey, \"' in a.keys() → No, '\", findkey, \"' is NOT one of the keys in this dictionary.\", sep=\"\")\n", "\n", "# Step 3: Check if 'Piyabute' value exists\n", "findvalue = 'Piyabute'\n", "if findvalue in a.values():\n", " print(\"'\", findvalue, \"' in a.values() → Yes, '\", findvalue, \"' is one of the values in this dictionary.\", sep=\"\")\n", "else:\n", " print(\"'\", findvalue, \"' in a.values() → No, '\", findvalue, \"' is NOT one of the values in this dictionary.\", sep=\"\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Find the index of a specific string element" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Change the value of an element of a dictionary\n", "\n", "# Step 1: Create a dictionary 'a'\n", "a = {'sid': 6010001, 'fname': 'Piyabute', 'lname': 'Fuangkhon', 'phone': '027232236', 'active': True}\n", "print('a =', a)\n", "\n", "# Step 2: Change the value of the 'active' key to 'False'\n", "a['active'] = False\n", "print(\"\\na['active'] = False\\n→\", a)\n", "\n", "# Step 3: Change the value of the 'phone' key to '023004543'\n", "a.update({'phone': '023004543'})\n", "print(\"\\na.update({'phone':'023004543'})\\n→\", a)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Add a new element to a dictionary\n", "\n", "# Step 1: Create a dictionary 'a'\n", "a = {'sid': 6010001, 'fname': 'Piyabute', 'lname': 'Fuangkhon', 'phone': '027232236', 'active': True}\n", "print('a =', a)\n", "\n", "# Step 2: Add a new element to the dictionary - 'address':'88 Moo 8 Bangna-Trad K.M.26'\n", "a['address'] = '88 Moo 8 Bangna-Trad K.M.26'\n", "print(\"\\na['address'] = '88 Moo 8 Bangna-Trad K.M.26'\\n→\", a)\n", "\n", "# Step 3: Add a new element to the dictionary - 'district':'Hua Mak'\n", "a.update({'district': 'Hua Mak'})\n", "print(\"\\na.update({'district': 'Hua Mak'})\\n→\", a)\n", "\n", "# Step 4: Update an existing element in the dictionary - 'district':'Bang Sao Thong'\n", "a.update({'district': 'Bang Sao Thong'})\n", "print(\"\\na.update({'district': 'Bang Sao Thong'})\\n→\", a)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Delete an element in a dictionary\n", "\n", "# Step 1: Create a dictionary 'a'\n", "a = {'sid': 6010001, 'fname': 'Piyabute', 'lname': 'Fuangkhon', 'phone': '027232236', 'active': True}\n", "print('a =', a)\n", "\n", "# Step 2: Delete a specific element in the dictionary - delete 'phone'\n", "del a['phone']\n", "print(\"\\ndel a['phone']\\n→\", a)\n", "\n", "# Step 3: Delete the last element in the dictionary - delete 'active'\n", "b = a.popitem()\n", "print(\"\\na.popitem()\\n→\", a)\n", "print('b =', b)\n", "print('type(b) =', type(b))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Clear a dictionary and delete a dictionary\n", "\n", "# Step 1: Create a dictionary 'a'\n", "a = {'sid': 6010001, 'fname': 'Piyabute', 'lname': 'Fuangkhon', 'phone': '027232236', 'active': True}\n", "print('a =', a)\n", "\n", "# Step 2: Clear all elements in the dictionary\n", "a.clear()\n", "print(\"\\na.clear()\\n→\", a)\n", "\n", "# Step 3: Delete the dictionary\n", "del a\n", "\n", "if 'a' in locals():\n", " print(\"'a' does exist\")\n", "else:\n", " print(\"'a' does not exist\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Loop a dictionary\n", "\n", "# Step 1: Define a dictionary named 'a' with some sample data.\n", "a = {'sid': 6010001, 'fname': 'Piyabute', 'lname': 'Fuangkhon', 'phone': '027232236', 'active': True}\n", "\n", "# Step 2: Print all elements in the dictionary.\n", "print('Print all elements')\n", "for i, (key, value) in enumerate(a.items()):\n", " print(i, 'key of a =', key, ', value of a =', value)\n", "\n", "# Step 3: Print all keys in the dictionary.\n", "print()\n", "print('Print all keys')\n", "for i, key in enumerate(a):\n", " print(i, 'key of a =', key)\n", "\n", "# Step 4: Print all keys using .keys() method.\n", "print()\n", "print('Print all keys using .keys()')\n", "for i, key in enumerate(a.keys()):\n", " print(i, 'key of a =', key)\n", "\n", "# Step 5: Print all values using keys as indexes.\n", "print()\n", "print('Print all values using key as index')\n", "for i, key in enumerate(a):\n", " print(i, 'value of a =', a[key])\n", "\n", "# Step 6: Print all values using .values() method.\n", "print()\n", "print('Print all values using .values()')\n", "for i, value in enumerate(a.values()):\n", " print(i, 'value of a =', value)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Loop a list of dictionary\n", "\n", "# Step 1: Define a list of dictionaries 'a' containing sample data.\n", "a0 = {'sid': 6010001, 'fname': 'Piyabute'}\n", "a1 = {'sid': 6010002, 'fname': 'Robert'}\n", "a2 = {'sid': 6010003, 'fname': 'Elon'}\n", "\n", "a = [a0, a1, a2]\n", "\n", "# Step 2: Print individual dictionary elements.\n", "print('a[0] =', a[0])\n", "print('a[1] =', a[1])\n", "print('a[2] =', a[2])\n", "\n", "# Step 3: Check if 'fname' key exists in each dictionary.\n", "search_key = 'fname'\n", "for i, dictionary in enumerate(a):\n", " if search_key in dictionary:\n", " print(\"'\", search_key, \"' in a[\", i, \"] → Yes\", sep='')\n", " else:\n", " print(\"'\", search_key, \"' in a[\", i, \"] → No\", sep='')\n", "\n", "# Step 4: Check if 'Robert' value exists in each dictionary.\n", "search_value = 'Robert'\n", "for i, dictionary in enumerate(a):\n", " if search_value in dictionary.values():\n", " print(\"'\", search_value, \"' in a[\", i, \"] → Yes\", sep='')\n", " else:\n", " print(\"'\", search_value, \"' in a[\", i, \"] → No\", sep='')\n", "\n", "# Step 5: Check if 6010003 value exists in each dictionary.\n", "search_value = 6010003\n", "for i, dictionary in enumerate(a):\n", " if search_value in dictionary.values():\n", " print(\"'\", search_value, \"' in a[\", i, \"] → Yes\", sep='')\n", " else:\n", " print(\"'\", search_value, \"' in a[\", i, \"] → No\", sep='')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Sort a dictionary\n", "\n", "# Step 1: Define a dictionary 'a' with key-value pairs.\n", "a = {6010003: 'Elon', 6010002: 'Robert', 6010001: 'Piyabute'}\n", "\n", "# Step 2: Sort the dictionary by keys and print the result.\n", "sorted_by_keys = sorted(a.items(), key=lambda x: x[0]) # Sorting by keys (x[0])\n", "print('sorted(a.items(), key=lambda x: x[0]) →')\n", "for item in sorted_by_keys:\n", " print(item)\n", "\n", "# Step 3: Sort the dictionary by values and print the result.\n", "sorted_by_values = sorted(a.items(), key=lambda x: x[1]) # Sorting by values (x[1])\n", "print()\n", "print('sorted(a.items(), key=lambda x: x[1]) →')\n", "for item in sorted_by_values:\n", " print(item)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Sort a dictionary in a reverse order\n", "\n", "# Step 1: Define a dictionary 'a' with key-value pairs.\n", "a = {6010003: 'Elon', 6010002: 'Robert', 6010001: 'Piyabute'}\n", "\n", "# Step 2: Sort the dictionary by keys in reverse order and print the result.\n", "sorted_by_keys_reverse = sorted(a.items(), key=lambda x: x[0], reverse=True) # Sorting by keys in reverse order (x[0])\n", "print('sorted(a.items(), key=lambda x: x[0], reverse=True) →')\n", "for item in sorted_by_keys_reverse:\n", " print(item)\n", "\n", "# Step 3: Sort the dictionary by values in reverse order and print the result.\n", "sorted_by_values_reverse = sorted(a.items(), key=lambda x: x[1], reverse=True) # Sorting by values in reverse order (x[1])\n", "print()\n", "print('sorted(a.items(), key=lambda x: x[1], reverse=True) →')\n", "for item in sorted_by_values_reverse:\n", " print(item)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Sort a list of dictionary\n", "\n", "# Step 1: Define a list of dictionaries.\n", "list_of_dicts = [\n", " {'sid': 6010003, 'fname': 'Elon'},\n", " {'sid': 6010002, 'fname': 'Robert'},\n", " {'sid': 6010001, 'fname': 'Piyabute'}\n", "]\n", "\n", "# Step 2: Sort the list of dictionaries by a specific key, e.g., 'sid'.\n", "sorted_list = sorted(list_of_dicts, key=lambda x: x['sid'])\n", "\n", "# Step 3: Print the sorted list.\n", "for item in sorted_list:\n", " print(item)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Copy a dictionary\n", "\n", "# Step 1: Define a dictionary 'a'.\n", "a = {'sid': 6010001, 'fname': 'Piyabute', 'active': True}\n", "print('a =', a)\n", "\n", "# Step 2: Copy dictionary 'a' to 'b' by values.\n", "b = a.copy()\n", "print('b = a.copy() →', b)\n", "\n", "# Step 3: Modify dictionary 'b'.\n", "b.update({'active': False})\n", "print(\"b.update({'active': False}) →\", b)\n", "\n", "# Step 4: Print dictionary 'a' to confirm it remains unchanged.\n", "print('a =', a)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Create a nested dictionary\n", "\n", "# Step 1: Define a nested dictionary 'myfriend'.\n", "myfriend = {\n", " 6010001 : {\n", " \"name\" : \"Vasa\",\n", " \"year\" : 2000\n", " },\n", " 6010002 : {\n", " \"name\" : \"Pisal\",\n", " \"year\" : 2010\n", " },\n", " 6010003 : {\n", " \"name\" : \"Sumate\",\n", " \"year\" : 2021\n", " }\n", "}\n", "\n", "# Step 2: Loop through the keys of the outer dictionary.\n", "for k in myfriend:\n", " print('Key =', k)\n", "\n", "# Step 3: Loop through the values of the outer dictionary.\n", "for v in myfriend.values():\n", " print('Value =', v)\n", "\n", "# Step 4: Loop through both keys and values of the outer dictionary using items().\n", "for k, v in myfriend.items():\n", " print('Key =', k, '/ Value =', v)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Create a nested dictionary from another dictionaries\n", "\n", "# Step 1: Define three dictionaries.\n", "friend1 = {'name': 'Vasa', 'year': 2000}\n", "friend2 = {'name': 'Pisal', 'year': 2010}\n", "friend3 = {'name': 'Sumate', 'year': 2021}\n", "\n", "# Step 2: Create a nested dictionary 'myfriend' using the above dictionaries as values.\n", "myfriend = {6010001: friend1, 6010002: friend2, 6010003: friend3}\n", "\n", "# Step 3: Loop through the keys of the outer dictionary.\n", "for k in myfriend:\n", " print('Key =', k)\n", "\n", "# Step 4: Loop through the values of the outer dictionary.\n", "for v in myfriend.values():\n", " print('Value =', v)\n", "\n", "# Step 5: Loop through both keys and values of the outer dictionary using items().\n", "for k, v in myfriend.items():\n", " print('Key =', k, '/ Value =', v)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Dictionary Methods\n", "\n", "# clear() Removes all the elements from the dictionary\n", "# copy() Returns a copy of the dictionary\n", "# fromkeys() Returns a dictionary with the specified keys and value\n", "# get() Returns the value of the specified key\n", "# items() Returns a list containing a tuple for each key value pair\n", "# keys() Returns a list containing the dictionary's keys\n", "# pop() Removes the element with the specified key\n", "# popitem() Removes the last inserted key-value pair\n", "# setdefault() Returns the value of the specified key. If the key does not exist: insert the key, with the specified value\n", "# update() Updates the dictionary with the specified key-value pairs\n", "# values() Returns a list of all the values in the dictionary" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Dictionary exercises\n", "\n", "# 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": [ "# https://www.w3schools.com/python/python_sets.asp\n", "\n", "# A set object is an unordered collection of distinct objects.\n", "# A dictionary is in key:value format.\n", "# A set is in value-only format." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Create a set\n", "\n", "# Step 1: Create a set 'a' with some elements.\n", "a = {'red', 'green', 'blue', 'blue'}\n", "print('a =', a)\n", "\n", "# Step 2: Print each value in the set.\n", "i = 0\n", "for x in a:\n", " print(i + 1, ' element of a = ', x, sep='')\n", " i = i + 1\n", "\n", "# Step 3: Print the type of the variable 'a'.\n", "print('type(a) →', type(a))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Find if a specific value is in a set\n", "\n", "# Step 1: Create a set 'a' with some elements.\n", "a = {101, 102, 103, 104, 105}\n", "print('a =', a)\n", "\n", "# Step 2: Check if 103 is in the set 'a'.\n", "print('103 is in a →', 103 in a)\n", "\n", "# Step 3: Check if 106 is in the set 'a'.\n", "print('106 is in a →', 106 in a)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Add a new element to a set\n", "\n", "# Step 1: Create a set 'a' with some elements.\n", "a = {101, 102, 103, 104, 105}\n", "print('a =', a)\n", "\n", "# Step 2: Check if 106 is in the set 'a'.\n", "print('106 is in a →', 106 in a)\n", "\n", "# Step 3: Add 106 to the set 'a' using the add() method.\n", "a.add(106)\n", "print('a.add(106) →', a)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Update a set to include specific element(s)\n", "\n", "# Step 1: Create a set 'a' with some elements.\n", "a = {101, 102, 103, 104, 105}\n", "print('a =', a)\n", "\n", "# Step 2: Include 106 in the set 'a' using the update() method with a single element.\n", "a.update({106})\n", "print('a.update({106}) →', a)\n", "\n", "# Step 3: Include 107 and 108 in the set 'a' using the update() method with multiple elements.\n", "a.update({107, 108})\n", "print('a.update({107,108}) →', a)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Update a set to include elements in another set\n", "\n", "# Step 1: Create sets 'a' and 'b' with some elements.\n", "a = {101, 102, 103, 104, 105}\n", "b = {888, 999}\n", "print('a =', a)\n", "print('b =', b)\n", "\n", "# Step 2: Add elements from set 'b' to set 'a' using the update() method.\n", "a.update(b)\n", "print('a.update(b) →', a)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Add new elements from a list,tuple,dictionary into a set\n", "\n", "# Step 1: Create a set 'a', a list 'b', a tuple 'c', and a dictionary 'd' with some elements.\n", "a = {101, 102, 103, 104, 105} # a set\n", "b = [666, 777] # a list\n", "c = (888, 999) # a tuple\n", "d = {6010001: 'Vasa'} # a dictionary\n", "print('a =', a)\n", "print('b =', b)\n", "print('c =', c)\n", "print('d =', d)\n", "\n", "# Step 2: Add new elements from list 'b' to set 'a' (add 666, 777).\n", "a.update(b)\n", "print('a.update(b) →', a)\n", "\n", "# Step 3: Add new elements from tuple 'c' to set 'a' (add 888, 999).\n", "a.update(c)\n", "print('a.update(c) →', a)\n", "\n", "# Step 4: Add new elements from dictionary 'd' to set 'a' (add 6010001).\n", "a.update(d.keys())\n", "print('a.update(d.keys()) →', a)\n", "a.update(d.values())\n", "print('a.update(d.values()) →', a)\n", "a.update(d.items())\n", "print('a.update(d.items()) →', a)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Remove a specific element from a set\n", "\n", "# Step 1: Create a set 'a' with some elements.\n", "a = {101, 102, 103, 104, 105}\n", "print('a =', a)\n", "\n", "# Step 2: Remove the element '103' from the set 'a' using the remove() method.\n", "a.remove(103)\n", "print('a.remove(103) →', a)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Clear a set and delete a set\n", "\n", "# Step 1: Create a set 'a' with some elements.\n", "a = {101, 102, 103, 104, 105}\n", "print('a =', a)\n", "\n", "# Step 2: Clear all items in the set 'a' using the clear() method.\n", "a.clear()\n", "print('a.clear() →', a)\n", "\n", "# Step 3: Delete the set 'a'.\n", "del a\n", "\n", "# Step 4: Check if 'a' still exists in the local namespace.\n", "if 'a' in locals(): # You can also use 'globals()' if needed.\n", " print(\"'a' does exist\")\n", "else:\n", " print(\"'a' does not exist\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### DATA TYPE - SET - MATHEMATICS" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Compute mathematics on a set\n", "\n", "# Step 1: Create a set 'a' with some elements.\n", "a = {101, 103, 104, 102, 106, 105}\n", "print('a =', a)\n", "\n", "# Step 2: Calculate the summation of elements in the set using sum().\n", "print('sum(a) →', sum(a))\n", "\n", "# Step 3: Find the minimum element in the set using min().\n", "print('min(a) →', min(a))\n", "\n", "# Step 4: Find the maximum element in the set using max().\n", "print('max(a) →', max(a))\n", "\n", "# Step 5: Calculate the number of elements in the set using len().\n", "print('len(a) →', len(a))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### DATA TYPE - SET - OPERATIONS" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Find whether b is a subset of a (b <= a)\n", "\n", "# Step 1: Create sets 'a' and 'b'.\n", "a = {101, 102, 103, 104, 105, 106}\n", "b = {101, 102, 103}\n", "print('a =', a)\n", "print('b =', b)\n", "\n", "# Step 2: Check if 'b' is a subset of 'a' using the issubset() method.\n", "print('a.issubset(b) →', a.issubset(b))\n", "print('b.issubset(a) →', b.issubset(a))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Find whether b is a superset of a (b >= a)\n", "\n", "# Step 1: Create sets 'a' and 'b'.\n", "a = {101, 102, 103, 104, 105, 106}\n", "b = {101, 102, 103}\n", "print('a =', a)\n", "print('b =', b)\n", "\n", "# Step 2: Check if 'b' is a superset of 'a' using the issuperset() method.\n", "print('a.issuperset(b) →', a.issuperset(b))\n", "print('b.issuperset(a) →', b.issuperset(a))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Union a with b (a | b) - Combine the element(s) in a and b\n", "\n", "# Step 1: Create sets 'a' and 'b'.\n", "a = {101, 102, 103, 104, 105, 106}\n", "b = {777, 888, 999}\n", "print('a =', a)\n", "print('b =', b)\n", "\n", "# Step 2: Calculate the union of sets 'a' and 'b' without modifying 'a'.\n", "union_result = a.union(b)\n", "print('a.union(b) →', union_result)\n", "print('a =', a) # 'a' remains unchanged\n", "\n", "# Step 3: Calculate the union of sets 'a' and 'b' and assign the result to a new variable 'c'.\n", "c = a.union(b)\n", "print()\n", "print('c = a.union(b) →', c)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Intersection a with b → (a & b) - Find the element(s) in a and b\n", "\n", "# Step 1: Create sets 'a' and 'b'.\n", "a = {101, 102, 103, 104, 105, 106}\n", "b = {101, 102, 103, 777, 888, 999}\n", "print('a =', a)\n", "print('b =', b)\n", "\n", "# Step 2: Calculate the intersection of sets 'a' and 'b' without modifying 'a'.\n", "intersection_result = a.intersection(b)\n", "print('a.intersection(b) →', intersection_result)\n", "print('a =', a) # 'a' remains unchanged\n", "\n", "# Step 3: Calculate the intersection of sets 'a' and 'b' and assign the result to a new variable 'c'.\n", "c = a.intersection(b)\n", "print()\n", "print('c = a.intersection(b) →', c)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Difference a with b → (a - b) - Find the element(s) in a, but not in b\n", "\n", "# Step 1: Create sets 'a' and 'b'.\n", "a = {101, 102, 103, 104, 105, 106}\n", "b = {101, 102, 103, 777, 888, 999}\n", "print('a =', a)\n", "print('b =', b)\n", "\n", "# Step 2: Calculate the difference between sets 'a' and 'b' without modifying 'a'.\n", "difference_result = a.difference(b)\n", "print('a.difference(b) →', difference_result)\n", "print('a =', a) # 'a' remains unchanged\n", "\n", "# Step 3: Calculate the difference between sets 'a' and 'b' and assign the result to a new variable 'c'.\n", "c = a.difference(b)\n", "print()\n", "print('c = a.difference(b) →', c)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Symmetric difference a with b → (a ^ b) or (a - b) | (a - b) or (~(a & b))\n", "# Find the element(s) in both a and b, but NOT the duplicates\n", "\n", "# Step 1: Create sets 'a' and 'b'.\n", "a = {101, 102, 103, 104, 105, 106}\n", "b = {101, 102, 103, 777, 888, 999}\n", "print('a =', a)\n", "print('b =', b)\n", "\n", "# Step 2: Calculate the symmetric difference between sets 'a' and 'b' without modifying 'a'.\n", "symmetric_difference_result = a.symmetric_difference(b)\n", "print('a.symmetric_difference(b) →', symmetric_difference_result)\n", "print('a =', a) # 'a' remains unchanged\n", "\n", "# Step 3: Calculate the symmetric difference between sets 'a' and 'b' and assign the result to a new variable 'c'.\n", "c = a.symmetric_difference(b)\n", "print()\n", "print('c = a.symmetric_difference(b) →', c)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Whatever function ending with _update needs to be done first\n", "# a.difference_update(b)\n", "# a.intersection_update(u)\n", "\n", "# Step 1: Create sets 'a', 'b', and 'u'.\n", "a = {101, 102, 103, 104, 105, 106}\n", "b = {101, 102, 103, 777, 888, 999}\n", "u = {102, 103, 105}\n", "\n", "# Step 2: Use difference_update to modify 'a' by removing elements that are also in 'b'.\n", "a.difference_update(b)\n", "print('After a.difference_update(b): a =', a)\n", "\n", "# Step 3: Use intersection_update to modify 'a' by keeping only elements that are in both 'a' and 'u'.\n", "a.intersection_update(u)\n", "print('After a.intersection_update(u): a =', a)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Sample Set Operations\n", "\n", "# Step 1: Create sets for engineers, managers, and programmers.\n", "engineers = {'John', 'Jane', 'Jack', 'Janice'}\n", "managers = {'Jane', 'Jack', 'Susan', 'Zack'}\n", "programmers = {'Jack', 'Sam', 'Susan', 'Janice'}\n", "print('Engineers =', engineers)\n", "print('Managers =', managers)\n", "print('Programmers =', programmers)\n", "\n", "# Step 2: Calculate the union of all roles to find all employees.\n", "employees = engineers | managers | programmers\n", "print('Employees →', employees)\n", "\n", "# Step 3: Calculate the intersection to find employees who are both engineers and managers.\n", "engineers_managers = engineers & managers \n", "print('Engineers who are also managers →', engineers_managers)\n", "\n", "# Step 4: Calculate the difference to find engineers who are not managers.\n", "engineers_but_managers = engineers - managers \n", "print('Engineers who are not managers →', engineers_but_managers)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Sort set" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Set Methods\n", "\n", "# add() Adds an element to the set\n", "# clear() Removes all the elements from the set\n", "# copy() Returns a copy of the set\n", "# difference() Returns a set containing the difference between two or more sets\n", "# difference_update() Removes the items in this set that are also included in another, specified set\n", "# discard() Remove the specified item\n", "# intersection() Returns a set, that is the intersection of two other sets\n", "# intersection_update() Removes the items in this set that are not present in other, specified set(s)\n", "# isdisjoint() Returns whether two sets have a intersection or not\n", "# issubset() Returns whether another set contains this set or not\n", "# issuperset() Returns whether this set contains another set or not\n", "# pop() Removes an element from the set\n", "# remove() Removes the specified element\n", "# symmetric_difference() Returns a set with the symmetric differences of two sets\n", "# symmetric_difference_update() inserts the symmetric differences from this set and another\n", "# union() Return a set containing the union of sets\n", "# update() Update the set with the union of this set and others" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Set Exercises\n", "\n", "# 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": [ "# Convert a list into a set\n", "\n", "# Step 1: Create a list 'a'.\n", "a = [1, 2, 3, 4, 5, 6]\n", "print('a =', a)\n", "print('type(a) =', type(a))\n", "\n", "# Step 2: Convert the list 'a' into a set 's'.\n", "s = set(a)\n", "print('s = set(a) →', s)\n", "print('type(s) =', type(s))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Convert a tuple into a set\n", "\n", "# Step 1: Create a tuple 'a'.\n", "a = (1, 2, 3, 4, 5, 6)\n", "print('a =', a)\n", "print('type(a) =', type(a))\n", "\n", "# Step 2: Convert the tuple 'a' into a set 's'.\n", "s = set(a)\n", "print('s = set(a) →', s)\n", "print('type(s) =', type(s))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Convert a dictionary into a set\n", "\n", "# Step 1: Create a dictionary 'a'.\n", "a = {1: 'A', 2: 'B', 3: 'C'}\n", "print('a =', a)\n", "print('type(a) =', type(a))\n", "\n", "# Step 2: Convert the dictionary keys into a set 's'.\n", "s = set(a.keys())\n", "print('s = set(a.keys()) →', s)\n", "print('type(s) =', type(s))\n", "\n", "# Step 3: Convert the dictionary values into a set and union it with the previous set 's'.\n", "s = s.union(set(a.values()))\n", "print('s = set(a.values()) →', s)\n", "print('type(s) =', type(s))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Convert string to integer data type\n", "\n", "# Step 1: Create a string 'a' that represents a number.\n", "a = '10'\n", "print('a =', a)\n", "print('type(a) =', type(a))\n", "\n", "# Step 2: Convert the string 'a' to an integer 'b'.\n", "b = int(a)\n", "print('b = int(a) →', b)\n", "print('type(b) =', type(b))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Convert string to float data type\n", "\n", "# Step 1: Create a string 'a' that represents a floating-point number.\n", "a = '10.1'\n", "print('a =', a)\n", "print('type(a) =', type(a))\n", "\n", "# Step 2: Convert the string 'a' to a float 'b'.\n", "b = float(a)\n", "print('b = float(a) →', b)\n", "print('type(b) =', type(b))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Convert string to float data type\n", "\n", "# Step 1: Create a string 'a' that represents a number (either integer or float).\n", "a = '10.1'\n", "print('a =', a)\n", "\n", "# Step 2: Check if 'a' contains a period ('.'). If it does, convert it to a float; otherwise, convert it to an integer.\n", "if '.' in a:\n", " b = float(a)\n", " print('b = float(a) →', b)\n", " print('type(b) =', type(b))\n", "else:\n", " c = int(a)\n", " print('c = int(a) →', c)\n", " print('type(c) =', type(c))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Convert integer to string data type\n", "\n", "# Step 1: Create an integer 'a'.\n", "a = 10\n", "print('a =', a)\n", "print('type(a) =', type(a))\n", "\n", "# Step 2: Convert the integer 'a' to a string 'b'.\n", "b = str(a)\n", "print('b = str(a) →', b)\n", "print('type(b) =', type(b))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Convert float to string data type\n", "\n", "# Step 1: Create a float 'a'.\n", "a = 10.1\n", "print('a =', a)\n", "print('type(a) =', type(a))\n", "\n", "# Step 2: Convert the float 'a' to a string 'b'.\n", "b = str(a)\n", "print('b = str(a) →', b)\n", "print('type(b) =', type(b))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# List all the supported methods for a class\n", "\n", "# Step 1: Integer\n", "a = 10\n", "print('Step 1 - Integer:')\n", "print('a =', a)\n", "print('type(a) =', type(a))\n", "print('Methods and attributes for Integer:')\n", "for item in dir(a):\n", " print(item)\n", "\n", "# Step 2: Float\n", "print('\\nStep 2 - Float:')\n", "a = 10.1\n", "print('a =', a)\n", "print('type(a) =', type(a))\n", "print('Methods and attributes for Float:')\n", "for item in dir(a):\n", " print(item)\n", "\n", "# Step 3: String\n", "print('\\nStep 3 - String:')\n", "a = '10.1'\n", "print('a =', a)\n", "print('type(a) =', type(a))\n", "print('Methods and attributes for String:')\n", "for item in dir(a):\n", " print(item)" ] }, { "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": [ "# https://www.w3schools.com/python/python_operators.asp" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Operators\n", "\n", "# Step 1: Initialize variables a and b.\n", "a = 15\n", "b = 5\n", "print('Step 1: Initialize variables a and b')\n", "print('a =', a)\n", "print('b =', b)\n", "\n", "# Step 2: Addition\n", "print('\\nStep 2: Addition')\n", "print('a+b →', a + b)\n", "\n", "# Step 3: Subtraction\n", "print('\\nStep 3: Subtraction')\n", "print('a-b →', a - b)\n", "\n", "# Step 4: Multiplication\n", "print('\\nStep 4: Multiplication')\n", "print('a*b →', a * b)\n", "print('float(a)*b →', float(a) * b)\n", "print('a*float(b) →', a * float(b))\n", "print('float(a)*float(b) →', float(a) * float(b))\n", "print('float(a*b) →', float(a * b))\n", "\n", "# Step 5: Change the values of variables a and b.\n", "a = 15\n", "b = 2\n", "print()\n", "print('Step 5: Change the values of variables a and b')\n", "print('a =', a)\n", "print('b =', b)\n", "\n", "# Step 6: Division\n", "print('\\nStep 6: Division')\n", "print('a/b →', a / b)\n", "print('float(a)/b →', float(a) / b)\n", "print('a/float(b) →', a / float(b))\n", "print('float(a)/float(b) →', float(a) / float(b))\n", "\n", "# Step 7: Floor or Div (Output of a division)\n", "print('\\nStep 7: Floor or Div (Output of a division)')\n", "print('a//b →', a // b)\n", "print('float(a)//b →', float(a) // b)\n", "print('a//float(b) →', a // float(b))\n", "print('float(a)//float(b) →', float(a) // float(b))\n", "\n", "# Step 8: Modulus (Remainder of a division)\n", "print('\\nStep 8: Modulus (Remainder of a division)')\n", "print('a%b →', a % b)\n", "print('float(a)%b →', float(a) % b)\n", "print('a%float(b) →', a % float(b))\n", "print('float(a)%float(b) →', float(a) % float(b))\n", "\n", "# Step 9: Exponentiation (a**b)\n", "print('\\nStep 9: Exponentiation (a**b)')\n", "print('a**b →', a ** b)\n", "print('float(a)**b →', float(a) ** b)\n", "print('a**float(b) →', a ** float(b))\n", "print('float(a)**float(b) →', float(a) ** float(b))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## OPERATORS - COMPOUND ARITHMETIC OPERATORS" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Addition (a = a+b)\n", "\n", "# Step 1: Initialize variables a and b\n", "a = 15\n", "b = 5\n", "\n", "# Step 2: Print the values of a and b\n", "print('a =', a)\n", "print('b =', b)\n", "\n", "# Step 3: Perform addition operation (a = a + b) and print the result\n", "result = a + b\n", "print('a = a + b → a =', a, '+', b, ' → a =', result)\n", "\n", "# Step 4: Perform addition operation using shorthand (a += b) and print the result\n", "a += b # This is equivalent to a = a + b\n", "print('a += b → a =', a, '+', b, ' → a =', a)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Subtraction (a = a-b)\n", "\n", "# Step 1: Initialize variables a and b\n", "a = 15\n", "b = 5\n", "\n", "# Step 2: Print the values of a and b\n", "print('a =', a)\n", "print('b =', b)\n", "\n", "# Step 3: Perform subtraction operation (a = a - b) and print the result\n", "result = a - b\n", "print('a = a - b → a =', a, '-', b, ' → a =', result)\n", "\n", "# Step 4: Perform subtraction operation using shorthand (a -= b) and print the result\n", "a -= b # This is equivalent to a = a - b\n", "print('a -= b → a =', a, '-', b, ' → a =', a)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Multiplication (a = a*b)\n", "\n", "# Step 1: Initialize variables a and b\n", "a = 15\n", "b = 5\n", "\n", "# Step 2: Print the values of a and b\n", "print('a =', a)\n", "print('b =', b)\n", "\n", "# Step 3: Perform multiplication operation (a = a * b) and print the result\n", "result = a * b\n", "print('a = a × b → a =', a, '×', b, ' → a =', result)\n", "\n", "# Step 4: Perform multiplication operation using shorthand (a *= b) and print the result\n", "a *= b # This is equivalent to a = a * b\n", "print('a *= b → a =', a, '×', b, ' → a =', a)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Division (a = a/b)\n", "\n", "# Step 1: Initialize variables a and b\n", "a = 15\n", "b = 5\n", "\n", "# Step 2: Print the values of a and b\n", "print('a =', a)\n", "print('b =', b)\n", "\n", "# Step 3: Perform division operation (a = a / b) and print the result\n", "result = a / b\n", "print('a = a / b → a =', a, '÷', b, ' → a =', result)\n", "\n", "# Step 4: Perform division operation using shorthand (a /= b) and print the result\n", "a /= b # This is equivalent to a = a / b\n", "print('a /= b → a =', a, '÷', b, ' → a =', a)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## OPERATORS - LOGICAL OPERATORS" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Check 'a' is strictly less than 'b'\n", "\n", "# Step 1: Initialize variables a and b\n", "a = 5\n", "b = 5\n", "\n", "# Step 2: Check if a is strictly less than b and store the result in variable c\n", "c = a < b # This will be a Boolean value (True or False)\n", "\n", "# Step 3: Print the values of a and b\n", "print('a =', a)\n", "print('b =', b)\n", "\n", "# Step 4: Print the comparison operation (a < b) as a question\n", "print('a < b → ?')\n", "\n", "# Step 5: Print the comparison operation (a < b) with values and the result\n", "print(a, '<', b, '→ ?')\n", "\n", "# Step 6: Print the result of the comparison (True or False)\n", "print(a, '<', b, '→', c)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Check 'a' is less than or equal to 'b'\n", "\n", "# Step 1: Initialize variables a and b\n", "a = 5\n", "b = 5\n", "\n", "# Step 2: Check if a is less than or equal to b and store the result in variable c\n", "c = a <= b # This will be a Boolean value (True or False)\n", "\n", "# Step 3: Print the values of a and b\n", "print('a =', a)\n", "print('b =', b)\n", "\n", "# Step 4: Print the comparison operation (a <= b) as a question\n", "print('a <= b → ?')\n", "\n", "# Step 5: Print the comparison operation (a <= b) with values and the result\n", "print(a, '<=', b, '→ ?')\n", "\n", "# Step 6: Print the result of the comparison (True or False)\n", "print(a, '<=', b, '→', c)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Check 'a' is strictly greater than 'b'\n", "\n", "# Step 1: Initialize variables a and b\n", "a = 5\n", "b = 5\n", "\n", "# Step 2: Check if a is strictly greater than b and store the result in variable c\n", "c = a > b # This will be a Boolean value (True or False)\n", "\n", "# Step 3: Print the values of a and b\n", "print('a =', a)\n", "print('b =', b)\n", "\n", "# Step 4: Print the comparison operation (a > b) as a question\n", "print('a > b → ?')\n", "\n", "# Step 5: Print the comparison operation (a > b) with values and the result\n", "print(a, '>', b, '→ ?')\n", "\n", "# Step 6: Print the result of the comparison (True or False)\n", "print(a, '>', b, '→', c)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Check 'a' is greater than or equal to 'b'\n", "\n", "# Step 1: Initialize variables a and b\n", "a = 5\n", "b = 5\n", "\n", "# Step 2: Check if a is greater than or equal to b and store the result in variable c\n", "c = a >= b # This will be a Boolean value (True or False)\n", "\n", "# Step 3: Print the values of a and b\n", "print('a =', a)\n", "print('b =', b)\n", "\n", "# Step 4: Print the comparison operation (a >= b) as a question\n", "print('a >= b → ?')\n", "\n", "# Step 5: Print the comparison operation (a >= b) with values and the result\n", "print(a, '>=', b, '→ ?')\n", "\n", "# Step 6: Print the result of the comparison (True or False)\n", "print(a, '>=', b, '→', c)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Check if 'a' is equal to 'b'\n", "\n", "# Step 1: Initialize variables a and b\n", "a = 5\n", "b = 5\n", "\n", "# Step 2: Check if a is equal to b and store the result in variable c\n", "c = a == b # This will be a Boolean value (True or False)\n", "\n", "# Step 3: Print the values of a and b\n", "print('a =', a)\n", "print('b =', b)\n", "\n", "# Step 4: Print the comparison operation (a == b) as a question\n", "print('a == b → ?')\n", "\n", "# Step 5: Print the comparison operation (a == b) with values and the result\n", "print(a, '==', b, '→ ?')\n", "\n", "# Step 6: Print the result of the comparison (True or False)\n", "print(a, '==', b, '→', c)\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Check 'a' is not equal to 'b'\n", "\n", "# Step 1: Initialize variables a and b\n", "a = 5\n", "b = 5\n", "\n", "# Step 2: Check if a is not equal to b and store the result in variable c\n", "c = a != b # This will be a Boolean value (True or False)\n", "\n", "# Step 3: Print the values of a and b\n", "print('a =', a)\n", "print('b =', b)\n", "\n", "# Step 4: Print the comparison operation (a != b) as a question\n", "print('a != b → ?')\n", "\n", "# Step 5: Print the comparison operation (a != b) with values and the result\n", "print(a, '!=', b, '→ ?')\n", "\n", "# Step 6: Print the result of the comparison (True or False)\n", "print(a, '!=', b, '→', c)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# AND (True/False, case sensitive) (both are True, then True; otherwise, false)\n", "\n", "# Step 1: Initialize boolean variables a and b\n", "a = True\n", "b = False\n", "\n", "# Step 2: Print the values of a and b\n", "print('a =', a)\n", "print('b =', b)\n", "\n", "# Step 3: Perform logical AND operation (a and b) and print the result\n", "result1 = a and b\n", "print('a and b →', result1)\n", "\n", "# Step 4: Perform logical AND operation (a & b) and print the result\n", "result2 = a & b\n", "print('a & b →', result2)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# OR (both are False, then false; otherwise, True)\n", "\n", "# Step 1: Initialize boolean variables a and b\n", "a = True\n", "b = False\n", "\n", "# Step 2: Print the values of a and b\n", "print('a =', a)\n", "print('b =', b)\n", "\n", "# Step 3: Perform logical OR operation (a or b) and print the result\n", "result1 = a or b\n", "print('a or b →', result1)\n", "\n", "# Step 4: Perform logical OR operation (a | b) and print the result\n", "result2 = a | b\n", "print('a | b →', result2)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# NOT (negation)\n", "\n", "# Step 1: Initialize a boolean variable a\n", "a = True\n", "\n", "# Step 2: Print the value of a\n", "print('a =', a)\n", "\n", "# Step 3: Perform the logical NOT operation (not a) and print the result\n", "result = not a\n", "print('not a →', result)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## OPERATORS - MEMBERSHIP" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# List - Find whether b is in a\n", "\n", "# Step 1: Initialize a list a and an element b\n", "a = [101, 102]\n", "b = 101\n", "\n", "# Step 2: Print the values of a and b\n", "print('a =', a)\n", "print('b =', b)\n", "\n", "# Step 3: Check if b is in the list a and print the result\n", "result = b in a\n", "print('b in a →', result)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Tuple - Find whether b is in a\n", "\n", "# Step 1: Initialize a tuple a and an element b\n", "a = (101, 102)\n", "b = 101\n", "\n", "# Step 2: Print the values of a and b\n", "print()\n", "print('a =', a)\n", "print('b =', b)\n", "\n", "# Step 3: Check if b is in the tuple a and print the result\n", "result = b in a\n", "print('b in a →', result)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Set - Find whether b is in a\n", "\n", "# Step 1: Initialize a set a and an element b\n", "a = {101, 102}\n", "b = 101\n", "\n", "# Step 2: Print the values of a and b\n", "print()\n", "print('a =', a)\n", "print('b =', b)\n", "\n", "# Step 3: Check if b is in the set a and print the result\n", "result = b in a\n", "print('b in a →', result)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# List - Find whether b is NOT in a\n", "\n", "# Step 1: Initialize a list a and an element b\n", "a = [101, 102]\n", "b = 101\n", "\n", "# Step 2: Print the values of a and b\n", "print('a =', a)\n", "print('b =', b)\n", "\n", "# Step 3: Check if b is not in the list a and print the result\n", "result = b not in a\n", "print('b not in a →', result)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Tuple - Find whether b is NOT in a\n", "\n", "# Step 1: Initialize a tuple a and an element b\n", "a = (101, 102)\n", "b = 101\n", "\n", "# Step 2: Print the values of a and b\n", "print()\n", "print('a =', a)\n", "print('b =', b)\n", "\n", "# Step 3: Check if b is not in the tuple a and print the result\n", "result = b not in a\n", "print('b not in a →', result)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Set - Find whether b is NOT in a\n", "\n", "# Step 1: Initialize a set a and an element b\n", "a = {101, 102}\n", "b = 101\n", "\n", "# Step 2: Print the values of a and b\n", "print()\n", "print('a =', a)\n", "print('b =', b)\n", "\n", "# Step 3: Check if b is not in the set a and print the result\n", "result = b not in a\n", "print('b not in a →', result)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## OPERATORS - IDENTITY" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# is - number (==)\n", "\n", "# Step 1: Initialize integer variables a, b, and c\n", "a = 1\n", "b = 1\n", "c = 2\n", "\n", "# Step 2: Print the values of a, b, and c\n", "print('a =', a)\n", "print('b =', b)\n", "print('c =', c)\n", "\n", "# Step 3: Check if b is the same object as a (reference the same value in memory)\n", "result1 = b is a\n", "print('b is a →', result1)\n", "\n", "# Step 4: Check if c is the same object as a (reference the same value in memory)\n", "result2 = c is a\n", "print('c is a →', result2)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# is not (!=)\n", "\n", "# Step 1: Initialize integer variables a, b, and c\n", "a = 1\n", "b = 1\n", "c = 2\n", "\n", "# Step 2: Print the values of a, b, and c\n", "print('a =', a)\n", "print('b =', b)\n", "print('c =', c)\n", "\n", "# Step 3: Check if b is not the same object as a (do not reference the same value in memory)\n", "result1 = b is not a\n", "print('b is not a →', result1)\n", "\n", "# Step 4: Check if c is not the same object as a (do not reference the same value in memory)\n", "result2 = c is not a\n", "print('c is not a →', result2)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# is - string\n", "\n", "# Step 1: Initialize string variables a, b, and c\n", "a = \"hello\"\n", "b = \"hello\"\n", "c = \"Hello\"\n", "\n", "# Step 2: Print the values of a, b, and c\n", "print()\n", "print('a =', a)\n", "print('b =', b)\n", "print('c =', c)\n", "\n", "# Step 3: Check if b is not the same object as a (do not reference the same value in memory)\n", "result1 = b is not a\n", "print('b is not a →', result1)\n", "\n", "# Step 4: Check if c is not the same object as a (do not reference the same value in memory)\n", "result2 = c is not a\n", "print('c is not a →', result2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## OPERATORS - PRECEDENCE" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Arithmetic operators will be performend in a specific order defined by the precedence\n", "# (),*/,+-\n", "\n", "# Step 1: Initialize integer variables a, b, and c\n", "a = 3\n", "b = 2\n", "c = 1\n", "\n", "# Step 2: Print the values of a, b, and c\n", "print('a =', a)\n", "print('b =', b)\n", "print('c =', c)\n", "\n", "# Step 3: Perform arithmetic operations with expressions and print the results\n", "\n", "# a + b - c → Add a and b first, then subtract c\n", "print('a+b-c →', a + b - c, '(calculate a+b first)')\n", "\n", "# a * b - c → Multiply a and b first, then subtract c\n", "print('a*b-c →', a * b - c, '(calculate a*b first)')\n", "\n", "# a + b * c → Multiply b and c first, then add a\n", "print('a+b*c →', a + b * c, '(calculate b*c first)')\n", "\n", "# (a + b) * c → Add a and b first, then multiply by c using parentheses\n", "print('(a+b)*c →', (a + b) * c, '(calculate a+b first)')\n", "\n", "# a + (b * c) → Multiply b and c first, then add a using parentheses\n", "print('a+(b*c) →', a + (b * c), '(calculate b*c first)')\n", "\n", "# (a + b) - c → Add a and b first, then subtract c using parentheses\n", "print('(a+b)-c →', (a + b) - c, '(calculate a+b first)')\n", "\n", "# a + (b - c) → Subtract c from b first, then add a using parentheses\n", "print('a+(b-c) →', a + (b - c), '(calculate b-c first)')\n", "\n", "# (a * b) ** c → Multiply a and b first, then raise the result to the power of c using parentheses\n", "print('(a*b)**c →', (a * b) ** c, '(calculate a*b first)')\n", "\n", "# a * (b ** c) → Raise b to the power of c first, then multiply the result by a using parentheses\n", "print('a*(b**c) →', a * (b ** c), '(calculate b**c first)')" ] }, { "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": [ "# Syntax\n", "# if expression1:\n", "# statement(s)\n", "# elif expression2:\n", "# statement(s)\n", "# else:\n", "# statement(s)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# if-else\n", "\n", "# Step 1: Initialize integer variables a and b\n", "a = 1\n", "b = 2\n", "\n", "# Step 2: Print the values of a and b\n", "print('a =', a)\n", "print('b =', b)\n", "\n", "# Step 3: Use an if-else statement to compare a and b\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\n", "\n", "# Step 1: Initialize integer variables a and b\n", "a = 1\n", "b = 2\n", "\n", "# Step 2: Print the values of a and b\n", "print('a =', a)\n", "print('b =', b)\n", "\n", "# Step 3: Use an if-elif-else statement to compare a and b\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 input()\n", "\n", "# Step 1: Prompt the user to enter the order amount and convert it to a float\n", "order = float(input('What is the order amount: ')) # default input function returns a string, so convert to float\n", "\n", "# Step 2: Use an if-else statement to determine the discount\n", "if order > 100:\n", " discount = 25\n", "else:\n", " discount = 0\n", "\n", "# Step 3: Print the calculated discount\n", "print('Discount =', discount)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## CONTROL STRUCTURES - TERNARY OPERATOR" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# STOP ON 24/08/2021\n", "# Ternary operator\n", "\n", "# Step 1: Prompt the user to enter the order amount and convert it to a float\n", "order = float(input('What is the order amount: ')) # default input function returns a string, so convert to float\n", "\n", "# Step 2: Use a ternary operator to calculate the discount\n", "discount = 25 if order > 100 else 0\n", "\n", "# Step 3: Print the calculated discount\n", "print('Discount =', discount)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Challenge \n", "# Ask 'What is your grade'\n", "# if grade is A, then print \"Excellent!\"\n", "# if grade is B, then print \"Well done!\"\n", "# if grade is C, then print \"Work harder\"\n", "# otherwise, 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": [ "# Syntax\n", "# while condition:\n", "# statement(s)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# while-loop\n", "\n", "# Step 1: Initialize integer variable a\n", "a = 1\n", "\n", "# Step 2: Prompt the user to enter the number of loops and convert it to an integer\n", "loop = int(input('Enter the loop: '))\n", "\n", "# Step 3: Print a message to indicate the beginning of the loop\n", "print('Begin loop')\n", "\n", "# Step 4: Use a while loop to iterate while a is less than or equal to the specified loop value\n", "while (a <= loop):\n", " # Step 5: Print the value of a inside the loop\n", " print('Inside loop: a =', a)\n", " \n", " # Step 6: Increment the value of a by 1\n", " a += 1 # The indentation (tab) is important; it must be inside the loop block\n", "\n", "# Step 7: Print a message to indicate the end of the loop\n", "print('End loop')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Challenge" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## CONTROL STRUCTURES - FOR-LOOP" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# for variable in range(a,b):\n", "# statement(s)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# for-loop - print 1,2,3,...,n\n", "# Print the loop directly\n", "# Step 1: Prompt the user to enter the number of loops and convert it to an integer\n", "loop = int(input('Enter the loop: '))\n", "\n", "# Step 2: Print a message to indicate the beginning of the loop\n", "print('Begin loop')\n", "\n", "# Step 3: Use a for loop to iterate from 1 to the specified loop value (inclusive)\n", "for a in range(1, loop + 1):\n", " # Step 4: Print the current value of 'a' inside the loop\n", " print('Inside loop: a =', a)\n", "\n", "# Step 5: Print a message to indicate the end of the loop\n", "print('End Loop')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# for-loop - print 1,2,3,...,n\n", "# Print the loop from a list\n", "\n", "# Step 1: Initialize an empty list 'a'\n", "a = []\n", "\n", "# Step 2: Print a message to indicate the beginning of the loop\n", "print('Begin loop')\n", "\n", "# Step 3: Use a for loop to iterate from 1 to the specified loop value (inclusive)\n", "for x in range(1, loop + 1):\n", " # Step 4: Append the current value of 'x' to the list 'a'\n", " a.append(x)\n", " \n", " # Step 5: Print the list 'a' inside the loop\n", " print('Inside loop:', a)\n", "\n", "# Step 6: Print a message to indicate the end of the loop\n", "print('End loop')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Challenge" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# MODULE 4 - FUNCTIONS" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## FUNCTIONS" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Blocks of code that perform specific tasks\n", "# - Calculate a mathematical expression\n", "# - Evaluate the outcome of a series of statements\n", "# - Print results in a specific format" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Syntax\n", "# def func_name(input list):\n", "# statement(s)\n", "# return output_expression" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Pass one argument, return one output\n", "\n", "# Step 1: Define a function 'powertwo' that takes one argument 'x' and returns 'x*x'\n", "def powertwo(x):\n", " return x * x\n", "\n", "# Step 2: Prompt the user to enter a number and convert it to an integer\n", "n = int(input('Enter a number: '))\n", "\n", "# Step 3: Calculate the square of the entered number using the 'powertwo' function\n", "result = powertwo(n)\n", "\n", "# Step 4: Print the result\n", "print('The power two of', n, 'is', result)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Challenge - Taxi Fare\n", "# Create a function for computing the taxi fare\n", "# taxi fare = booking fee + starting price+ distance * cost per km" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Pass one argument, return two outputs\n", "\n", "# Step 1: Define a function 'power23' that takes one argument 'x' and returns a tuple containing 'x*x' and 'x*x*x'\n", "def power23(x):\n", " return (x * x, x * x * x)\n", "\n", "# Step 2: Prompt the user to enter a number and convert it to an integer\n", "n = int(input('Enter a number: '))\n", "\n", "# Step 3: Calculate the square and cube of the entered number using the 'power23' function\n", "result = power23(n)\n", "\n", "# Step 4: Print the results\n", "print('The power two and three of', n, 'are', result[0], 'and', result[1])" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Challenge - Function\n", "# Create a function to return the discount and the tax for grocery purchase\n", "# discount = 25 if order > 200 else 0\n", "# tax = 0.07*(order after discount)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Pass two arguments, return one argument\n", "\n", "# Step 1: Define a function 'add' that takes two arguments 'x' and 'y', adds them, and returns the result\n", "def add(x, y):\n", " z = x + y\n", " return z\n", "\n", "# Step 2: Prompt the user to enter two numbers and convert them to integers\n", "m = int(input('Enter a number #1: '))\n", "n = int(input('Enter a number #2: '))\n", "\n", "# Step 3: Calculate the sum of the entered numbers using the 'add' function\n", "result = add(m, n)\n", "\n", "# Step 4: Print the result\n", "print(m, '+', n, '=', result)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Assign default values to the arguments\n", "\n", "# Step 1: Define a function 'rect' with default values for 'a' and 'b'\n", "def rect(a=3, b=5):\n", " return a * b\n", "\n", "# Step 2: Call the 'rect' function without providing arguments (uses default values)\n", "print('rect() →', rect())\n", "\n", "# Step 3: Call the 'rect' function and override default values (a ← 2, b ← 3)\n", "print('rect(2,3) →', rect(2, 3))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Pass variable arguments\n", "\n", "# Step 1: Define a function 'sum' that takes 'a' as the first argument and '*b' to collect additional arguments in a tuple\n", "def sum(a, *b):\n", " s = a\n", " for i in b:\n", " s = s + i\n", " return s\n", "\n", "# Step 2: Call the 'sum' function with different numbers of arguments\n", "print('sum(1) →', sum(1))\n", "print('sum(1,2) →', sum(1, 2))\n", "print('sum(1,2,3) →', sum(1, 2, 3))\n", "print('sum(1,2,3,4) →', sum(1, 2, 3, 4))\n", "print('sum(1,2,3,4,5) →', sum(1, 2, 3, 4, 5))\n", "print('sum(1,2,3,4,5,6) →', sum(1, 2, 3, 4, 5, 6))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Challenge - Minimum Value\n", "# Give a sequence of variable number of elements, create a function to determine the minimum value" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## FUNCTIONS - LAMBDA" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# https://www.w3schools.com/python/python_lambda.asp\n", "\n", "# A lambda function can take any number of arguments, but can only have one expression.\n", "\n", "# When to use Def or Lambda\n", "# When you don't need the function name, use lambda, eg passing a function to another function\n", "# When you need to use the function name to re-use again, use def\n", "\n", "# Syntax\n", "# lambda input list: output expression\n", "\n", "# equivalent to\n", "\n", "# def name(arg1, arg2,....): \n", "# return expression" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Create a lambda\n", "\n", "# Step 1: Create a lambda function 'f' that takes 'x' as an argument and returns 'x*x'\n", "f = lambda x: x*x\n", "\n", "# Step 2: Print the lambda function\n", "print('f = lambda x: x*x')\n", "\n", "# Step 3: Call the lambda function and calculate 'x*x'\n", "print('x*x →', f(10))\n", "\n", "\n", "# Create a function equivalent to the above lambda\n", "\n", "# Step 1: Define a regular function 'f' that takes 'x' as an argument and returns 'x*x'\n", "def f(x):\n", " return x*x\n", "\n", "# Step 2: Print the regular function\n", "print()\n", "print('def f(x):')\n", "print(' return x*x')\n", "\n", "# Step 3: Call the regular function and calculate 'x*x'\n", "print('x*x →', f(10))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Challenge - Lambda\n", "# Write the lambda function for \n", "# def f(x,y):\n", "# return 10*x+y" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## FUNCTIONS - MAP" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# https://www.w3schools.com/python/ref_func_map.asp\n", "\n", "# The map() function executes a specified function for each item in an iterable.\n", "# The item is sent to the function as a parameter.\n", "\n", "# Syntax\n", "# map(function, seq)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Create a lambda and execute the map function\n", "\n", "# Step 1: Create a list 'a'\n", "a = [1, 2, 3, 4, 5]\n", "\n", "# Step 2: Create a lambda function 'f' that calculates the square of its input 'x'\n", "f = lambda x: x**2\n", "\n", "# Step 3: Print the list 'a' and the lambda function 'f'\n", "print('a =', a)\n", "print('f = lambda x: x**2')\n", "\n", "# Step 4: Use the 'map' function to apply 'f' to each element in 'a', and convert the result to a list\n", "result = list(map(f, a))\n", "\n", "# Step 5: Print the result, which contains the squares of the elements in 'a'\n", "print('list(map(f, a)) →', result)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Challenge - Map\n", "# Using map to compute the answer for \n", "# f = lambda x,y:10*x+y\n", "# x = [0,1,2,3]\n", "# y = [2,4,6,8]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# MODULE 5 - MODULES (LIBRARY)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# https://www.w3schools.com/python/python_modules.asp\n", "\n", "# A module allows you to logically organize your Python code.\n", "# Grouping related code into a module makes the code easier to understand and use.\n", "# A module is a Python object with arbitrarily named attributes that you can bind and reference.\n", "# Simply, a module is a file consisting of Python code.\n", "# A module can define functions, classes and variables.\n", "# A module can also include runnable code.\n", "\n", "# Python’s standard library is very useful and extensive.\n", "# https://docs.python.org/3/library/\n", "# math\n", "# random\n", "# statistics\n", "# sys\n", "# datetime\n", "# urllib\n", "\n", "# Syntax\n", "# library_name.function()\n", "\n", "# The only difference between \"import\" and \"from\" statements is what name is bound.\n", "# import sys binds the name sys to the module (so sys -> sys.modules['sys']).\n", "# from sys import argv binds a different name, argv , pointing straight at the attribute contained inside of the module (so argv -> sys)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Import everything in a \"math\" library\n", "\n", "# Step 1: Import the entire 'math' library\n", "import math\n", "\n", "# Step 2: Calculate the sine of 0.5 radians using the 'math.sin()' function\n", "result = math.sin(0.5)\n", "\n", "# Step 3: Print the result\n", "print('math.sin(0.5) →', result)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Import everything in a \"math\" library with a new abbreviation\n", "\n", "# Select \"Kernel\" menu and execute \"Restart & Clear Output\" before executing the below statements\n", "# Error will occur because of unknown math.sin function\n", "\n", "# Step 1: Import the entire 'math' library with the abbreviation 'm'\n", "import math as m\n", "\n", "# Step 2: Correctly calculate the sine of 0.5 radians using the 'm.sin()' function\n", "print('math.sin(0.5) →', math.sin(0.5)) # Comment this line to fix the problem\n", "print('m.sin(0.5) →', m.sin(0.5)) # Use 'm.sin()' to correctly calculate the sine" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Import everything in a math library\n", "\n", "# Select \"Kernel\" menu and execute \"Restart & Clear Output\" before executing the below statements\n", "# Error will occur because of unknown math.sin function\n", "\n", "# Step 1: Import everything from the 'math' library\n", "from math import *\n", "\n", "# Step 2: Correctly calculate the sine of 0.5 radians using the 'sin()' function\n", "#print(math.sin(0.5)) # Comment this line to fix the problem\n", "print('sin(0.5) →', sin(0.5)) # Use 'sin()' to correctly calculate the sine" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# The statement \"import math\" brings only the name math into scope.\n", "# The statement \"import *\" brings all of the names exposed by the math module into scope.\n", "\n", "# \"import math\"\n", "# The advantage of \"import math\" is that it keeps your namespace clean \n", "# and helps you quickly recognize which modules the functions used in your code came from. \n", "# The disadvantage is having to use longer function names, \n", "# for example: math.sqrt instead of sqrt. \n", "# This problem can be mitigated by shortening the name\n", "# (for example, NumPy is customarily invoked using import numpy as np).\n", "\n", "# \"import *\"\n", "# The advantage of \"import *\" is having shorter function names,\n", "# for example: sqrt instead of math.sqrt. \n", "\n", "# It’s generally considered good practice to avoid wildcard imports, \n", "# especially for code that will be reused." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Import a few selected names in a math library\n", "\n", "# Select \"Kernel\" menu and execute \"Restart & Clear Output\" before executing the below statements\n", "# Error will occur because of unknown cos function\n", "\n", "from math import sin,pi\n", "\n", "print(sin(0.5))\n", "print(cos(0.5)) # comment this statement to fix the problem" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## MODULES - MATH" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# math library\n", "\n", "# Step 1: Import the 'math' library\n", "import math\n", "\n", "# Step 2: Print the constants from the 'math' library\n", "print('math.pi =', math.pi) # Print the constant for pi (π)\n", "print('math.e =', math.e) # Print the constant for the base of the natural logarithm (e)\n", "print('math.inf =', math.inf) # Print positive infinity (inf)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Compute sin function\n", "\n", "# Step 1: Import the 'math' library\n", "import math\n", "\n", "# Step 2: Prompt the user to enter a number and convert it to a float\n", "n = float(input('Enter a number: '))\n", "\n", "# Step 3: Calculate the sine of the entered number using 'math.sin()' and print the result\n", "print('math.sin(', n, ') → ', math.sin(n), sep='')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Compute cos function\n", "\n", "# Step 1: Import the 'math' library\n", "import math\n", "\n", "# Step 2: Prompt the user to enter a number and convert it to a floating-point number\n", "n = float(input('Enter a number: '))\n", "\n", "# Step 3: Calculate the cosine of the entered number using 'math.cos()' and print the result\n", "print('math.cos(', n, ') → ', math.cos(n), sep='')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Compute radians function\n", "\n", "# Step 1: Import the 'math' library\n", "import math\n", "\n", "# Step 2: Prompt the user to enter a degree value and convert it to a floating-point number\n", "n = float(input('Enter a degree: '))\n", "\n", "# Step 3: Convert the degree value into radians using 'math.radians()' and print the result\n", "print('math.radians(', n, ') → ', math.radians(n), sep='')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Compute a log 2 function\n", "\n", "# Step 1: Import the 'math' library\n", "import math\n", "\n", "# Step 2: Prompt the user to enter a number and convert it to a floating-point number\n", "n = float(input('Enter a number: '))\n", "\n", "# Step 3: Compute the base-2 logarithm of the entered number using 'math.log()' and print the result\n", "print('math.log(', n, ', 2) → ', math.log(n, 2), sep='')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Compute a log base n function\n", "\n", "# Step 1: Import the 'math' library\n", "import math\n", "\n", "# Step 2: Prompt the user to enter a number 'm' and convert it to a floating-point number\n", "m = float(input('Enter a number: '))\n", "\n", "# Step 3: Prompt the user to enter a base value 'n' and convert it to a floating-point number\n", "n = float(input('Enter a base value: '))\n", "\n", "# Step 4: Compute the logarithm of 'm' with base 'n' using 'math.log()' and print the result\n", "print('math.log(', m, ',', n, ') → ', math.log(m, n), sep='')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Compute a factorial function\n", "\n", "# Step 1: Import the 'math' library\n", "import math\n", "\n", "# Step 2: Prompt the user to enter a number 'n' and convert it to an integer\n", "n = int(float(input('Enter a number: ')))\n", "\n", "# Step 3: Compute the factorial of 'n' using 'math.factorial()' and print the result\n", "print(n, '! → ', math.factorial(n), sep='')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Compute a great common divisor (GCD) function\n", "\n", "# Step 1: Import the 'math' library\n", "import math\n", "\n", "# Step 2: Prompt the user to enter two numbers 'm' and 'n' and convert them to integers\n", "m = int(float(input('Enter a number #1: ')))\n", "n = int(float(input('Enter a number #2: ')))\n", "\n", "# Step 3: Compute the greatest common divisor (GCD) of 'm' and 'n' using 'math.gcd()' and print the result\n", "print('math.gcd(', m, ',', n, ') → ', math.gcd(m, n), sep='')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Compute a square root function\n", "\n", "# Step 1: Import the 'math' library\n", "import math\n", "\n", "# Step 2: Prompt the user to enter a number 'n' and convert it to a floating-point number\n", "n = float(input('Enter a number: '))\n", "\n", "# Step 3: Compute the square root of 'n' using 'math.sqrt()' and print the result\n", "print('math.sqrt(', n, ') → ', math.sqrt(n), sep='')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Compute floor and ceil functions\n", "\n", "# Step 1: Import the 'math' library\n", "import math\n", "\n", "# Step 2: Prompt the user to enter a number with decimal points and convert it to a floating-point number\n", "n = float(input('Enter a number with decimal points: '))\n", "\n", "# Step 3: Round the number to the nearest integer using the built-in 'round()' function\n", "print('round(', n, ', 0) → ', round(n, 0), sep='')\n", "\n", "# Step 4: Round the number down to the nearest integer using 'math.floor()'\n", "print('math.floor(', n, ') → ', math.floor(n), sep='')\n", "\n", "# Step 5: Round the number up to the nearest integer using 'math.ceil()'\n", "print('math.ceil(', n, ') → ', math.ceil(n), sep='')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## MODULES - RANDOM" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# The random module provides many commonly used random functions\n", "\n", "# Step 1: Import the 'random' module\n", "import random\n", "\n", "# Step 2: Initialize randomness (optional)\n", "random.seed() # You can provide a seed value inside the parentheses if needed" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Compute a random from 0 to 1 - floating point\n", "\n", "# Step 1: Import the 'random' module\n", "import random\n", "\n", "# Step 2: Generate and print five random floating-point numbers in the range [0, 1)\n", "for i in range(0, 5):\n", " print('random.random() →', random.random())" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Compute a random from a range [m,n) (n is excluded!) - integer\n", "# The randrange() method returns a randomly selected element from the specified range.\n", "\n", "# Step 1: Import the 'random' module\n", "import random\n", "\n", "# Step 2: Prompt the user to enter a starting number 'm' and an ending number 'n', both as floating-point numbers\n", "m = float(input('Enter a starting number: '))\n", "n = float(input('Enter an ending number: '))\n", "\n", "# Step 3: Generate and print five random integers within the range [m, n) using 'random.randrange()'\n", "for i in range(0, 5):\n", " print('random.randrange(', m, ',', n, ') → ', random.randrange(m, n), sep='')\n", "\n", "# Step 4: Generate and print five random integers within the range [m, n) with a specific step (step = 2)\n", "for i in range(0, 5):\n", " print('random.randrange(', m, ',', n, ', 2) → ', random.randrange(m, n, 2), sep='')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Compute a random from a range [m,n] (n is included!) - integer \n", "# The randint() method returns an integer number selected element from the specified range.\n", "\n", "# Step 1: Import the 'random' module\n", "import random\n", "\n", "# Step 2: Prompt the user to enter a starting number 'm' and an ending number 'n', both as floating-point numbers\n", "m = float(input('Enter a starting number: '))\n", "n = float(input('Enter an ending number: '))\n", "\n", "# Step 3: Generate and print five random integers within the range [m, n] using 'random.randint()'\n", "for i in range(0, 5):\n", " print('random.randint(', m, ',', n, ') → ', random.randint(m, n), sep='')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Random a floating point number with uniform distribution.\n", "\n", "# Step 1: Import the 'random' module\n", "import random\n", "\n", "# Step 2: Prompt the user to enter a starting number 'm' and an ending number 'n', both as floating-point numbers\n", "m = float(input('Enter a starting number: '))\n", "n = float(input('Enter an ending number: '))\n", "\n", "# Step 3: Generate and print five random floating-point numbers with a uniform distribution within the range [m, n) using 'random.uniform()'\n", "for i in range(0, 5):\n", " print('random.uniform(', m, ',', n, ') → ', random.uniform(m, n), sep='')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Random a floating point number with gaussian distribution.\n", "\n", "# Step 1: Import the 'random' module\n", "import random\n", "\n", "# Step 2: Prompt the user to enter a mean (mu) and a standard deviation (sigma) as floating-point numbers\n", "mu = float(input('Enter the mean (mu): '))\n", "sigma = float(input('Enter the standard deviation (sigma): '))\n", "\n", "# Step 3: Generate and print five random floating-point numbers with a Gaussian distribution\n", "# The 'mu' and 'sigma' values should be used as arguments to 'random.gauss()'\n", "for i in range(0, 5):\n", " print('random.gauss(', mu, ',', sigma, ') → ', random.gauss(mu, sigma), sep='')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Random an item in a string\n", "\n", "# Step 1: Import the 'random' module\n", "import random\n", "\n", "# Step 2: Define a list of possible pets\n", "possiblePets = ['bat', 'cat', 'dog', 'fish']\n", "\n", "# Step 3: Print the list of possible pets\n", "print('possiblePets =', possiblePets)\n", "\n", "# Step 4: Generate and print five random pet names using 'random.choice(possiblePets)'\n", "for i in range(0, 5):\n", " print('random.choice(possiblePets) →', random.choice(possiblePets))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Shuffle the order of items in a string\n", "\n", "# Step 1: Import the 'random' module\n", "import random\n", "\n", "# Step 2: Define a list of cards\n", "cards = ['Jack', 'Queen', 'King', 'Ace']\n", "\n", "# Step 3: Print the original order of cards\n", "print('cards =', cards)\n", "\n", "# Step 4: Generate and print five shuffled orders of cards using 'random.shuffle(cards)'\n", "for i in range(0, 5):\n", " random.shuffle(cards)\n", " print('random.shuffle(cards) →', cards)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## MODULES - STATISTICS" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# https://www.w3schools.com/python/module_statistics.asp\n", "\n", "# Python has a built-in module that you can use to calculate mathematical statistics of numeric data." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Mean\n", "\n", "# Step 1: Import the 'statistics' module\n", "import statistics\n", "\n", "# Step 2: Define a list of values\n", "x = [1, 2, 3, 4, 5, 6]\n", "\n", "# Step 3: Print the list of values\n", "print('x =', x)\n", "\n", "# Step 4: Calculate and print the mean of the list using 'statistics.mean(x)'\n", "print('statistics.mean(x) →', statistics.mean(x))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Median\n", "\n", "# Step 1: Import the 'statistics' module\n", "import statistics\n", "\n", "# Step 2: Define a list of values\n", "x = [1, 2, 3, 4, 5, 6]\n", "\n", "# Step 3: Print the list of values\n", "print('x =', x)\n", "\n", "# Step 4: Calculate and print the median of the list using 'statistics.median(x)'\n", "print('statistics.median(x) →', statistics.median(x))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Variance\n", "\n", "# Step 1: Import the 'statistics' module\n", "import statistics\n", "\n", "# Step 2: Define a list of values\n", "x = [1, 2, 3, 4, 5, 6]\n", "\n", "# Step 3: Print the list of values\n", "print('x =', x)\n", "\n", "# Step 4: Calculate and print the variance of the list using 'statistics.variance(x)'\n", "print('statistics.variance(x) →', statistics.variance(x))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Standard deviation\n", "\n", "# Step 1: Import the 'statistics' module\n", "import statistics\n", "\n", "# Step 2: Define a list of values\n", "x = [1, 2, 3, 4, 5, 6]\n", "\n", "# Step 3: Print the list of values\n", "print('x =', x)\n", "\n", "# Step 4: Calculate and print the variance of the list using 'statistics.variance(x)'\n", "print('statistics.variance(x) →', statistics.variance(x))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## MODULES - DATE & TIME" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# https://www.w3schools.com/python/python_datetime.asp\n", "\n", "# A date in Python is not a data type of its own, but we can import a module named datetime to work with dates as date objects." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Show a current date, time, year, month, day, hour, minute, second, microsecond\n", "\n", "# Step 1: Import the 'datetime' module\n", "from datetime import datetime\n", "\n", "# Step 2: Get the current date and time\n", "now = datetime.now()\n", "\n", "# Step 3: Print individual components\n", "print('Date =', now.date()) # Print the current date\n", "print('Time =', now.time()) # Print the current time\n", "print('Year =', now.year) # Print the current year\n", "print('Month =', now.month) # Print the current month\n", "print('Day =', now.day) # Print the current day of the month\n", "print('Hour =', now.hour) # Print the current hour\n", "print('Minute =', now.minute) # Print the current minute\n", "print('Second =', now.second) # Print the current second\n", "print('Micro Second =', now.microsecond) # Print the current 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": [ "# Open file from the URL\n", "\n", "# Step 1: Import the 'urllib' library\n", "import urllib\n", "\n", "# Step 2: Specify the URL of the file to be opened\n", "url = \"https://piyabute.com/data/research/iris.data.csv\"\n", "\n", "# Step 3: Open the file from the URL\n", "file = urllib.request.urlopen(url)\n", "\n", "# Step 4: Iterate through each line of the file\n", "for line in file:\n", " # Step 5: Decode each line from bytes to a UTF-8 string\n", " decoded_line = line.decode(\"utf-8\")\n", " \n", " # Step 6: Print each decoded line\n", " print(decoded_line)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Open file from a local host\n", "\n", "# Step 1: Open the file \"exams100.csv\" in read mode (\"r\")\n", "my_file = open(\"iris.data.csv\", \"r\")\n", "\n", "# Step 2: Read the entire content of the file\n", "content = my_file.read()\n", "\n", "# Step 3: Print the content of the file\n", "print(content)\n", "\n", "# Step 4: Split the content into a list using commas as separators\n", "content_list = content.split(\",\")\n", "\n", "# Step 5: Close the file\n", "my_file.close()\n", "\n", "# Step 6: Print the content as a list\n", "print(content_list)" ] }, { "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 }