Files
004_comission/max015/T04/CDS1001T4Report_wrong.ipynb
louiscklaw acf9d862ff update,
2025-01-31 21:15:04 +08:00

1398 lines
38 KiB
Plaintext

{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# CDS1001 Tutorial 4 Report"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Input your name and student ID in the cell below (<font color='red'>if a cell is not in edit mode, double click it</font>):"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<div class=\"alert alert-info\">\n",
" \n",
"Your name: \n",
"\n",
"Your student ID:\n",
" \n",
"</div>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Objectives:\n",
"- Understand why functions are used in coding\n",
"- Be able to understand and use user-defined functions\n",
"- Understand basic usage of some built-in functions\n",
"- Be able to understand and draw flow charts"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### **Instructions for the report**:\n",
"* Follow Section 1 and Section 2 of the tutorial instruction to launch Python IDLE through Anaconda Navigation.\n",
"* Refer to Section 2.2 of the tutorial instruction to open tutorial 4 report\n",
"* Complete Parts 1-3 led by the lecturer\n",
"* Complete Part 4 independently\n",
"* Follow Section 3 of the tutorial instruction to save the report and zip the report folder. The zip file is named as CDS1001T4Report{your student_id}.zip (e.g., if student_id is 1234567, then the zip file's name is CDS1001T4Report1234567.zip). <font color='red'>The zip file needs to include the following files:\n",
" - an .ipynb file of this tutorial report \n",
" - image files of flowcharts or screenshots used in this tutorial report </font> \n",
"* Submit the zip file of the report folder in the blackboard. The submission due date is **<font color='red'>17 Oct 2023, 11:55 PM</font>**"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Part 1 Python Function"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 1.1. Read the following code and answer questions below:"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"The lowest shipping rate is: 10.0\n"
]
}
],
"source": [
"def min_num(num1, num2):\n",
" res = num1\n",
" if num2<res:\n",
" res = num2\n",
" return res\n",
"\n",
"rate1 = float(input('Enter the 1st shipping rate: '))\n",
"rate2 = float(input('Enter the 2nd shipping rate: '))\n",
"lowest_rate = min_num(rate1, rate2)\n",
"print('The lowest shipping rate is:', lowest_rate)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Question 1.1: List all the functions used in the code above, explain what types of functions they are, and explain what they are used for (3 points). "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Answer 1.1: \n",
"\n",
"Python function `input`, acquire input from user and store it to the variable.\n",
"Python function `print`, print the text defined in it's parameters e.g. print('helloworld') will output `helloworld` to the console/output device. \n",
"Python function `float`, convert input to a float number"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Question 1.2: Revise the statement ``lowest_rate = min_num(rate1, rate2)``, so that given an additional 3rd shipping rate as part of the input, the code outputs the lowest rate among the three shipping rates. Based on this, explain the benefits brought by the use of a function. (4 points)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"#revise the code below accordingly:\n",
"def min_num(num1, num2, num3):\n",
" res = min([num1, num2, num3])\n",
" return res\n",
"\n",
"rate1 = float(input('Enter the 1st shipping rate: '))\n",
"rate2 = float(input('Enter the 2nd shipping rate: '))\n",
"rate3 = float(input('Enter the 3rd shipping rate: '))\n",
"\n",
"lowest_rate = min_num(rate1, rate2, rate3) #revise this statement\n",
"\n",
"print('The lowest shipping rate is:', lowest_rate)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Answer 1.2: \n",
"\n",
"By using functions, it greatly help the readability of the code. In the above example. Other coders can easier to get the ideas \"find the minimum number\" by it's name suggest \"min_num\". \n",
"\n",
"Also, using function can help reusability throughout the program. By using function, the same idea/process can be easier to be reused by just calling function same function/def. \n",
"\n",
"Last but not least, it helps the whole program to be more modular. The function/def with similar purpose can be relocated and grouped into a single library/file. It generally helps to manage the code through-out the whole software project.\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Part 2 User-defined Functions"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 2.1. Read the following functions, and describe the name, body, parameters of each function, and illustrate its usage (4 points):"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### (a)"
]
},
{
"cell_type": "code",
"execution_count": 28,
"metadata": {},
"outputs": [],
"source": [
"def min_num(num1, num2):\n",
" res = num1\n",
" if num2<res:\n",
" res = num2\n",
" return res"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Answer: \n",
"\n",
"The name of the function is `min_num`. It takes 2 parameters `num1` and `num2` and compare them. \n",
"\n",
"First of all, the `num1` is assumed to be the smaller one. Then compare it by `num2` with a `if` branch.\n",
"\n",
"If the `num2` is smaller than the `res` (at line `4`, currently equivalent to `num1`). The res will be replaced by `num2` and bypass process otherwise. \n",
"\n",
"Effectively it will return/output the smaller number from those two input. \n"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"5\n"
]
}
],
"source": [
"#edit this cell to show how to use the function above to print the minimum value of 10 and 5\n",
"\n",
"print(min_num(10,5))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### (b)"
]
},
{
"cell_type": "code",
"execution_count": 30,
"metadata": {},
"outputs": [],
"source": [
"def print_stars():\n",
" print('**********')\n",
" return\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Answer:\n",
"\n",
"The name of the function is `print_stars`. \n",
"\n",
"It takes no input parameters, print 10 `*`(star) and then exit function(return)."
]
},
{
"cell_type": "code",
"execution_count": 31,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"**********\n",
"**********\n"
]
}
],
"source": [
"#edit this cell to show how to use the function above to print two lines of 10 stars\n",
"\n",
"print_stars()\n",
"print_stars()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 2.2. Execute each of the codes below, explain the errors received, and discuss how to fix the errors (6 points):"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### (a)"
]
},
{
"cell_type": "code",
"execution_count": 33,
"metadata": {},
"outputs": [
{
"ename": "IndentationError",
"evalue": "unindent does not match any outer indentation level (<tokenize>, line 5)",
"output_type": "error",
"traceback": [
"\u001b[1;36m File \u001b[1;32m<tokenize>:5\u001b[1;36m\u001b[0m\n\u001b[1;33m return res\u001b[0m\n\u001b[1;37m ^\u001b[0m\n\u001b[1;31mIndentationError\u001b[0m\u001b[1;31m:\u001b[0m unindent does not match any outer indentation level\n"
]
}
],
"source": [
"def positive_num(num):\n",
"res = 0\n",
"if num>=0:\n",
" res = num\n",
" return res\n",
"\n",
"print(positive_num(10))\n",
"print(positive_num(0))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Answer:\n",
"\n",
"The indentation of the code was wrong. Python strictly relies on the indentation to define the function `def` and `if` clause.\n"
]
},
{
"cell_type": "code",
"execution_count": 37,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"10\n",
"0\n"
]
}
],
"source": [
"#Copy the corrected code below in this cell:\n",
"\n",
"def positive_num(num):\n",
" res = 0\n",
" if num>=0:\n",
" res = num\n",
" return res\n",
"\n",
"print(positive_num(10))\n",
"print(positive_num(0))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### (b)"
]
},
{
"cell_type": "code",
"execution_count": 38,
"metadata": {
"scrolled": false
},
"outputs": [
{
"ename": "NameError",
"evalue": "name 'difference' is not defined",
"output_type": "error",
"traceback": [
"\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[1;31mNameError\u001b[0m Traceback (most recent call last)",
"\u001b[1;32md:\\_workspace\\carousell-comission-playlist\\max015\\T04\\CDS1001T4Report.ipynb Cell 30\u001b[0m line \u001b[0;36m1\n\u001b[1;32m----> <a href='vscode-notebook-cell:/d%3A/_workspace/carousell-comission-playlist/max015/T04/CDS1001T4Report.ipynb#X41sZmlsZQ%3D%3D?line=0'>1</a>\u001b[0m \u001b[39mprint\u001b[39m(difference(\u001b[39m10\u001b[39m,\u001b[39m30\u001b[39m))\n\u001b[0;32m <a href='vscode-notebook-cell:/d%3A/_workspace/carousell-comission-playlist/max015/T04/CDS1001T4Report.ipynb#X41sZmlsZQ%3D%3D?line=1'>2</a>\u001b[0m \u001b[39mdef\u001b[39;00m \u001b[39mdifference\u001b[39m(num1,num2):\n\u001b[0;32m <a href='vscode-notebook-cell:/d%3A/_workspace/carousell-comission-playlist/max015/T04/CDS1001T4Report.ipynb#X41sZmlsZQ%3D%3D?line=2'>3</a>\u001b[0m res \u001b[39m=\u001b[39m num1\u001b[39m-\u001b[39mnum2\n",
"\u001b[1;31mNameError\u001b[0m: name 'difference' is not defined"
]
}
],
"source": [
"print(difference(10,30))\n",
"def difference(num1,num2):\n",
" res = num1-num2\n",
" if res < 0:\n",
" res = -res\n",
" return res"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Answer:\n",
"\n",
"The function/def `difference` was used before defining it."
]
},
{
"cell_type": "code",
"execution_count": 39,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"20\n"
]
}
],
"source": [
"#Copy the corrected code below in this cell:\n",
"\n",
"def difference(num1,num2):\n",
" res = num1-num2\n",
" if res < 0:\n",
" res = -res\n",
" return res\n",
"\n",
"print(difference(10,30))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### (c)"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {
"scrolled": false
},
"outputs": [
{
"ename": "NameError",
"evalue": "name 'res' is not defined",
"output_type": "error",
"traceback": [
"\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[1;31mNameError\u001b[0m Traceback (most recent call last)",
"\u001b[1;32md:\\_workspace\\carousell-comission-playlist\\max015\\T04\\CDS1001T4Report.ipynb Cell 34\u001b[0m line \u001b[0;36m8\n\u001b[0;32m <a href='vscode-notebook-cell:/d%3A/_workspace/carousell-comission-playlist/max015/T04/CDS1001T4Report.ipynb#X45sZmlsZQ%3D%3D?line=4'>5</a>\u001b[0m \u001b[39mreturn\u001b[39;00m res\n\u001b[0;32m <a href='vscode-notebook-cell:/d%3A/_workspace/carousell-comission-playlist/max015/T04/CDS1001T4Report.ipynb#X45sZmlsZQ%3D%3D?line=6'>7</a>\u001b[0m difference(\u001b[39m10\u001b[39m,\u001b[39m20\u001b[39m)\n\u001b[1;32m----> <a href='vscode-notebook-cell:/d%3A/_workspace/carousell-comission-playlist/max015/T04/CDS1001T4Report.ipynb#X45sZmlsZQ%3D%3D?line=7'>8</a>\u001b[0m \u001b[39mprint\u001b[39m(res)\n",
"\u001b[1;31mNameError\u001b[0m: name 'res' is not defined"
]
}
],
"source": [
"def difference(num1,num2):\n",
" res = num1-num2\n",
" if res < 0:\n",
" res = -res\n",
" return res\n",
"\n",
"difference(10,20)\n",
"print(res)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Answer:\n",
"\n",
"The variable `res` wasn't defined before use."
]
},
{
"cell_type": "code",
"execution_count": 44,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"10\n"
]
}
],
"source": [
"#Copy the corrected code below in this cell:\n",
"\n",
"def difference(num1,num2):\n",
" res = num1-num2\n",
" if res < 0:\n",
" res = -res\n",
" return res\n",
"\n",
"res = difference(10,20)\n",
"print(res)\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 2.3. Execute the codes below, and answer the questions (8 points):"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### (a)"
]
},
{
"cell_type": "code",
"execution_count": 45,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1005.0\n"
]
}
],
"source": [
"def compute_shipping_cost(quantity,rate):\n",
" cost = quantity * rate\n",
" return cost\n",
"\n",
"cost = compute_shipping_cost(10,100.5)\n",
"compute_shipping_cost(10,10)\n",
"print(cost)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font color='red'>*Edit this cell to explain why in the code above, after executing ``compute_shipping_cost(10,10)``, the value of variable ``cost`` is unchanged:*</font>\n",
"\n",
"Answer:\n",
"\n",
"This is because those two `cost` were in different scope. The `cost` at line `5` takes effect in the root of the program. While the cost at line `2` effects inside the function/def `compute_shipping_cost`. The changes of the value `cost` was only effect inside `def` and won't propergate to the root. \n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### (b)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def compute_shipping_cost(quantity,rate=50):\n",
" cost = quantity * rate\n",
" return cost\n",
"\n",
"cost1 = compute_shipping_cost(10,50)\n",
"cost2 = compute_shipping_cost(10)\n",
"print(cost1,cost2)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font color='red'>*Edit this cell to explain why after the code is executed, ``cost1`` and ``cost2`` have the same value:*</font>\n",
"\n",
"This is because the default input of the `rate` in function/def `compute_shipping_rate` was `50`. The result of first call `compute_shipping_cost` (in line `5`) was take 2 input (10 and 50) and the second call of it (in line `6`) with 1 input only (`10`). By the definition of the function/def, the rate will be default to 50 if the input of it is undefined.\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### (c)"
]
},
{
"cell_type": "code",
"execution_count": 47,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"******************************\n",
"Today is Monday\n",
"******************************\n",
"..............................\n",
"Tomorrow will be Tuesday\n",
"..............................\n"
]
}
],
"source": [
"def print_star_line():\n",
" print('******************************')\n",
"\n",
"def print_dot_line():\n",
" print('..............................')\n",
" \n",
"def print_message(message, func_print_line):\n",
" func_print_line()\n",
" print(message)\n",
" func_print_line()\n",
" \n",
"print_message('Today is Monday', print_star_line)\n",
"print_message('Tomorrow will be Tuesday', print_dot_line)\n",
" "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font color='red'>*Edit this cell to explain why, in the code above, the first call of function ``print_message`` displays lines of stars, but the second call of function ``print_message`` displays lines of dots*</font>\n",
"\n",
"\n",
"The first call (at line `12`) of function/def `print_message` passed with `print_star_line` at it's second input. \n",
"\n",
"It is noted that the `print_star_line` there (at line `12`) wasn't ended with `()`. thus that effectively passing the references of function/def `print_star_line` as an second input of `print_message` and storing it into variable `func_print_line`. Meanwhile, the second and forth line inside function/def calling `func_print_line`. So that effectively calling `print_star_line` inside function/def `print_message`. \n",
"\n",
"Same mechanism applies to `print_dot_line`. By replacing the second parameter to `print_dot_line`. The function/def inside `print_message` will call `print_dot_line` instead. Thus, dot`.` printed out.\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### (d)"
]
},
{
"cell_type": "code",
"execution_count": 48,
"metadata": {
"scrolled": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"10\n"
]
}
],
"source": [
"res = 0\n",
"def difference(num1,num2):\n",
" global res\n",
" res = num1-num2\n",
" if res < 0:\n",
" res = -res\n",
" return res\n",
"\n",
"difference(10,20)\n",
"print(res)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font color='red'>*Edit this cell to explain why in the code above, the value of the global variable ``res`` is changed after the call of function ``difference``:*</font>\n",
"\n",
"This is because the second line of function/def`difference`, the `global res` given the access of the `res` to global scope. thus the `res` (at line `4`) accessing the global/root `res` variable. So the value changed."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 2.4. In the codes below, what are the scope of each variable ``x``? (3 points)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"x = 0\n",
"def double(x):\n",
" x = x*2\n",
" return x\n",
"\n",
"x = double(10)\n",
"print(x)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font color='red'>*Edit this cell to explain the scope of each variable ``x``:*</font>\n",
"\n",
"x at line 1: define variable `x` in global scope.\n",
"x at line 3,4: accessing the x at local scope defined at line 2\n",
"x at line 6,7: accessing the x at global scope.\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 2.5. Simplify the code below by defining and using a new function (7 points)."
]
},
{
"cell_type": "code",
"execution_count": 51,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Lowest Cost for test 150 : 1350.0\n"
]
}
],
"source": [
"customer = input('Enter customer name: ')\n",
"quantity = int(input('Enter order quantity: '))\n",
"rate1 = 10.0\n",
"threshold1 = 100\n",
"discount1 = 0.1\n",
"rate2 = 11.0\n",
"threshold2 = 200\n",
"discount2 = 0.3\n",
"\n",
"cost1 = rate1*quantity\n",
"if quantity>=threshold1:\n",
" cost1 = cost1*(1.0-discount1)\n",
"cost2 = rate2*quantity\n",
"if quantity>=threshold2:\n",
" cost2 = cost2*(1.0-discount2)\n",
" \n",
"lowest_cost = cost1\n",
"if cost2<lowest_cost:\n",
" lowest_cost = cost2\n",
"print('Lowest Cost for', customer, ':', lowest_cost)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### (a)"
]
},
{
"cell_type": "code",
"execution_count": 52,
"metadata": {},
"outputs": [],
"source": [
"#edit this cell to define the body of a new function named compute_cost_discount with \n",
"# four parameters, quantity, rate, threshold, discount, that returns the cost:\n",
"\n",
"def compute_cost_discount(quantity, rate, threshold, discount):\n",
" cost = rate * quantity\n",
" if quantity>=threshold:\n",
" cost = cost*(1.0-discount)\n",
" return cost\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### (b)"
]
},
{
"cell_type": "code",
"execution_count": 57,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Lowest Cost for 250 : 1924.9999999999998\n"
]
}
],
"source": [
"#edit this cell to simplify the original code using the function defined above:\n",
"\n",
"rate1 = 10.0\n",
"threshold1 = 100\n",
"discount1 = 0.1\n",
"\n",
"rate2 = 11.0\n",
"threshold2 = 200\n",
"discount2 = 0.3\n",
"\n",
"def compute_cost_discount(quantity, rate, threshold, discount):\n",
" cost = rate * quantity\n",
" if quantity>=threshold:\n",
" cost = cost*(1.0-discount)\n",
" return cost\n",
"\n",
"\n",
"customer = input('Enter customer name: ')\n",
"quantity = int(input('Enter order quantity: '))\n",
"\n",
"cost1 = compute_cost_discount(quantity, rate1, threshold1, discount1)\n",
"cost2 = compute_cost_discount(quantity, rate2, threshold2, discount2)\n",
"\n",
"lowest_cost = cost1\n",
"\n",
"if cost2<lowest_cost:\n",
" lowest_cost = cost2\n",
"\n",
"print('Lowest Cost for', customer, ':', lowest_cost)\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### (c)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font color='red'>*Create a python file of the simplified code above in Python IDLE, test the code using your studentid as input for customer id, take a screenshot of the result, and paste the screenshot below in this cell:*</font>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 2.6. Rewrite your program of Problem 3.3. of tutorial 3 by defining and using a function called ``computepay`` which takes two parameters, ``hours`` and ``rate`` (5 points).\n",
"(For the example below, 475 = 40\\*10 + (45-40)\\*10\\*1.5) \n",
"\n",
"*Sample Input and Output:*\n",
"\n",
" Input:\n",
" Enter Hours: 45\n",
" Enter Rate: 10 \n",
"\n",
" Output:\n",
" Pay: 475"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### (a)"
]
},
{
"cell_type": "code",
"execution_count": 58,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Input:\n",
"Output:\n",
"Pay: 475.0\n"
]
}
],
"source": [
"# (a) Edit this cell rewrite your program below:\n",
"\n",
"def computepay(hours, rate):\n",
" output = 0\n",
" hours = int(hours)\n",
" rate = float(rate)\n",
"\n",
" if (hours > 40):\n",
" output = 40*rate + (hours-40)*rate*1.5\n",
" else:\n",
" output = hours*rate\n",
"\n",
" return output\n",
"\n",
"print('Input:')\n",
"hours = input('Enter Hours: ')\n",
"rate = input('Enter Rate: ')\n",
"\n",
"pay = computepay(hours, rate)\n",
"print('Output:')\n",
"print(f\"Pay: {pay}\")\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### (b)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font color='red'>Execute and test your revised code above for various inputs. Edit this cell to copy your test results below:</font>\n",
"\n",
"\n",
"```bash\n",
"PS D:\\_workspace\\carousell-comission-playlist\\max015\\T04> python .\\test_2_6.py\n",
"Input:\n",
"Enter Hours: 45\n",
"Enter Rate: 10\n",
"Output:\n",
"Pay: 475.0\n",
"PS D:\\_workspace\\carousell-comission-playlist\\max015\\T04> python .\\test_2_6.py\n",
"Input:\n",
"Enter Hours: 35\n",
"Enter Rate: 10\n",
"Output:\n",
"Pay: 350.0\n",
"```"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Part 3 Built-in Functions and Modules"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 3.1. Execute the codes below, and explain how the codes are executed (2 points):"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"scrolled": true
},
"outputs": [],
"source": [
"import math\n",
"pi = math.pi\n",
"d = math.sqrt(2)\n",
"print(pi * d)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font color='red'>*Edit this cell to explain how the code above is executed:*</font>\n",
"\n",
"at line 2, it takes `pi` constant from `math` library.\n",
"at line 3, it use `sqrt` function/def from `math` library.\n",
"at line 4, multiply `pi` to the square root `sqrt` and print it out."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 3.2. Use help() to show the definition and usage of function ``print``, and answer the following questions (4 points):"
]
},
{
"cell_type": "code",
"execution_count": 59,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"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": [
"#edit this cell to write a code to use help() to show the definition and usage of function print:\n",
"\n",
"help(print)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Question 3.2.1. Explain which parameters of function ``print`` have default values? What are these default values?"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font color='red'>*Edit this cell to answer the question above:*</font>\n",
"\n",
"By definition: `print(value, ..., sep=' ', end='\\n', file=sys.stdout, flush=False)`\n",
"parameters `sep`, `end`, `file`, `flush` got default values.\n",
"the default values of `sep` is ' '\n",
"the default values of `end` is '\\n' (a new line)\n",
"the default values of `file` is sys.stdout (console's standard/non-error output)\n",
"the default values of `flush` is False"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Question 3.2.2. Given three string variables ``s1``, ``s2``, and ``s3``, explain how to use function ``print`` and use keyword arguments to output a line that concatenates the three strings with '+' instead of ' ' between the strings. For example, if s1='Apple', s2='Orange', and s3='Grapes', then it outputs a line of 'Apple+Orange+Grapes'"
]
},
{
"cell_type": "code",
"execution_count": 61,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Apple+Orange+Grapes\n"
]
}
],
"source": [
"#edit this cell to write a code for the question above\n",
"\n",
"s1=\"Apple\"\n",
"s2=\"Orange\"\n",
"s3=\"Grapes\"\n",
"print(s1,s2,s3, sep=\"+\")\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 3.3. Use help() to show the definition and usage of function ``ctime`` in module ``time`` and answer the questions below (4 points):"
]
},
{
"cell_type": "code",
"execution_count": 62,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Help on built-in function ctime in module time:\n",
"\n",
"ctime(...)\n",
" ctime(seconds) -> string\n",
" \n",
" Convert a time in seconds since the Epoch to a string in local time.\n",
" This is equivalent to asctime(localtime(seconds)). When the time tuple is\n",
" not present, current time as returned by localtime() is used.\n",
"\n"
]
}
],
"source": [
"#edit this cell to write a code to use help() to show the definition and usage of function ctime of module time:\n",
"#Remember to import the module first\n",
"#Remember to use dot notation when using the function ctime of module time:\n",
"\n",
"from time import ctime\n",
"help(ctime)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Question 3.3.1. What is the use of function ``ctime`` of module ``time``? How can it be used?"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font color='red'>*Edit this cell to answer the question above:*</font>\n",
"\n",
"ctime count the seconds since Epoch time. By definition, epoch time start counting from \"January 1, 1970\". Equivalently that means it counting the time from 1970-Jan-01 00:00:00 until the time inputted to the function and output it to a human readable string."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Question 3.3.2. Write a statement to print the current time."
]
},
{
"cell_type": "code",
"execution_count": 26,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'Sun Oct 15 23:13:46 2023'"
]
},
"execution_count": 26,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"#Edit the cell to write a statement to show the current time\n",
"\n",
"from time import time\n",
"ctime(time())"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Part 4 Other Exercies"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 4.1. (Letter) Company FE would like to generate a seasonal greeting letter to its customer (25 points). \n",
"The letter is as follows:\n",
"\n",
" Dear {Title} {Customer Name},\n",
" Merry Christmas and Happy New Year!\n",
" Best,\n",
" {Your Name}\n",
"\n",
"Here, {Title} and {Customer Name} are input, and {Your Name} is your name.\n",
"\n",
"Write a function to generate the letter for given information about {Title}, {Customer Name}, and {Your Name}, where {Title} and {Customer Name} are from the input, and and {Your Name} is fixed to be your actual name (e.g., for me, {Your Name}='Ken'). \n",
"\n",
"Sample Input \n",
"\n",
" Enter Customer's Title: Ms.\n",
" Enter Customer's Name: Alice GORMALLY\n",
" \n",
"\n",
"Sample Output (where {Your Name} is 'Ken'):\n",
"\n",
" Dear Ms. Alice GORMALLY,\n",
" Merry Christmas and Happy New Year!\n",
" Best,\n",
" Ken"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### (a)"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [],
"source": [
"#edit this cell to define the function and write its body:\n",
"def genGreetingLetter(customer_name, title, your_name):\n",
"\n",
" greeting_letter_template = '''\n",
"Dear {Title} {Customer_Name},\n",
" Merry Christmas and Happy New Year!\n",
"Best,\n",
"{Your_Name}\n",
"'''.strip().replace('{Customer_Name}', customer_name).replace('{Title}', title).replace('{Your_Name}', your_name)\n",
" return greeting_letter_template\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### (b)"
]
},
{
"cell_type": "code",
"execution_count": 24,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"Dear Ms. Alice GORMALLY1,\n",
" Merry Christmas and Happy New Year!\n",
"Best,\n",
"Ken\n",
"\n",
"\n",
"Dear Ms. Alice GORMALLY2,\n",
" Merry Christmas and Happy New Year!\n",
"Best,\n",
"Ken\n",
"\n",
"\n",
"Dear Ms. Alice GORMALLY3,\n",
" Merry Christmas and Happy New Year!\n",
"Best,\n",
"Ken\n",
"\n"
]
}
],
"source": [
"#edit this cell to write a code that uses the function above to generate three letters, \n",
"# where {Title} and {Customer Name} are from the input, \n",
"#and {Your Name} is fixed to be your actual name (e.g., for me, {Your Name}='Ken')\n",
"\n",
"customer_names = []\n",
"customer_titles = []\n",
"my_name = ''\n",
"\n",
"my_name = input(f\"please input your name:\")\n",
"\n",
"for i in range(0,3):\n",
" customer_titles.append(input(f\"Enter Customer's Title {(i+1)}:\"))\n",
" customer_names.append(input(f\"Enter Customer's Name {(i+1)} :\"))\n",
" \n",
"\n",
"\n",
"for i in range(0,len(customer_names)):\n",
" print()\n",
" print(genGreetingLetter(customer_names[i], customer_titles[i], my_name))\n",
" print()\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### (c)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font color='red'>Execute and test your revised code above for various inputs. Edit this cell to copy your test results below:</font>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 4.2. (Email signature) Write a function to print an email signature in the following format (25 points):\n",
" {First Name} {Last Name} \n",
" {Title}\n",
" {Affiliation}\n",
" Email: {Email}\n",
"where {First Name}, {Last Name}, {Title}, {Affiliation}, and {Email} are five parameters of the function.\n",
"\n",
"For example, according to my information, the output will be:\n",
"\n",
" Ken Fong\n",
" Assistant Professor of Teaching\n",
" Lingnan University\n",
" Email: kenfong@ln.edu.hk"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### (a)"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [],
"source": [
"#Edit this cell to define the function and write its body:\n",
"\n",
"def genEmailSignature(first_name, last_name, title, affiliation, email):\n",
"\n",
" signature_template = '''\n",
"{First_Name} {Last_Name}\n",
"{Title}\n",
"{Affiliation}\n",
"Email: {Email}\n",
"'''.strip().replace('{First_Name}', first_name).replace('{Last_Name}', last_name).replace('{Title}', title).replace('{Affiliation}', affiliation).replace('{Email}', email)\n",
" return signature_template\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### (b)"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Ken Fong\n",
"Assistant Professor of Teaching\n",
"Lingnan University\n",
"Email: kenfong@ln.edu.hk\n"
]
}
],
"source": [
"#Edit this cell to write a statement to use the function above to print an email signature for Ken Fong:\n",
"\n",
"print(genEmailSignature('Ken','Fong','Assistant Professor of Teaching','Lingnan University','kenfong@ln.edu.hk'))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### (c)"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Ken Fong\n",
"Assistant Professor of Teaching\n",
"Lingnan University\n",
"Email: kenfong@ln.edu.hk\n"
]
}
],
"source": [
"#Edit this cell to write a statement to use the function above to print an email signature according to your own information\n",
"\n",
"print(genEmailSignature('Ken','Fong','Assistant Professor of Teaching','Lingnan University','kenfong@ln.edu.hk'))"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.10.7"
}
},
"nbformat": 4,
"nbformat_minor": 4
}