Files
004_comission/jzzzz123/course_materials/Topic_1_Python_Basics_(with answers).ipynb
louiscklaw c0b4825bea update,
2025-01-31 21:12:16 +08:00

5020 lines
136 KiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

{
"cells": [
{
"cell_type": "markdown",
"metadata": {
"id": "WoU1nZS_dk7v"
},
"source": [
"[Whats Markdown?](https://www.markdownguide.org/getting-started)\n",
"\n",
"- Markdown is a lightweight markup language that you can use to add formatting elements to plaintext text documents. You add Markdown syntax to the text to indicate which words and phrases should look different.\n",
"- For example, to denote a heading, you add a number sign before it (e.g., # Heading One). Or to make a phrase bold, you add two asterisks before and after it (e.g., **this text is bold**).\n",
"\n",
"[Basic Syntax](https://www.markdownguide.org/basic-syntax/)\n",
"- Headings, paragraphs, line breaks, emphasis (e.g., bold, italic), lists (ordered and unordered), ..."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "Phm288_2QuAB"
},
"source": [
"<br>\n",
"\n",
"# 1 Operators\n",
"\n",
"In Python, we can directly write <b>*expressions*</b> and Python will generate the results for experessions. Expressions are typically comprised of <b>*operators*</b> and <b>*values*</b>.\n",
"- <b>*operators*</b> are a set of special symbols that carry out computations.\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "iWWlM-PuoUjY"
},
"source": [
"## 1.1 Arithmetic Operators\n",
"\n",
"The <font color='royalblue'><b>*arithmetic operators*</b></font> `+`, `-`, `*`, `/`, and `**` perform addition, subtraction, multiplication, division, and exponentiation:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "RypeFqFAPtDt",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "d00fe752-9362-4994-afd5-0ad30b7b3062"
},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"5.2"
]
},
"metadata": {},
"execution_count": 1
}
],
"source": [
"1.2 + 2 + 2"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "QsLURoqWQAzT",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "f7efc613-c940-495f-9976-dc4bf9ecd580"
},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"10"
]
},
"metadata": {},
"execution_count": 2
}
],
"source": [
"5 * 2"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "JnpFbh7vQCWC",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "0ed1fe74-8e7f-486e-d07b-5241ee8cd6b0"
},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"25"
]
},
"metadata": {},
"execution_count": 3
}
],
"source": [
"5 ** 2 # 5 squared"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "XCmg3g_rfYbW"
},
"source": [
"Parentheses `()` can be used for grouping:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "avNCWAiGP_Qq",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "b80706ca-61a1-4e95-ecbe-8d5d06ade6f3"
},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"2.0"
]
},
"metadata": {},
"execution_count": 4
}
],
"source": [
"(15 - 10) * 2 / 5"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "cbbMUKsJXCwi",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "5ed5004f-ee43-44d0-fb0f-67716d6a1933"
},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"25"
]
},
"metadata": {},
"execution_count": 5
}
],
"source": [
"5 * (3 + 2)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "YcKk6JkSQj6C",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "2574af58-32d2-4945-9e86-d893e0c64c79"
},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"5.666666666666667"
]
},
"metadata": {},
"execution_count": 6
}
],
"source": [
"17 / 3 # division; always return a result with a fractional part"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "wPt_dVQ6QVmq"
},
"source": [
"The `//` operator performs <font color='royalblue'><b>*integer or floored division*</b></font> that keeps only the integer part of the result, while the `%` operator calculates the remainder:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "Cd-L6HR6TFOB",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "74cf92e9-aee3-4f09-defc-e498e9754733"
},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"5"
]
},
"metadata": {},
"execution_count": 7
}
],
"source": [
"17 // 3 # floor division; discard the fractional part"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "720mFJnqQlV-",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "82a57643-58c3-4239-cab3-23ca2101d54d"
},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"2"
]
},
"metadata": {},
"execution_count": 8
}
],
"source": [
"17 % 3 # mod; return the remainder of the division"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "B5aV3QPIXUnM"
},
"source": [
"*Exercise:* From your math classes, you should know $a^2-b^2=(a-b)(a+b)$. Using this information to calculate the result of $19^2-18^2$ in at least two ways."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "5K0SiwgNXcEV",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "4c9ab10b-45c2-4360-c150-619e7c26a4fa"
},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"37"
]
},
"metadata": {},
"execution_count": 9
}
],
"source": [
"# write your codes here, the first way\n",
"19 ** 2 - 18 **2"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "3jD4Y8SzXe-a",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "5cfe7e5f-23bb-4841-ffad-35b7f9634033"
},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"37"
]
},
"metadata": {},
"execution_count": 10
}
],
"source": [
"# the second way\n",
"(19 + 18) * (19 - 18)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "A1w94yVqoed7"
},
"source": [
"## 1.2 Comparison Operators\n",
"\n",
"<font color='royalblue'><b>*Comparison (relational) operators*</b></font> are used to compare values on either sides of them. It returns either of the two <font color='royalblue'><b>*Boolean*</b></font> values, `True` and `False`.\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "KanNkLafVKso"
},
"source": [
"The table summarizes comparision operators:\n",
"\n",
"| Operator | Meaning |\n",
"|----|---|\n",
"| == | Equal to - `True` if both operands are equal |\n",
"| != | Not equal to - `True` if operands are not equal |\n",
"| < | Less than - `True` if left operand is less than the right |\n",
"| > | Greater than - `True` if left operand is greater than the right |\n",
"| <= | Less than or equal to - `True` if left operand is less than or equal to the right |\n",
"| >= | Greater than or equal to - `True` if left operand is greater than or equal to the right |\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "eqSarpzPWPZM",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "eed1d946-f029-4947-dede-5275996dada4"
},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"True"
]
},
"metadata": {},
"execution_count": 11
}
],
"source": [
"2 <= 5"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "vmzrggo7WSjN",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "d238af36-6dad-4240-f2a9-60c5263329f4"
},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"True"
]
},
"metadata": {},
"execution_count": 12
}
],
"source": [
"# chained in the mathematically obvious way\n",
"# it can only be written as 2 < 5 and 5 <= 5.0 in other languages\n",
"\n",
"2 < 5 <= 5.0"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "hbJDcS_BcxBA"
},
"source": [
"*Exercise:* Try to compare whether \"hello\" is equal to \"Hello\""
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "W9qapqupc5AT",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "ead54b27-bded-413a-b5b0-631368d59a2b"
},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"False"
]
},
"metadata": {},
"execution_count": 13
}
],
"source": [
"# write your codes here\n",
"\"hello\" == \"Hello\""
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "y5nz76vPkgP0"
},
"source": [
"## 1.3 Logical Operators\n",
"\n",
"\n",
"### Boolean Values: `True` and `False`\n",
"\n",
"\n",
"In computer science, the **Boolean data type** (`bool` for short in Python) is a data type that can only take on two truth values, `True` or `False`, intended to represent the truth values of logic and Boolean algebra.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"cell_style": "split",
"id": "VYSPDvrnkgP1",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "e823aeed-8f7e-49fe-e34b-00881fea2ac8"
},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"True"
]
},
"metadata": {},
"execution_count": 14
}
],
"source": [
"True # reserved keywords"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"cell_style": "split",
"id": "kREZmZddkgP1",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "106bcfe5-6158-4f3a-d593-4c84f1347379"
},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"False"
]
},
"metadata": {},
"execution_count": 15
}
],
"source": [
"False # reserved keywords"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "2vmnOtMUWmA0"
},
"source": [
"<font color='royalblue'><b>*Logical (Boolean) operators*</b></font> (`and`, `or` and `not`) perform Boolean logic upon two Boolean expressions and return Boolean results (`True` or `False`).\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "bz1ePYtCXu98"
},
"source": [
"Logical operators in Python are summarized as follows. The order indicates the relative levels of precedence (ordered by descending priority):\n",
"\n",
"\n",
"|Operator|Meaning|\n",
"|:-- |:-- |\n",
"|not|True if operand is false (complements the operand)|\n",
"|and|True if both the operands are true|\n",
"|or|True if either of the operands is true|\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "PVa40u5bXILc",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "644fc777-1a5a-477b-8444-630b675f3b7f"
},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"False"
]
},
"metadata": {},
"execution_count": 16
}
],
"source": [
"not True # only require one operand"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "SNXGO_KSXL4E",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "265b4e9a-23eb-4790-b329-ed78adfe50ef"
},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"False"
]
},
"metadata": {},
"execution_count": 17
}
],
"source": [
"False or False"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "6jpZRDSZeM93"
},
"source": [
"*Exerciese:* Do not run the following codes first, predict the returned results of `2 < 5 and not False` and `2 < 5 and 5 < 5.0 or 5 < 1024`."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "ERI2aU_-XPgc",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "a93809df-7e0a-4d77-fc45-9c8950d6d79a"
},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"True"
]
},
"metadata": {},
"execution_count": 18
}
],
"source": [
"2 < 5 and not False"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "7HFvKyHUXjn0",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "efe44a88-43af-4e96-f10c-b539607659e6"
},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"True"
]
},
"metadata": {},
"execution_count": 19
}
],
"source": [
"2 < 5 and 5 < 5.0 or 5 < 1024"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "MXNENMdEgh03"
},
"source": [
"<br>\n",
"\n",
"# 2 Objects and Their Types\n",
"\n",
"Everything in Python is an object, and every object has an <font color='royalblue'><b>*identity*</b></font>, a <font color='royalblue'><b>*type*</b></font>, and a <font color='royalblue'><b>*value*</b></font>.\n",
"\n",
"Python's built-in data types can be found at: https://www.w3schools.com/python/python_datatypes.asp\n",
"\n",
" <img src=\"https://www.dropbox.com/s/akxnl7mc1k768tx/data%20types.png?raw=1\" width=400/>\n",
"\n",
"The built-in function `type()` returns an object's type:\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "ZeDbgQoLhKFw",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "3ec6a378-b69e-4cd4-b5f2-059db1a90f85"
},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"bool"
]
},
"metadata": {},
"execution_count": 20
}
],
"source": [
"type(True)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "m7r7GK88hWB_",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "58336c23-e3ae-4d51-e199-e5586a421fa6"
},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"int"
]
},
"metadata": {},
"execution_count": 21
}
],
"source": [
"type(5**2)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "gTz9SEcohd-R",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "6dca313b-4fbc-4abf-e4f7-d23d7c9ea108"
},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"float"
]
},
"metadata": {},
"execution_count": 22
}
],
"source": [
"type(2.0) # with a decimal point"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "LgnagsKHhfsR",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "3ddaf437-94f6-4e74-a517-f78c41e4cc27"
},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"float"
]
},
"metadata": {},
"execution_count": 23
}
],
"source": [
"type(3.8e15) # with an exponent; base 10"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "g42KHqNVkgP8",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "c8d9f9d9-e498-4f43-8636-67f75a28b037"
},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"float"
]
},
"metadata": {},
"execution_count": 24
}
],
"source": [
"type(15 / 5)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "jNQXiSAegDNV",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "ea91589b-cf1c-47ef-a795-8bb3a3c8a2e6"
},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"3.0"
]
},
"metadata": {},
"execution_count": 25
}
],
"source": [
"15/5"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "mmB_ePaskgP9",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "7b5ddf01-6707-49a2-d1d9-847e9493645e"
},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"int"
]
},
"metadata": {},
"execution_count": 26
}
],
"source": [
"type(17 // 5)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "hXTO9tk2kgP-",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "dab64cb5-8eec-4e14-917a-34867e7a998d"
},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"int"
]
},
"metadata": {},
"execution_count": 27
}
],
"source": [
"type(17 % 3)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "5tYQ9MsV_Uxa"
},
"source": [
"\n",
"\n",
"\n",
"An object's <font color='royalblue'><b>*type*</b></font> determines:\n",
"\n",
"- A domain of possible values, e.g.:\n",
"\n",
" - The `bool` type has only two values, i.e., `True` and `False`;\n",
" - The `int` type represents whole numbers (e.g., `1`, `2`, `-34`, `1024`);\n",
" - The numbers with a decimal point or an exponent (or both) (e.g., `2.0`, `3.2`, `.3`, `3.8e15`) have type `float` (short for floating-point numbers).\n",
" \n",
"- A set of possible operations that can be performed on these values (e.g., arithmetic operations like `+`, `-`, `*`, etc.).\n",
"\n",
"\n",
"\n",
"More genrally, everything in Python is an object.\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "sf62xwIpbAn5"
},
"source": [
"<br>\n",
"\n",
"# 3 Variables\n",
"\n",
"One of the most powerful features of a programming language is the ability to manipulate <font color='royalblue'><b>*variables*</b></font>. In Python, a variable is ***a name that refers to an object***."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "6IvwVp2AzfmM"
},
"source": [
"## 3.1 Declare Variables\n",
"\n",
"Using the equal sign (`=`), an assignment statement defines a variable by\n",
"\n",
"- Evaluating the expression on the right of `=` to construct a new or retrieve an existing object;\n",
"\n",
"- Binding a name on the left of `=` to the object."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "SBENOmJyze4n"
},
"outputs": [],
"source": [
"width = 10"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "wLgxlKXn_9dn"
},
"source": [
"\n",
"\n",
"<img src=\"https://raw.githubusercontent.com/justinjiajia/img/master/python/var1.png\" width=120 />\n",
"\n",
"\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "KFRBAU07z1dP"
},
"outputs": [],
"source": [
"height = 12"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "bF5DNkdIATfY"
},
"source": [
"\n",
"<img src=\"https://raw.githubusercontent.com/justinjiajia/img/master/python/var2.png\" width=120 />"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "AKut-oZOAnJP"
},
"source": [
"When we enter a name in Python, it gives us back the object bound to it:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "kvZtrnqTAmJa",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "007eeda7-5b35-472f-f494-ef5a0929a55b"
},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"10"
]
},
"metadata": {},
"execution_count": 30
}
],
"source": [
"width"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "7-cKOPfaAyW7",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "cf6f7046-2ef2-4463-d05f-eef52cc9e447"
},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"12"
]
},
"metadata": {},
"execution_count": 31
}
],
"source": [
"height"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "MjR9TY7XA3cn"
},
"outputs": [],
"source": [
"area = width * height"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "tlLM4RJLBC9g"
},
"source": [
"\n",
"\n",
"<img src=\"https://raw.githubusercontent.com/justinjiajia/img/master/python/expr1.png\" width=300 />"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "X2j-k9u4BUVd",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "4e8973c3-7fc4-4e90-c3a6-f07c2f785bfa"
},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"120"
]
},
"metadata": {},
"execution_count": 33
}
],
"source": [
"area"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "QikJF5GOBe99"
},
"outputs": [],
"source": [
"width = width + 5"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "irIEx66tBiM5"
},
"source": [
"\n",
"\n",
"\n",
"<img src=\"https://raw.githubusercontent.com/justinjiajia/img/master/python/expr2.png\" width=185 />"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "h6MRm9TPBhZh",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "3ec35745-e9c8-41e7-8ae6-9f5b742457b6"
},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"15"
]
},
"metadata": {},
"execution_count": 35
}
],
"source": [
"width"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "On_EWQlKB8iD"
},
"source": [
"\n",
"## 3.2 Compound/Augmented Assignment Operators\n",
"\n",
"`width = width + 5` examplifies a very common operation. Python provides a shorthand operator, `+=`, to express it more cleanly:\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "4L5qnWhITmeO",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "6da7e4a6-d7cf-4fe9-c5c0-ba681895100e"
},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"20"
]
},
"metadata": {},
"execution_count": 36
}
],
"source": [
"width += 5\n",
"width"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "0-4_9z7MTpob"
},
"source": [
"Similar <font color='royalblue'><b>*compound/augmented assignment operators*</b></font> include `-=`, `*=`, `%=`, and so on:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "gOXuHqraT8L1",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "f2b02950-951d-4ba5-f51a-97cb1402e3eb"
},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"4.0"
]
},
"metadata": {},
"execution_count": 37
}
],
"source": [
"width /= 5; width"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "O7ONE_IvCyxZ"
},
"source": [
"**<font color='steelblue' > Question </font>**: What is the value of `j` after evaluating `i += 7`?"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "WvRorN0xlMSn",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "db9f1f63-38ca-46e1-c77a-a70be81551fe"
},
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"i= 12\n",
"j= 5\n"
]
}
],
"source": [
"i = 5\n",
"j = i\n",
"i += 7\n",
"\n",
"#write codes to check value of i and j\n",
"print(\"i=\", i)\n",
"print(\"j=\", j)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "p3cs5dftIv8n"
},
"source": [
"\n",
"\n",
"## 3.3 Naming Conventions\n",
"\n",
"Python has some rules to follow when forming a variable name:\n",
"\n",
"- Can contain both letters (uppercase or lowercase), digits (but cannot start with a number), and the underscore character (_).\n",
"\n",
"- Python's keywords cannot be used as variable names, because the Python interpreter uses them to recognize the structure of the program."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "ShlXtEoPkgQO",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 141
},
"outputId": "58a37b95-0266-4a70-f51d-7be9da0b4054"
},
"outputs": [
{
"output_type": "error",
"ename": "SyntaxError",
"evalue": "cannot assign to True (<ipython-input-39-da5279a5acf3>, line 1)",
"traceback": [
"\u001b[0;36m File \u001b[0;32m\"<ipython-input-39-da5279a5acf3>\"\u001b[0;36m, line \u001b[0;32m1\u001b[0m\n\u001b[0;31m True = 49.2\u001b[0m\n\u001b[0m ^\u001b[0m\n\u001b[0;31mSyntaxError\u001b[0m\u001b[0;31m:\u001b[0m cannot assign to True\n"
]
}
],
"source": [
"True = 49.2"
]
},
{
"cell_type": "markdown",
"source": [
"Python also provides a keyword module for working with Python keywords in a programmatic way. `kwlist` provides a list of all the Python keywords for the version of Python youre running."
],
"metadata": {
"id": "xLfiwOo6MUFU"
}
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "_tnr7Se7IzzC",
"outputId": "2625394c-1b66-4415-c776-f311d4186bcc"
},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"['False',\n",
" 'None',\n",
" 'True',\n",
" 'and',\n",
" 'as',\n",
" 'assert',\n",
" 'async',\n",
" 'await',\n",
" 'break',\n",
" 'class',\n",
" 'continue',\n",
" 'def',\n",
" 'del',\n",
" 'elif',\n",
" 'else',\n",
" 'except',\n",
" 'finally',\n",
" 'for',\n",
" 'from',\n",
" 'global',\n",
" 'if',\n",
" 'import',\n",
" 'in',\n",
" 'is',\n",
" 'lambda',\n",
" 'nonlocal',\n",
" 'not',\n",
" 'or',\n",
" 'pass',\n",
" 'raise',\n",
" 'return',\n",
" 'try',\n",
" 'while',\n",
" 'with',\n",
" 'yield']"
]
},
"metadata": {},
"execution_count": 40
}
],
"source": [
"import keyword\n",
"keyword.kwlist"
]
},
{
"cell_type": "code",
"source": [
"len(keyword.kwlist)"
],
"metadata": {
"id": "WDEGWzr4M2Jd",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "d75149db-9449-447f-d00d-7ad257e6f998"
},
"execution_count": null,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"35"
]
},
"metadata": {},
"execution_count": 41
}
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "Me5gSdwFmAHN"
},
"source": [
"*Exercise:* Try to **violate** each naming rules by defining several new variables"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "flPCDbYel82z",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 141
},
"outputId": "bd71a9cb-93ff-4fdd-dadf-007eb9a4e2f3"
},
"outputs": [
{
"output_type": "error",
"ename": "SyntaxError",
"evalue": "invalid decimal literal (<ipython-input-42-19a99b08a5d1>, line 2)",
"traceback": [
"\u001b[0;36m File \u001b[0;32m\"<ipython-input-42-19a99b08a5d1>\"\u001b[0;36m, line \u001b[0;32m2\u001b[0m\n\u001b[0;31m 1day = 'Monday'\u001b[0m\n\u001b[0m ^\u001b[0m\n\u001b[0;31mSyntaxError\u001b[0m\u001b[0;31m:\u001b[0m invalid decimal literal\n"
]
}
],
"source": [
"# write your codes here\n",
"1day = 'Monday'"
]
},
{
"cell_type": "code",
"source": [
"course$ = 100"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/",
"height": 141
},
"id": "DYSeBUjLOskk",
"outputId": "62231c40-741f-4e15-d24e-74324d47f5b0"
},
"execution_count": null,
"outputs": [
{
"output_type": "error",
"ename": "SyntaxError",
"evalue": "invalid syntax (<ipython-input-43-f3b72d74310c>, line 1)",
"traceback": [
"\u001b[0;36m File \u001b[0;32m\"<ipython-input-43-f3b72d74310c>\"\u001b[0;36m, line \u001b[0;32m1\u001b[0m\n\u001b[0;31m course$ = 100\u001b[0m\n\u001b[0m ^\u001b[0m\n\u001b[0;31mSyntaxError\u001b[0m\u001b[0;31m:\u001b[0m invalid syntax\n"
]
}
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "i4CtL_zIJBGl"
},
"source": [
"A good coding style requires a variable name to be ***descriptive*** and ***mnemonic***."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "cufjK1xrkgQP"
},
"outputs": [],
"source": [
"course_name = \"Business Applications Development in Python\"\n",
"course_code = \"ISOM3400\"\n",
"course_is_elective = True"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "KmMYRvsjKOgV"
},
"source": [
"\n",
"## 3.4 Namespaces\n",
"\n",
"A <font color=\"royalblue\"><b>*namespace*</b></font> is a <font color=\"royalblue\"><b>*mapping from names to objects*</b></font> in a specific programming context, and can be conceptualized as an \"invisible dictionary\".\n",
"\n",
"The built-in function `dir()`, when called without arguments,\n",
"returns the list of all the names (functions and variables) belonging to the namespace from where it is called.\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "eLtxL5ERkgRD"
},
"outputs": [],
"source": [
"a_trial_variable = 'will be deleted soon'"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "1iBiLVbUkgRD",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "d61d53b9-7818-435e-d431-da5d31196699"
},
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"['In', 'Out', '_', '_1', '_10', '_11', '_12', '_13', '_14', '_15', '_16', '_17', '_18', '_19', '_2', '_20', '_21', '_22', '_23', '_24', '_25', '_26', '_27', '_3', '_30', '_31', '_33', '_35', '_36', '_37', '_4', '_40', '_41', '_5', '_6', '_7', '_8', '_9', '__', '___', '__builtin__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', '_dh', '_i', '_i1', '_i10', '_i11', '_i12', '_i13', '_i14', '_i15', '_i16', '_i17', '_i18', '_i19', '_i2', '_i20', '_i21', '_i22', '_i23', '_i24', '_i25', '_i26', '_i27', '_i28', '_i29', '_i3', '_i30', '_i31', '_i32', '_i33', '_i34', '_i35', '_i36', '_i37', '_i38', '_i39', '_i4', '_i40', '_i41', '_i42', '_i43', '_i44', '_i45', '_i5', '_i6', '_i7', '_i8', '_i9', '_ih', '_ii', '_iii', '_oh', 'a_trial_variable', 'area', 'exit', 'get_ipython', 'height', 'i', 'j', 'keyword', 'quit', 'width']\n"
]
}
],
"source": [
"print(dir())"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "Es2CpRk1pfA3"
},
"source": [
"Deleting a name using [the `del` statement](https://docs.python.org/3/reference/simple_stmts.html#del) removes the name from the namespace:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "GUQ9DH8rpjgH"
},
"outputs": [],
"source": [
"del a_trial_variable"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "euHag_VlqBiV",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "6fca2356-268f-45fc-f5ed-f475f12f7553"
},
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"['In', 'Out', '_', '_1', '_10', '_11', '_12', '_13', '_14', '_15', '_16', '_17', '_18', '_19', '_2', '_20', '_21', '_22', '_23', '_24', '_25', '_26', '_27', '_3', '_30', '_31', '_33', '_35', '_36', '_37', '_4', '_40', '_41', '_5', '_6', '_7', '_8', '_9', '__', '___', '__builtin__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', '_dh', '_i', '_i1', '_i10', '_i11', '_i12', '_i13', '_i14', '_i15', '_i16', '_i17', '_i18', '_i19', '_i2', '_i20', '_i21', '_i22', '_i23', '_i24', '_i25', '_i26', '_i27', '_i28', '_i29', '_i3', '_i30', '_i31', '_i32', '_i33', '_i34', '_i35', '_i36', '_i37', '_i38', '_i39', '_i4', '_i40', '_i41', '_i42', '_i43', '_i44', '_i45', '_i46', '_i47', '_i5', '_i6', '_i7', '_i8', '_i9', '_ih', '_ii', '_iii', '_oh', 'area', 'exit', 'get_ipython', 'height', 'i', 'j', 'keyword', 'quit', 'width']\n"
]
}
],
"source": [
"print(dir())"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "eNxfVQDLkgRF",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 176
},
"outputId": "b5a1babc-8e46-4c9e-d6a2-77098a4ccd55"
},
"outputs": [
{
"output_type": "error",
"ename": "NameError",
"evalue": "name 'a_trial_variable' is not defined",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)",
"\u001b[0;32m<ipython-input-48-eb4c8d65befc>\u001b[0m in \u001b[0;36m<cell line: 1>\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0ma_trial_variable\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[0;31mNameError\u001b[0m: name 'a_trial_variable' is not defined"
]
}
],
"source": [
"a_trial_variable"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "UrBXNrXAqJVg"
},
"source": [
"When objects become unreachable, they can be garbage-collected."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "M9I_J0oShEYH"
},
"source": [
"<br>\n",
"\n",
"# 4 Functions"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "Xro--X1T3eTI"
},
"source": [
"> Programming = Data + Function"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "u6HfueVZjpKJ"
},
"source": [
"A function is a machine which turns input objects (called the arguments) into an output object (called the return value), according to a definite rule (defined somewhere for this function).\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "JrxKY81ZKC29"
},
"source": [
"\n",
"\n",
"We can draw an analogy of a programming function to a mathematical function.\n",
"\n",
"\n",
"\n",
"Consider $f(a,b)=a^2+b^2$:\n",
"\n",
"- A function definition usually associates a name (i.e., $f$) with a sequence of statements that performs a computation (i.e., $a^2+b^2$).\n",
"\n",
"- Once a function is defined, we can \"call\" it by name with necessary inputs provided (i.e., $f(3,5)$).\n",
"\n",
"- When a function is called or invoked, Python goes back and looks up its definition, executes the code inside the function definition (i.e., $3^2+5^2$), and return an output (i.e., $34$)."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "MZQ6tHCEkisI"
},
"source": [
"Python provides a number of [**built-in functions**](https://docs.python.org/3/library/functions.html) that we can use without needs to provide the function definition as well as import a module:\n",
"\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "Mnv9aYZojO0f",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "ce55c851-a074-4ab2-82b9-0183271cf5ab"
},
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"hello world\n"
]
}
],
"source": [
"print('hello world') # print object"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "cjNAbpeEkh5T",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "c6c94ee5-3a85-4ee3-c21c-2d3a6ab75295"
},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"5.11"
]
},
"metadata": {},
"execution_count": 50
}
],
"source": [
"abs(-5.11) # return the absolute value of a number"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "N1ZsRVzojTwL",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "3c9b7028-6cb1-4725-a9fa-053a511f30c4"
},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"4.56"
]
},
"metadata": {},
"execution_count": 51
}
],
"source": [
"round(4.55892, 2) # return number (1st argument) rounded to ndigits (2nd argument) precision after the decimal point."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "grA9RkhcciRw",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "b1e19868-ee3d-4c67-8db4-db2069bb9d48"
},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"8"
]
},
"metadata": {},
"execution_count": 52
}
],
"source": [
"pow(2, 3) # return base (1st argument) to the power exp (2nd argument)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "CSakjCYCkpQw",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "42850447-9909-443c-d4ef-f04b837278f5"
},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"5"
]
},
"metadata": {},
"execution_count": 53
}
],
"source": [
"max(1, 2, 3, 4, 5) # return the largest item"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "4DKmmVGZkrGr",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "bc6456c6-7906-4562-de72-21e03c119d90"
},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"1"
]
},
"metadata": {},
"execution_count": 54
}
],
"source": [
"min(1, 2, 3, 4, 5) # return the smallest item"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "sDxEWDKoku3I",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "161fe355-b0ff-4543-b9bb-f9608a18efd7"
},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"(4, 1)"
]
},
"metadata": {},
"execution_count": 55
}
],
"source": [
"divmod(9, 2) # return the quotient and remainder when using integer division"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "V2Rzriz9lTba"
},
"source": [
"Typing a function's name without `()` echos \"the value\" or more precisely the <font color=\"royalblue\">**string representation**</font> of the function:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "qBN9YyLJlT7p",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "bc91d4d7-c413-497f-8629-37412ac66a2c"
},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"<function max>"
]
},
"metadata": {},
"execution_count": 57
}
],
"source": [
"max"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "MGbmYUX6k6cy"
},
"source": [
"If the usage of a function is unknown, we can call `help()` to print help for the function:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "ToI27i89k53w",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "045dd0bd-1a47-43b2-d9eb-a0b0caf196bd"
},
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Help on built-in function max in module builtins:\n",
"\n",
"max(...)\n",
" max(iterable, *[, default=obj, key=func]) -> value\n",
" max(arg1, arg2, *args, *[, key=func]) -> value\n",
" \n",
" With a single iterable argument, return its biggest item. The\n",
" default keyword-only argument specifies an object to return if\n",
" the provided iterable is empty.\n",
" With two or more arguments, return the largest argument.\n",
"\n"
]
}
],
"source": [
"help(max)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "QNvvdDDqiwVD"
},
"source": [
"<br>\n",
"\n",
"# 5 Strings\n",
"\n",
"Besides numbers and Booleans, Python can also manipulate strings, which are sequences of characters.\n",
"\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "CRrNZhsscuSF"
},
"source": [
"\n",
"## 5.1 String Literals\n",
"\n",
"Strings are constructed by enclosing a sequence of characters in single quotes (`'`) or double quotes (`\"`):"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "V6Ti7K6MjIgz",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 35
},
"outputId": "399993c0-66ea-422d-e261-1c8684e779a2"
},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"'Welcome to Python Programming'"
],
"application/vnd.google.colaboratory.intrinsic+json": {
"type": "string"
}
},
"metadata": {},
"execution_count": 61
}
],
"source": [
"'Welcome to Python Programming'"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "AfnfgbhzjL-G",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 35
},
"outputId": "5cddf2ac-7f8b-4e99-a55b-5705e1fddcc4"
},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"'Welcome to Python Programming'"
],
"application/vnd.google.colaboratory.intrinsic+json": {
"type": "string"
}
},
"metadata": {},
"execution_count": 59
}
],
"source": [
"\"Welcome to Python Programming\""
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "F1eHBZnWjbw-"
},
"source": [
" Single quoted strings can contain double quotes, and vice versa"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "Ba1AIO3ijbBV"
},
"outputs": [],
"source": [
"\"Programming isn't hard.\""
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "9H-jsam6jx62"
},
"outputs": [],
"source": [
"'\"Yes\", they said.'"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "T87y5hj0oMbG"
},
"outputs": [],
"source": [
"strr='\"Yes\", they said.' # assign this string to a variable strr"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "7E7icLAZoQK6",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 35
},
"outputId": "1b506e4c-6228-4bc0-8bc5-4a0b53bbcacc"
},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"'\"Yes\", they said.'"
],
"application/vnd.google.colaboratory.intrinsic+json": {
"type": "string"
}
},
"metadata": {},
"execution_count": 63
}
],
"source": [
"strr"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "c6pInT4pjLMw"
},
"source": [
"**<font color='steelblue' > Question </font>**: What if we have to use single (double) quotes literally in a single(double)-quoted string? Escape their special behaviors with backslashes (`\\`):"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "-AwV8aCilKaa",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 35
},
"outputId": "e688465e-c0db-4404-f626-2d038dcc88fe"
},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"'\"No, it isn\\'t\", they said'"
],
"application/vnd.google.colaboratory.intrinsic+json": {
"type": "string"
}
},
"metadata": {},
"execution_count": 66
}
],
"source": [
"'\"No, it isn\\'t\", they said'"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "nNfogqwso04V"
},
"source": [
"*Exercise:* Try to create a string value with both single and double quotes, and check what you will get by not using backslash to escape the quotes."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "xDFmB_gRo3Cf",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 141
},
"outputId": "43b68f7f-f3a8-4a5e-ba66-13cc7368951c"
},
"outputs": [
{
"output_type": "error",
"ename": "SyntaxError",
"evalue": "unterminated string literal (detected at line 2) (<ipython-input-68-5b8dbab51113>, line 2)",
"traceback": [
"\u001b[0;36m File \u001b[0;32m\"<ipython-input-68-5b8dbab51113>\"\u001b[0;36m, line \u001b[0;32m2\u001b[0m\n\u001b[0;31m 'Jenny told me, \"Charels didn't come yesterday\"'\u001b[0m\n\u001b[0m ^\u001b[0m\n\u001b[0;31mSyntaxError\u001b[0m\u001b[0;31m:\u001b[0m unterminated string literal (detected at line 2)\n"
]
}
],
"source": [
"# write your codes here\n",
"'Jenny told me, \"Charels didn't come yesterday\"'"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "LpMpaBA_oE7M"
},
"source": [
"When we press the <kbd class=\"\">Enter</kbd> key, a <b>*newline character*</b> (`\\n`) is generated to signify the end of a line. But Python uses newlines to delineate statements.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "J4GTuWvnJmFf",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 141
},
"outputId": "092e91c0-e001-4141-e6d7-ed04bfbcfd4c"
},
"outputs": [
{
"output_type": "error",
"ename": "SyntaxError",
"evalue": "unterminated string literal (detected at line 1) (<ipython-input-69-ddc1acafbb91>, line 1)",
"traceback": [
"\u001b[0;36m File \u001b[0;32m\"<ipython-input-69-ddc1acafbb91>\"\u001b[0;36m, line \u001b[0;32m1\u001b[0m\n\u001b[0;31m 'Python Programming\u001b[0m\n\u001b[0m ^\u001b[0m\n\u001b[0;31mSyntaxError\u001b[0m\u001b[0;31m:\u001b[0m unterminated string literal (detected at line 1)\n"
]
}
],
"source": [
"'Python Programming\n",
"for Business Analytics'"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "j5cdIus6oRVt"
},
"source": [
"\n",
"\n",
"\n",
"One way to make a string literal span multiple lines is to write it inside triple quotes, `\"\"\"` or `'''`:\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "Pn3HvXgNkgQZ",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 35
},
"outputId": "5f4a3597-8dc9-4d5a-f1af-6b0641664593"
},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"'Python Programming\\nfor Business Analytics'"
],
"application/vnd.google.colaboratory.intrinsic+json": {
"type": "string"
}
},
"metadata": {},
"execution_count": 70
}
],
"source": [
"'''Python Programming\n",
"for Business Analytics''' # a newline (\\n) is automatically included in it"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "80Z6XJTd2w1p"
},
"source": [
"We can also use `()` to combine multiple string literals (possibly spanning multiple lines) into one:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "glLybREa2vga",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 35
},
"outputId": "15b5ff98-5f14-4272-e5e6-99b49573acd7"
},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"'Python Programming for Business Analytics'"
],
"application/vnd.google.colaboratory.intrinsic+json": {
"type": "string"
}
},
"metadata": {},
"execution_count": 71
}
],
"source": [
"(\"Python Programming \"\n",
"\"for Business Analytics\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "F0xQ03GJozSo"
},
"source": [
"`print()` is used to display the actual content represented by a string literal:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "IbVBCtkaorVQ",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "57bf2c50-148b-4938-ecdc-8dc8f2410320"
},
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Python Programming\n",
"for Business Analytics\n"
]
}
],
"source": [
"print('Python Programming\\nfor Business Analytics')"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "3-m8yOGEkIrs"
},
"source": [
"\n",
"## 5.2 Escape Sequences\n",
"\n",
"An <font color='royalblue'><b>*escape sequence*</b></font> (of characters) can be used to denote a special character which cannot be typed easily on a keyboard or one which has been reserved for other purposes.\n",
"\n",
"Some common escape sequences include:\n",
"\n",
"|Sequence|Meaning|\n",
"|:-- |:-- |\n",
"|`\\\\`|literal backslash|\n",
"|`\\'`|single quote|\n",
"|`\\\"`|double quote|\n",
"|`\\t`|tab|\n",
"|`\\n`|newline|"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "FEdpi9m0qKLV"
},
"source": [
"**<font color='steelblue' > Question </font>**: How to print the following using escape sequences:\n",
"\n",
"`I don't think \"a\" is equal to \"A\" in 'Python'`"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "wE0BJQ0hjQH7",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "c9cc4f59-36ab-49e5-8006-fd86dca82ee5"
},
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"I don't think \"a\" is equal to \"A\" in 'Python'\n"
]
}
],
"source": [
"print('I don\\'t think \"a\" is equal to \"A\" in \\'Python\\'') # write the string here"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "ABgZhk3XsBu6"
},
"source": [
"We can make a string literal span multiple lines by including a backslash character \\ at the end of each line to escape the newline (\\n):"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "lNzPg2qBsE28",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 35
},
"outputId": "76b25717-191e-416f-f2dd-c7d9ee1914f4"
},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"'Python Programming for Business Analytics'"
],
"application/vnd.google.colaboratory.intrinsic+json": {
"type": "string"
}
},
"metadata": {},
"execution_count": 74
}
],
"source": [
"'Python Programming \\\n",
"for Business Analytics'"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "jl_Af1ZYsN9y"
},
"source": [
"*Exercise:* Try to predict what the string will be like if we print it\n",
"\n",
"```\n",
"\"\\\"Python is fast enough for our site and allows us to produce maintainable features in record times, \\\n",
"with a minimum of developers,\\\" \\n said Cuong Do, Software Architect, YouTube.com.\"\n",
"```"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "jgfuQVafsuCU",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "ea8ae637-8740-4907-8f67-ec9f1dc16e9c"
},
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"\"Python is fast enough for our site and allows us to produce maintainable features in record times, with a minimum of developers,\" \n",
" said Cuong Do, Software Architect, YouTube.com.\n"
]
}
],
"source": [
"# write codes to verify your prediction\n",
"print(\"\\\"Python is fast enough for our site and allows us to produce maintainable features in record times, \\\n",
"with a minimum of developers,\\\" \\n said Cuong Do, Software Architect, YouTube.com.\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "MzJ4RGl1lMwa"
},
"source": [
"\n",
"## 5.3 String Operations\n",
"\n",
"In Python, strings have type `str`, which is a special kind of <font color=\"royalblue\"><b>*sequence types*</b></font>. String objects support several operations and built-in functions.\n",
"\n",
"### 5.3.1 Concatenating and multiplying strings\n",
"\n",
"- The operators `+` and `*` works with strings:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "v8RTOGqalwQW"
},
"outputs": [],
"source": [
"course = 'Python Programming'"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "wlmfuAmluW54",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 36
},
"outputId": "b03b9a49-6738-4189-bb1e-b331900a8e0e"
},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"'Python Programming for Business Analtytics'"
],
"application/vnd.google.colaboratory.intrinsic+json": {
"type": "string"
}
},
"metadata": {},
"execution_count": 3
}
],
"source": [
"course + ' for Business Analtytics'"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "O80E3g01l0Pa",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 36
},
"outputId": "78bfa3f3-9b67-4314-f2fc-78c1198f7ad6"
},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"'Python ProgrammingPython Programming'"
],
"application/vnd.google.colaboratory.intrinsic+json": {
"type": "string"
}
},
"metadata": {},
"execution_count": 4
}
],
"source": [
"course * 2"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "_PB18VyAuf-3"
},
"source": [
"- `-` and `/`, however, are incompatible with the `str` type:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "FQWULEMuunYD",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 175
},
"outputId": "7a878934-4c5a-4d65-e33d-ed0c330be02d"
},
"outputs": [
{
"output_type": "error",
"ename": "TypeError",
"evalue": "unsupported operand type(s) for -: 'str' and 'str'",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)",
"\u001b[0;32m<ipython-input-5-9f3c505dd770>\u001b[0m in \u001b[0;36m<cell line: 1>\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mcourse\u001b[0m \u001b[0;34m-\u001b[0m \u001b[0;34m'Programming'\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[0;31mTypeError\u001b[0m: unsupported operand type(s) for -: 'str' and 'str'"
]
}
],
"source": [
"course - 'Programming'"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "MiJQ5z8EupAJ",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 175
},
"outputId": "838e867a-6de9-4886-bee3-384bf9a94475"
},
"outputs": [
{
"output_type": "error",
"ename": "TypeError",
"evalue": "unsupported operand type(s) for /: 'str' and 'int'",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)",
"\u001b[0;32m<ipython-input-6-44ec5a0e38f1>\u001b[0m in \u001b[0;36m<cell line: 1>\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mcourse\u001b[0m \u001b[0;34m/\u001b[0m \u001b[0;36m2\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[0;31mTypeError\u001b[0m: unsupported operand type(s) for /: 'str' and 'int'"
]
}
],
"source": [
"course / 2"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "2gjSArIFutQ9"
},
"source": [
"*Exercise:* Use two strings s1=“little \" s2=\"lamb \" to create a new string s3=\"little lamb little lamb \" by using string concatenation and multiplication."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "2ugD6Wp5zxIx",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 36
},
"outputId": "39975659-50e8-449b-f0c3-646066a4b4be"
},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"'little lamb little lamb '"
],
"application/vnd.google.colaboratory.intrinsic+json": {
"type": "string"
}
},
"metadata": {},
"execution_count": 7
}
],
"source": [
"# write your codes here\n",
"s1=\"little \"\n",
"s2=\"lamb \"\n",
"s3 = (s1 + s2) * 2\n",
"s3"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "Tth7Ic6ymM1y"
},
"source": [
"### 5.3.2 Check substrings\n",
"\n",
"- The <font color=\"royalblue\"><b>*membership operators*</b></font> `in` and `not in` take two strings and return `True` if the first appears as a substring in the second:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "7a2vrvYhmjfl",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "3094dc0e-55b2-4f05-b0b6-0bf06336c865"
},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"False"
]
},
"metadata": {},
"execution_count": 8
}
],
"source": [
"'nan' not in 'banana'"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "5Hb9ckxummUb",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "d4e38ec0-2dd2-4733-d131-176bee6160e1"
},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"True"
]
},
"metadata": {},
"execution_count": 10
}
],
"source": [
"'p' in 'Python Programming'"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "T2IBxjwtmx48"
},
"source": [
"### 5.3.3 Comparing strings\n",
"\n",
"- The comparison operators (e.g., `==`, `>`, `<=`) compare strings ***lexicographically***, the way in which sequences are ordered based on the <b>*alphabetical order*</b> of their component characters:\n",
"\n",
" - In alphabetical ordering, digits come before letters and capital letters come before lowercase letters.\n",
" - i.e., digits (as characters) < uppercase letters < lowercase letters.\n",
" - Compare the leftmost characters first, and generate `True` or `False` if their values differ, or continue until a difference is observed."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "E-VLsEzgmvbc",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "b1d970b8-ad89-43d4-f88a-f309490b70f6"
},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"False"
]
},
"metadata": {},
"execution_count": 11
}
],
"source": [
"'Python Programming' == 'python programming'"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "Up93Axsuo_Pi",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "e717f9fc-8984-48c2-fc70-afff28e06fe5"
},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"True"
]
},
"metadata": {},
"execution_count": 12
}
],
"source": [
"'Python Programming' < 'python programming'"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "KXD159w4pCht",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "471dafcb-02d4-409e-de60-5f30b7121ac4"
},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"False"
]
},
"metadata": {},
"execution_count": 13
}
],
"source": [
"'python programming' < 'python cookbook'"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "chPFfcJKByV_",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "4c4aae07-93b1-4e75-f846-99875daf78a9"
},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"True"
]
},
"metadata": {},
"execution_count": 14
}
],
"source": [
"'9999' < 'A'"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "MM1HpZt5pIw8"
},
"source": [
"### 5.3.4 String length\n",
"\n",
"- `len()` returns the number of characters in a string:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "jIagmUnFpNnz",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "8d422611-226e-46e6-c536-cab13f036adb"
},
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Python Programming\n"
]
},
{
"output_type": "execute_result",
"data": {
"text/plain": [
"18"
]
},
"metadata": {},
"execution_count": 15
}
],
"source": [
"print(course)\n",
"len(course)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "CfSuSowBpPre",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "31c37c52-0fca-4d8b-c8b2-95ae9f3c853f"
},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"4"
]
},
"metadata": {},
"execution_count": 16
}
],
"source": [
"len('True')"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "N1Zw0rpG4mrH"
},
"source": [
"### 5.3.5 String Indexing\n",
"\n",
"A string is a sequence of characters, and is ***reducible*** to the component characters.\n",
"\n",
"The characters in a string are indexed by integers (representing positions in the sequence), and can be individually accessed by using the indexing operator (`[]` that encloses an integer).\n",
"\n",
"The index set contains the integers 0, 1, …, and `len()-1` (<font color=\"royalblue\"><b>*0-based indexing*</b></font>).\n",
"\n",
"<img src=\"https://www.dropbox.com/s/xnh6t9q1kn1gg0g/indexing.png?raw=1\" width=600></img>"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "RLnvuuSw53f8",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 36
},
"outputId": "e1325b0d-7536-460f-976d-225312972ab5"
},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"'Python Programming'"
],
"application/vnd.google.colaboratory.intrinsic+json": {
"type": "string"
}
},
"metadata": {},
"execution_count": 17
}
],
"source": [
"course"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "_xoI_dRr56Tv",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 36
},
"outputId": "d38a0164-cd93-433a-f7a3-62094927f9f9"
},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"'t'"
],
"application/vnd.google.colaboratory.intrinsic+json": {
"type": "string"
}
},
"metadata": {},
"execution_count": 18
}
],
"source": [
"course[2]"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "T7x8Hz4A5-3w"
},
"source": [
"Strings can also be <font color=\"salmon\">***back indexed***</font> using negative integers. Negative indexing counts backward from the end of a sequence and starts from `-1`.\n",
"- i.e., `-1` refers to the last character, `-2` refers to the second-to-last character, and so on"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "X68-bRkA6Fh0",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 36
},
"outputId": "195f51a4-701a-4665-d9db-416dda3d66f2"
},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"'P'"
],
"application/vnd.google.colaboratory.intrinsic+json": {
"type": "string"
}
},
"metadata": {},
"execution_count": 19
}
],
"source": [
"course[-3*6]"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "Yhman6Jv6Klu"
},
"source": [
"Out of range indexing will incur an error:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "iBDoFEpw6LsF",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 175
},
"outputId": "e0c35790-9fd1-479e-c3d5-ca23b7d1c6c3"
},
"outputs": [
{
"output_type": "error",
"ename": "IndexError",
"evalue": "string index out of range",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mIndexError\u001b[0m Traceback (most recent call last)",
"\u001b[0;32m<ipython-input-20-dbd31bb88304>\u001b[0m in \u001b[0;36m<cell line: 1>\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mcourse\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m18\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[0;31mIndexError\u001b[0m: string index out of range"
]
}
],
"source": [
"course[18]"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "h5AsSro86OrJ"
},
"source": [
"*Exercise:* get the first 'o' and the second 'o' in the string course with both positive and negative index."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "kU2im5Pd6Rpt",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 36
},
"outputId": "2d77f3e7-62df-4b88-f2c2-bdfe2aba19ec"
},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"'o'"
],
"application/vnd.google.colaboratory.intrinsic+json": {
"type": "string"
}
},
"metadata": {},
"execution_count": 22
}
],
"source": [
"# write your codes here\n",
"course[4]; course[-14]\n",
"course[9]; course[-9]"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "KWE8nfX86aNf"
},
"source": [
"### 5.3.6 String Slicing\n",
"\n",
"\n",
"Slicing is an operation that extracts a segment of a string (called a **slice**).\n",
"\n",
"The slicing operator `[i:j]` returns the part of the sequence from the element indexed by `i` to the element indexed by `j`, including the first but excluding the last:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "aibL-fcC6lMs",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 36
},
"outputId": "beb89edc-aaef-40c9-efa3-f06e9141298f"
},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"'Python'"
],
"application/vnd.google.colaboratory.intrinsic+json": {
"type": "string"
}
},
"metadata": {},
"execution_count": 23
}
],
"source": [
"course[0:6]"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "q6c693ym6oWg",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 36
},
"outputId": "c7bf0021-8627-4354-af8c-e4386183a657"
},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"'Python'"
],
"application/vnd.google.colaboratory.intrinsic+json": {
"type": "string"
}
},
"metadata": {},
"execution_count": 24
}
],
"source": [
"course[-18:-12]"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "M0CPaHvJ6twD",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 36
},
"outputId": "af2b9e2e-acb3-4321-b20b-cc9bc0f8c5ea"
},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"'Python'"
],
"application/vnd.google.colaboratory.intrinsic+json": {
"type": "string"
}
},
"metadata": {},
"execution_count": 25
}
],
"source": [
"course[0:-12]"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "Qjwp09Nl6xpM",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 36
},
"outputId": "843a14d4-be09-4788-c9f9-087ef49f8f22"
},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"'Programming'"
],
"application/vnd.google.colaboratory.intrinsic+json": {
"type": "string"
}
},
"metadata": {},
"execution_count": 26
}
],
"source": [
"course[-11:18]"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "L3DxydUZ65K2"
},
"source": [
"If the 1st argument is omitted, the slice starts at the beginning of the string; if the 2nd argument is omitted, the slice goes to the end of the string:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "6m5KtA8_7BdB",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 36
},
"outputId": "25ace502-739b-45e0-e76d-8a5939ab0618"
},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"'Programming'"
],
"application/vnd.google.colaboratory.intrinsic+json": {
"type": "string"
}
},
"metadata": {},
"execution_count": 27
}
],
"source": [
"course[-11:]"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "7_hS-20n7DiW",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 36
},
"outputId": "8eab6cda-c7b8-4050-abb4-6bbbe76ac4c0"
},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"'Python'"
],
"application/vnd.google.colaboratory.intrinsic+json": {
"type": "string"
}
},
"metadata": {},
"execution_count": 28
}
],
"source": [
"course[:-12]"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "LW_RC-957F56",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 36
},
"outputId": "feae7bb4-6e1b-4741-93ec-f3389b2b0d3c"
},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"'Python Programming'"
],
"application/vnd.google.colaboratory.intrinsic+json": {
"type": "string"
}
},
"metadata": {},
"execution_count": 29
}
],
"source": [
"course[:]"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "rh9KHLG17Juj"
},
"source": [
"*Exericse:* use slicing to get the substring `gram`. Try at least two methods( e.g. positive index, negative index)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "rIJabpSf7L1F",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 36
},
"outputId": "d89a59cf-2817-45f3-b73b-5f933af6b75f"
},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"'gram'"
],
"application/vnd.google.colaboratory.intrinsic+json": {
"type": "string"
}
},
"metadata": {},
"execution_count": 31
}
],
"source": [
"#write your codes here\n",
"course[10:14]\n",
"course[-8:-4]"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "qV-nUdd77cXn"
},
"source": [
"## 5.3.7 Strings are Immutable\n",
"\n",
"Strings in Python is <font color=\"salmon\">***immutable***</font>. That is, the value of string objects cannot change:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "fT027R0B7gUh",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 175
},
"outputId": "c6679f08-d8e3-4818-af7c-bec75dca67a1"
},
"outputs": [
{
"output_type": "error",
"ename": "TypeError",
"evalue": "'str' object does not support item assignment",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)",
"\u001b[0;32m<ipython-input-32-c18cc7006df3>\u001b[0m in \u001b[0;36m<cell line: 1>\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mcourse\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m7\u001b[0m\u001b[0;34m]\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m'p'\u001b[0m \u001b[0;31m# Modifying characters isn't allowed.\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[0;31mTypeError\u001b[0m: 'str' object does not support item assignment"
]
}
],
"source": [
"course[7] = 'p' # Modifying characters isn't allowed."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "6IE0u0x-7jNc"
},
"source": [
"However, this does not mean that we can't change the value of a variable (more precisely, the object that a name refers to). We can assign the variable a new string:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "F1EmKR5-7m1r"
},
"outputs": [],
"source": [
"course = 'ISOM 3400'"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "6lmZf_Sf7647"
},
"source": [
"<img src=\"https://www.dropbox.com/s/rebczlm6cybqjlp/course.png?raw=1\" width=700></img>\n",
"\n",
"An object's <font color=\"royalblue\"><b>*mutability*</b></font> is determined by its type. Numbers and Booleans are also immutable (we will see some mutable data types later)."
]
},
{
"cell_type": "code",
"source": [
"course = 'Python programming'\n",
"course"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/",
"height": 36
},
"id": "p_Ngl0c8zW_o",
"outputId": "0a3127a7-50b4-427b-8eeb-7a331cebcdd2"
},
"execution_count": null,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"'Python programming'"
],
"application/vnd.google.colaboratory.intrinsic+json": {
"type": "string"
}
},
"metadata": {},
"execution_count": 34
}
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "e7hSEzRM1xBw"
},
"source": [
"<br>\n",
"\n",
"## 5.4 String Formatting\n",
"\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "WhDJ3QT9yqBh"
},
"outputs": [],
"source": [
"# using semicolon allows us to write multiple statements on the same line\n",
"shares = 3.2; stock = 'Apple'; price = 443.05"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "NP3gQO8siTNR"
},
"source": [
"To display the contents of these variables, we can pass them as a comma-separated list of argument to `print()`. By default, `print()` separates the content of each argument by a single space and appends a newline to the end of the output:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "sRr5FHF_iv_M",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "4b897992-5c77-4536-dd9e-a5f7def5e223"
},
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"purchase 3.2 shares of Apple at $ 443.05 per share\n"
]
}
],
"source": [
"print('purchase', shares, 'shares of', stock, \"at $\", price, 'per share')"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "i664F9yR4XG1",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "fffae324-e607-4608-980d-0ec062e5fb83"
},
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Help on built-in function print in module builtins:\n",
"\n",
"print(...)\n",
" print(value, ..., sep=' ', end='\\n', file=sys.stdout, flush=False)\n",
" \n",
" Prints the values to a stream, or to sys.stdout by default.\n",
" Optional keyword arguments:\n",
" file: a file-like object (stream); defaults to the current sys.stdout.\n",
" sep: string inserted between values, default a space.\n",
" end: string appended after the last value, default a newline.\n",
" flush: whether to forcibly flush the stream.\n",
"\n"
]
}
],
"source": [
"# access the help system\n",
"help(print)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "oBBnpQhgkFHZ",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "d7b86e16-6acb-4974-b312-e4c839870d5b"
},
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"purchase 3.2 shares of Apple at $ 443.05 per share\tpurchase-3.2-shares of-Apple-at $-443.05-per share\n"
]
}
],
"source": [
"print('purchase', shares, 'shares of', stock, \"at $\", price, 'per share', end='\\t')\n",
"print('purchase', shares, 'shares of', stock, \"at $\", price, 'per share', sep='-')"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "X8s7OvLskM_2"
},
"outputs": [],
"source": [
"with open(\"printout.txt\", \"w\") as f:\n",
" print('purchase', shares, 'shares of', stock, \"at $\", price, 'per share', sep='-', file=f)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "-IOXuP6NiChW"
},
"source": [
"`print() ` supports ouput formatting that is rudimentary at best. In many cases, we'll need more precise control over the appearance of data destined for display.\n",
"\n",
"Python provides several ways to format strings:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "ctXjoHEWEil6"
},
"outputs": [],
"source": [
"f'purchase {shares} shares of {stock} at ${price:.1f} per share' # f-string"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "dvXe9cIlN-SV"
},
"outputs": [],
"source": [
"'purchase {} shares of {} at ${:.1f} per share'.format(shares, stock, price) # format method (optional)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "IUWp27fKlwfx"
},
"outputs": [],
"source": [
"'purchase %d shares of %s at $%.1f per share' % (shares, stock, price) # the % operator; old-style string formatting (optional)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "xfbI4Mk2EKBO"
},
"source": [
"\n",
"### 5.4.1 f-strings\n",
"\n",
"\n",
"\n",
"Python 3.6 added a new string formatting approach called **formatted string literals** or **f-strings**, which provides a simple way to substitute values into strings.\n",
"\n",
"\n",
"\n",
"\n",
"<img src=\"https://raw.githubusercontent.com/justinjiajia/img/master/python/f-string.PNG\" width=500 />\n",
"\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "EMKUainZKQHP",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 36
},
"outputId": "803e1b58-b827-49be-9118-67305629ef88"
},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"'Five divided by ten is 50.00%'"
],
"application/vnd.google.colaboratory.intrinsic+json": {
"type": "string"
}
},
"metadata": {},
"execution_count": 41
}
],
"source": [
"a = 5; b = 10\n",
"f\"Five divided by ten is {a / b :.2%}\""
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "YZtyz4IszltG",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 36
},
"outputId": "4d00c022-c72f-453e-b15b-8bb24823d1a4"
},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"'purchase 11.4 shares of Google at $203.830000 per share'"
],
"application/vnd.google.colaboratory.intrinsic+json": {
"type": "string"
}
},
"metadata": {},
"execution_count": 42
}
],
"source": [
"# Format specifiers are optional\n",
"stock = 'Google'; price = 203.83; shares = 11.4\n",
"f'purchase {shares} shares of {stock} at ${price:f} per share' # The default precision of 'f' is 6."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "XTl3vHW1F547"
},
"source": [
"In order to make a brace appear in your string, we must use double braces:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "HNkdoin3F49y",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 36
},
"outputId": "f7a229bd-2b17-4470-d08a-c6cc75bdc8c6"
},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"'{a + b}'"
],
"application/vnd.google.colaboratory.intrinsic+json": {
"type": "string"
}
},
"metadata": {},
"execution_count": 43
}
],
"source": [
"f\"{{a + b}}\""
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "6yj_LV-pF_TQ",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 36
},
"outputId": "28e211a2-1a03-4ac3-b574-0615f54089d7"
},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"'{15}'"
],
"application/vnd.google.colaboratory.intrinsic+json": {
"type": "string"
}
},
"metadata": {},
"execution_count": 44
}
],
"source": [
"f\"{{{a + b}}}\""
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "lYmP0xZza9xy"
},
"source": [
"\n",
"#### Optional: Format Specifications\n",
"\n",
"The structure of a format specifier is shown as follows:\n",
"\n",
"\n",
"` [[<fill>]<align>][<sign>][#][0][<width>][<grouping_option>][.<precision>][<type>]`\n",
"\n",
"```\n",
"fill : <any character>\n",
"align : \"<\" | \">\" | \"=\" | \"^\"\n",
"sign : \"+\" | \"-\" | \" \"\n",
"width : digit+\n",
"grouping_option : \"_\" | \",\"\n",
"precision : digit+\n",
"type : \"b\" | \"c\" | \"d\" | \"e\" | \"E\" | \"f\" | \"F\" | \"g\" | \"G\" | \"n\" | \"o\" | \"s\" | \"x\" | \"X\" | \"%\"\n",
"```\n",
"\n",
"A format specficiation is introduced by a colon `:` that optionally follows the name or position of the argument to be assigned to the replacement field.\n",
"\n",
"More details on the new-style string formatting syntax can be found <a href=\"https://docs.python.org/3/library/string.html#format-string-syntax\">here.\n"
]
},
{
"cell_type": "code",
"source": [
"stock = 'Google'; price = 203.83; shares = 11.4\n",
"f'purchase {shares:.2f} shares of {stock:>10} at ${price:.2e} per share'"
],
"metadata": {
"id": "euy0bsgOgXLZ",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 36
},
"outputId": "519dfecd-d705-4765-b963-7060e519d791"
},
"execution_count": null,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"'purchase 11.40 shares of Google at $2.04e+02 per share'"
],
"application/vnd.google.colaboratory.intrinsic+json": {
"type": "string"
}
},
"metadata": {},
"execution_count": 45
}
]
},
{
"cell_type": "code",
"source": [
"stock = 'Google'; percentage = 0.1845; week = 52.3\n",
"f\"{stock:e<12}'s stock is trading {percentage:.1%} off of {week:.0f}-week highs\""
],
"metadata": {
"id": "VBmSUdYPgYAS",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 36
},
"outputId": "6edbd80b-fd2f-4fa6-87ee-16514803db78"
},
"execution_count": null,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"\"Googleeeeeee's stock is trading 18.4% off of 52-week highs\""
],
"application/vnd.google.colaboratory.intrinsic+json": {
"type": "string"
}
},
"metadata": {},
"execution_count": 46
}
]
},
{
"cell_type": "markdown",
"source": [
"*Exercise:* Suppose you have a variable year=2021 (int type) and a variable month=7 (int type), how you can generate a date string such as “Now it is 2021.07”?"
],
"metadata": {
"id": "BC-YpDmFZ2ca"
}
},
{
"cell_type": "code",
"source": [
" #write your codes here\n",
"year = 2021\n",
"month = 7\n",
"f\"Now it is {year}.{month:0>2d}\""
],
"metadata": {
"id": "6ccGVnPTZ4pb",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 36
},
"outputId": "2d1661a6-097c-4065-e8c1-a2e99f93a20b"
},
"execution_count": null,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"'Now it is 2021.07'"
],
"application/vnd.google.colaboratory.intrinsic+json": {
"type": "string"
}
},
"metadata": {},
"execution_count": 48
}
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "Amq06mGJIxHy"
},
"source": [
"### (Optional) 5.4.2 The Method Approach: `str.format()`\n",
"\n",
"\n",
"Formatting can also be handled by calling `.format()` on a string object. The syntax is similar to the one we used with f-strings:\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "xeYfahm4Iwdb"
},
"outputs": [],
"source": [
"# Simple positional formatting\n",
"'purchase {} shares of {} at $ {} per share'.format(shares, stock, price)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "0D1owWVKWIXq"
},
"outputs": [],
"source": [
"# Rearranging the order of display\n",
"'purchase {2} shares of {0} at $ {1:.1f} per share'.format('Google', 203.83, 11.4)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "_7Gawa7PJOqO"
},
"outputs": [],
"source": [
"# Maching by name\n",
"'purchase {shares} shares of {stock} at $ {price} per share'.format(stock='Google', price=203.83, shares=11.4)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "u0m6hhSg7YU7"
},
"source": [
"### (Optional) 5.4.3 \"Old Style\": The `%` Operator\n",
"\n",
" `%` is known as the ***formatting/interpolation operator***. It lets us do simple positional formatting easily.\n",
"\n",
"The operator takes the <font color=\"salmon\">***conversion specifiers***</font> (starting with `%`) on the left and the values on the right, producing a formatted string:\n",
"\n",
"\n",
"<img src=\"https://drive.google.com/uc?export=download&id=1h2heHfSZQ69Xtihh2NaMfQZatLS4Hl1Z\" width=600/>\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "hjz62xgnDrSz"
},
"source": [
"- In addition to representing the string interpolation operation, the `%` character also denotes the conversion specifiers, e.g., `%d`, `%s`, and `%.0f`, and the replacement fields in a format string.\n",
"- Each value is converted to a string value with the specified format and inserted into the format string in place of the corresponding replacement field (matched by position).\n",
"- More rules can be found at: https://docs.python.org/2/library/stdtypes.html#string-formatting"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "QaC72Tn46WXl"
},
"source": [
"\n",
"#### Conversion Specifiers\n",
"\n",
"A conversion specifier contains 2 (% and a letter specifying conversion type; required) or more (optional) characters (allowing for more fine-grained control over how values are printed) to determine how values are formatted when theyre inserted:\n",
"\n",
"The constructs of a conversion specifier is structured as follows:\n",
"\n",
"`%[<flags>][<width>][.<precision>]<type>`\n",
"\n",
"\n",
"|Component|Meaning|Possible Values|\n",
"|:-- |:-- |:--|\n",
"|`%`|Introduces the conversion specifier|\n",
"|`<type>`|Indicates the type of conversion to be performed|`d` for decimal integers <br>`f` for floating point numbers <br>`e` for exponential numbers <br> `s` for strings\n",
"|`.<precision>`|Determines the length and precision of outputs|\n",
"|`<width>`|Specifies the minimum width of the formatted result|\n",
"|`<flags>`|Indicates one or more flags that exert finer control over formatting|`0` for padding of values<br>`-` for justification of values\n",
"\n",
"\n",
"<br>\n",
"\n",
"<div class=\"alert alert-info\">More details on conversion specifiers can be found <a href=\"https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting\">here</a>.</div>\n",
"\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "owdb4-EPElxE"
},
"source": [
"In most cases, we just use %s, %f, %d, etc as the conversion specifiers."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "yfazLbxRC6UU"
},
"outputs": [],
"source": [
"'purchase %d shares of %s at $%f per share' % (shares, stock, price) # The default precision of 'f' is 6."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "w6p457VHExbF"
},
"source": [
"**More usages**\n",
"\n",
"When we want to control **the length (for string values) or precision of values**, use `%.<precision>d/f/s`"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "Cdn85PlMEwVJ"
},
"outputs": [],
"source": [
"'purchase %.6d shares of %.3s at $ %.0f per share' % (shares, stock, price)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "PALruLGAE7Fe"
},
"source": [
"When we want to control the width of the placeholder"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "43W_wADzJmHC"
},
"outputs": [],
"source": [
"'purchase %-6d shares of %-10s at $%.2e per share' % (shares, stock, price)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "lK2w-VQABHbZ"
},
"source": [
"To insert a literal `%` character into the output, specify two consecutive `%` characters in the format string:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "QdAMo1B9HHhI"
},
"outputs": [],
"source": [
"\"%s's stock is trading %.0f%% off of %d-week highs\" % ('Google', 0.1845 * 100, 52.3)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "WR7QepOrRdNt"
},
"source": [
"## 5.5 Accepting User Inputs\n",
"\n",
"Programs often need to obtain data from the user, usually by way of input from the keyboard. The simplest way to accomplish this in Python is with `input()`.\n",
"\n",
"`input(prompt)` prompts for and returns input as a string. We can assign what is returned into a variable, to be used later."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "Rl_4vK_4RuFt",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "584f9e8c-2189-47d6-8f3a-20099d786a78"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"What is your name? Jing\n",
"What is your age? 38\n",
"What is your gender? female\n"
]
}
],
"source": [
"name = input(\"What is your name? \")\n",
"age = input(\"What is your age? \")\n",
"gender = input(\"What is your gender? \")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "Rk3RsypYR0Tr",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 36
},
"outputId": "74cd2e6e-08fd-46a4-8b89-3c38afcadf32"
},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"'38'"
],
"application/vnd.google.colaboratory.intrinsic+json": {
"type": "string"
}
},
"metadata": {},
"execution_count": 50
}
],
"source": [
"age"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "bQ0H7xZ7R2Se",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "da182704-44c5-46cc-dddd-6137ae742341"
},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"str"
]
},
"metadata": {},
"execution_count": 51
}
],
"source": [
"type(age)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "ARe7vFI3R49s"
},
"source": [
"To display the contents of these variables, pass them as a comma-separated list of argument to `print()`. By default, `print()` separates the content of each argument by a single space and appends a newline to the end of the output:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "GYH7emBqR9-s",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "a0afc921-5b68-434d-f907-15601051881f"
},
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Jing is female at 38 years old.\n"
]
}
],
"source": [
"print(name, 'is', gender, 'at', age, 'years old.')"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "qkPzJe9NSOGo"
},
"outputs": [],
"source": [
"help(print)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "MFxxW4UkSWf0"
},
"source": [
"Try other usage of print() function"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "jBfJuG1JSY5Y"
},
"outputs": [],
"source": [
"print(name, 'is', gender, sep='-', end='\\t')\n",
"print('at', age, 'years old.', sep='-')"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "SvqzSsSRSkcH"
},
"source": [
"*Exercise*: Write a program to prompt the user to input the length and width of a rectangle with some prompt messages. Then calculate the area of the rectangle and print the result to the user with appropriate messages."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "HSpMdvCTSqa6"
},
"outputs": [],
"source": [
"#write your codes here\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "jqxjuXfZmDAp"
},
"source": [
"<br>\n",
"\n",
"# 6 Type Conversion\n",
"\n",
"\n",
"Built-in functions like `str()`, `int()`, `bool()`, and `float()` will try to convert anything to their respective types:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "Qo02se6s4HpG",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 175
},
"outputId": "9e1277f7-6290-4ef2-f761-130a558e7e26"
},
"outputs": [
{
"output_type": "error",
"ename": "TypeError",
"evalue": "unsupported operand type(s) for +: 'int' and 'str'",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)",
"\u001b[0;32m<ipython-input-53-312907c32eeb>\u001b[0m in \u001b[0;36m<cell line: 1>\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0;36m3\u001b[0m \u001b[0;34m+\u001b[0m \u001b[0;34m'4'\u001b[0m \u001b[0;31m# add or concatenate?\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[0;31mTypeError\u001b[0m: unsupported operand type(s) for +: 'int' and 'str'"
]
}
],
"source": [
"3 + '4' # add or concatenate?"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "nBtWRCxK3hUQ",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "6e6a5f2d-4da6-4729-83d9-d7fe195ce661"
},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"7"
]
},
"metadata": {},
"execution_count": 54
}
],
"source": [
"int(\"3\") + 4 # Now the ambiguity is cleared up"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "e0nSEUwe3jId",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 36
},
"outputId": "bee07692-c46c-4bb4-c6ca-9cbbef45645e"
},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"'3.4'"
],
"application/vnd.google.colaboratory.intrinsic+json": {
"type": "string"
}
},
"metadata": {},
"execution_count": 55
}
],
"source": [
"'3.' + str(4)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "2b4YlOk43tm9",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "9ac77aac-d96d-4147-cc86-31d9543076d7"
},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"3"
]
},
"metadata": {},
"execution_count": 56
}
],
"source": [
"int(float(\"3.4\")) # try int(\"3.4\")"
]
},
{
"cell_type": "code",
"source": [
"int(\"3.4\")"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/",
"height": 175
},
"id": "xIEOnjeN6pA6",
"outputId": "e69fac77-71df-409b-a121-d2fff1f52f2d"
},
"execution_count": null,
"outputs": [
{
"output_type": "error",
"ename": "ValueError",
"evalue": "invalid literal for int() with base 10: '3.4'",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mValueError\u001b[0m Traceback (most recent call last)",
"\u001b[0;32m<ipython-input-57-3594573f2808>\u001b[0m in \u001b[0;36m<cell line: 1>\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"3.4\"\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[0;31mValueError\u001b[0m: invalid literal for int() with base 10: '3.4'"
]
}
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "rkL5i1893u-7",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "3dfd7fb9-e1c2-4e8c-af25-4d5e49b675cd"
},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"False"
]
},
"metadata": {},
"execution_count": 58
}
],
"source": [
"bool(0) # return an object's truth value"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "N08Txf-_4CiT",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "12077506-bc1c-49f9-9cb7-f4ac823b63bb"
},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"True"
]
},
"metadata": {},
"execution_count": 59
}
],
"source": [
"bool(-3.4)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "OseDYKl73w9j",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "e503fcb5-3ec1-44ce-ef93-021013d9b81f"
},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"False"
]
},
"metadata": {},
"execution_count": 60
}
],
"source": [
"bool(\"\") # An empty string is false"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "E0xNGUkS3-N8",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "cd70f4e6-2121-41db-9e82-fcadb13cbe3f"
},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"True"
]
},
"metadata": {},
"execution_count": 61
}
],
"source": [
"bool(\"False\") # A non-empty string counts as True"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "Xb3oDNHE4CF3",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 175
},
"outputId": "61a7ce2e-0c9a-4547-f44d-0a7c71b6c41b"
},
"outputs": [
{
"output_type": "error",
"ename": "ValueError",
"evalue": "invalid literal for int() with base 10: 'I have $3.8 in my pocket'",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mValueError\u001b[0m Traceback (most recent call last)",
"\u001b[0;32m<ipython-input-62-35a09d6249bc>\u001b[0m in \u001b[0;36m<cell line: 1>\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m'I have $3.8 in my pocket'\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;31m# nonsensical conversion\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[0;31mValueError\u001b[0m: invalid literal for int() with base 10: 'I have $3.8 in my pocket'"
]
}
],
"source": [
"int('I have $3.8 in my pocket') # nonsensical conversion"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "YXXEWI7oN3Ly"
},
"source": [
"*Exercise:* Try to debug the following program so that it works reasonably."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "hVuNpcxYN5jG",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "788f4f4c-1190-4ae7-ab20-ad7d80a4ae44"
},
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"please input an integer: 20\n",
"After adding 10 the result would be 30\n"
]
}
],
"source": [
"# Try to correct the codes\n",
"number = input('please input an integer: ')\n",
"print(f'After adding 10 the result would be {int(number) + 10}')"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "qtIERvN0VEYy"
},
"source": [
"<br>\n",
"\n",
"# 7 Methods\n",
"\n",
"\n",
"A method is an <font color=\"salmon\">***object-oriented***</font> programming term, and refers to a function that is attached to and act upon a specific object (thereby considered an attribute of the object).\n",
"\n",
"\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "bz-AsfODz1OU"
},
"source": [
"\n",
"## 7.1 Method Invocation\n",
"\n",
"Like functions, methods are triggered with a call expression.\n",
"\n",
"A method call requires the <font color=\"royalblue\"><b>*attribute reference*</b></font> notation, i.e., a dot (`.`) between the invocation target and the method name:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "8bL385TVWXkS"
},
"outputs": [],
"source": [
"course = 'Python Programming'"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "aGwvhbZcWPR9",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 36
},
"outputId": "d6677b07-0e70-4ceb-9420-03bd8542c404"
},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"'python programming'"
],
"application/vnd.google.colaboratory.intrinsic+json": {
"type": "string"
}
},
"metadata": {},
"execution_count": 66
}
],
"source": [
"course.lower()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "D2gABWF7Wa27",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "f8b7ccf0-642c-479e-ad62-b5bd4452b878"
},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"False"
]
},
"metadata": {},
"execution_count": 67
}
],
"source": [
"(12.3).is_integer() # E.g., 12.3 is not; try (12).is_integer()"
]
},
{
"cell_type": "code",
"source": [
"(12.0).is_integer()"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "nqzZishL8OS9",
"outputId": "a422cf31-15bf-4bc0-d811-12fd6f3e36cb"
},
"execution_count": null,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"True"
]
},
"metadata": {},
"execution_count": 69
}
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "F5-PW7ZapFJj"
},
"source": [
" Any name following a dot can be called an **attribute**.\n",
"\n",
"\n",
" As a rule of thumb, Python's toolset is <font color=\"salmon\">***layered***</font>:\n",
"\n",
"- Generic operations that span multiple types show up as built-in functions or expressions (e.g., `len(x)`, `x[0]`);\n",
"\n",
"- Type-specific operations are implemented as method calls."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "_A1EVluSYfRd"
},
"source": [
"Again, typing a method's name without adding `()` echos the string representation of the method:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "FndDveaeYj33",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "8bae9cfa-cb42-4bc9-e367-c97fa75f3fc7"
},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"<function str.split(sep=None, maxsplit=-1)>"
]
},
"metadata": {},
"execution_count": 70
}
],
"source": [
"course.split"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "Cng2VJbPPXu_",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "22a999c8-423f-4ca6-8e94-a4dd51a0ad4f"
},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"['Python', 'Programming']"
]
},
"metadata": {},
"execution_count": 71
}
],
"source": [
"course.split()"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "WBHyDQt9XoJD"
},
"source": [
"\n",
"---\n",
"\n",
"<br/>\n",
"\n",
"## 7.2 Getting Help on Methods\n",
"\n",
"We can use the built-in function `dir(object)` to retrieve a list of all the attributes (including methods, which are <font color=\"royalblue\"><b>*function attributes*</b></font>) available for any object passed to it:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "g-Qrmd_zYE8N",
"outputId": "0b21efc0-bf17-456b-853a-111b5fc3469f"
},
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'removeprefix', 'removesuffix', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']\n"
]
}
],
"source": [
"print(dir(course))"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "Z6FSGhkpYQBh"
},
"source": [
"To learn about each method, we can pass them to the `help()` function:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "-E5dE4XYYPVK",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "9dbb902e-4aef-4866-d8ac-8664cec7faf5"
},
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Help on built-in function split:\n",
"\n",
"split(sep=None, maxsplit=-1) method of builtins.str instance\n",
" Return a list of the substrings in the string, using sep as the separator string.\n",
" \n",
" sep\n",
" The separator used to split the string.\n",
" \n",
" When set to None (the default value), will split on any whitespace\n",
" character (including \\\\n \\\\r \\\\t \\\\f and spaces) and will discard\n",
" empty strings from the result.\n",
" maxsplit\n",
" Maximum number of splits (starting from the left).\n",
" -1 (the default value) means no limit.\n",
" \n",
" Note, str.split() is mainly useful for data that has been intentionally\n",
" delimited. With natural text that includes punctuation, consider using\n",
" the regular expression module.\n",
"\n"
]
}
],
"source": [
"help(course.split)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "76u3sCogxnVV",
"outputId": "ae6bebb6-1986-4071-93b5-ea166f799230"
},
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Help on built-in function join:\n",
"\n",
"join(iterable, /) method of builtins.str instance\n",
" Concatenate any number of strings.\n",
" \n",
" The string whose method is called is inserted in between each given string.\n",
" The result is returned as a new string.\n",
" \n",
" Example: '.'.join(['ab', 'pq', 'rs']) -> 'ab.pq.rs'\n",
"\n"
]
}
],
"source": [
"help(course.join)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "CfS8t3kbyJZt",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 36
},
"outputId": "9a46b470-4c20-41c8-e260-24fdb51f982b"
},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"'Python-Programming'"
],
"application/vnd.google.colaboratory.intrinsic+json": {
"type": "string"
}
},
"metadata": {},
"execution_count": 75
}
],
"source": [
"'-'.join(course.split())"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "9xq3jrsO99g9"
},
"source": [
"<br>\n",
"\n",
"---\n",
"\n",
"<br>\n",
"\n",
"# Appendix: Operator Precedence\n",
"\n",
"Python evaluates expressions from left to right. The following table summarizes the <font color=\"royalblue\"><b>*operator precedence*</b></font> for all the operators we have seen so far, from highest precedence to lowest precedence:\n",
"\n",
"\n",
"\n",
"|Operator|Meaning|\n",
"|:-- |:-- |\n",
"|`()`|Grouping|\n",
"|`x[i], x[i:j:k], x(...), x.attr`|Indexing, slicing, call, attribute reference|\n",
"|`**`|Exponentiation|\n",
"|`+x, -x`|identity, negatition|\n",
"|`*, /, //, %`|Multiplication (repetition), division, integer division, remainder (format)|\n",
"|`+, -`|Addition (concatenation), substraction|\n",
"|`<, <=, >, >=, ==, !=, in, not in, is, is not`|Comparisons, including membership tests and identity tests|\n",
"|`not`|Logical negation|\n",
"|`and`|Logical AND|\n",
"|`or`|Logical OR|"
]
}
],
"metadata": {
"colab": {
"provenance": [],
"toc_visible": true
},
"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.7.13"
}
},
"nbformat": 4,
"nbformat_minor": 0
}