{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"tags": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"zsh:1: unknown file attribute: i\n"
]
}
],
"source": [
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# ฟังก์ชัน (Functions)\n",
"\n",
"**55** minutes\n",
"\n",
"## วัตถุประสงค์\n",
"\n",
"**หลังจากทำทำแล็บ นศ.จะสามารถ**\n",
"\n",
"* เข้าใจหลักการของฟังก์ชันและตัวแปรในภาษาไพธอน\n",
"* เขียนฟังก์ชันและเข้าใจการเรียกใช้ฟังก์ชัน/การส่งผ่านข้อมูล\n",
"\n",
"Ref:\n",
"\n",
"* https://docs.python.org/3/tutorial/controlflow.html#defining-functions\n",
"* https://realpython.com/defining-your-own-python-function/\n",
"* https://jakevdp.github.io/PythonDataScienceHandbook/01.01-help-and-documentation.html"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## ฟังก์ชัน (Functions in Python)\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"ฟังก์ชัน (Functions) คือ โปรแกรมย่อยหรือบล็อกของโค้ดที่รวมชุดคำสั่งที่ทำงานเฉพาะเจาะจง สามารถเรียกใช้ซ้ำๆ ได้ ฟังก์ชันช่วยให้เราไม่ต้องเขียนชุดคำสั่งเดิมๆ หลายครั้ง และช่วยย่อยโปรแกรมที่มีความซับซ้อนออกเป็นส่วนๆ ทำให้การเขียนโปรแกรมมีประสิทธิภาพมากขึ้น อ่านเข้าใจได้ง่ายขึ้น\n",
"\n",
"ฟังก์ชันมีคุณสมบัติดังต่อไปนี้ \n",
"* มีชื่อฟังก์ชัน\n",
"* มีหน้าที่เฉพาะเจาะจงชัดเจน\n",
"* มีชุดคำสั่งที่มีลำดับขั้นตอนรวมอยู่ภายใน\n",
"* มีการส่งคืนค่ากลับ (เสมอ)\n",
"* ถูกเรียกใช้ซ้ำๆ ได้\n",
"* ถูกเรียกจากหลายๆ ที่ได้\n",
"\n",
"\n",
"ฟังก์ชันที่ใช้ในภาษาไพธอนสามารถแบ่งออกเป็น 2 ประเภทหลักๆ คือ \n",
"\n",
"1. ฟังก์ชันที่ถูกสร้างไว้แล้ว (Pre-defined function)\n",
"\n",
"ฟังก์ชันที่ถูกสร้างไว้แล้ว (Pre-defined function) เป็นฟังก์ชันที่ถูกสร้างขึ้นโดยผู้พัฒนาไพธอน (ในรูปแบบ Library function) และเป็นส่วนหนึ่งของภาษาไพธอน (Built-in function) เราจึงสามารถเรียกใช้ฟังก์ชันประเภทนี้ได้ทันที เช่น ฟังก์ชัน print( ), input( ), sum( ), len( ) เป็นต้น\n",
"\n",
"2. ฟังก์ชันที่ผู้ใช้สร้างขึ้นเอง (User-Define Functions)\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Built-in functions\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"ในภาษาไพธอน มี Built-in function (หรือ Pre-defined function) มากมายหลายฟังก์ชัน เช่น\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"ฟังก์ชัน print( )"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[10.0, 8.5, 9.5, 7.0, 7.0, 9.5, 9.0, 9.5]\n"
]
}
],
"source": [
"# Build-in function print()\n",
"\n",
"album_ratings = [10.0, 8.5, 9.5, 7.0, 7.0, 9.5, 9.0, 9.5] \n",
"print(album_ratings)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"ฟังก์ชัน sum( ) รับข้อมูลที่เป็น iterable เช่น ลิสต์หรือทูเพิล แล้วคืนค่ากลับเป็นผลรวมของสมาชิกทุกตัวที่อยู่ในลิสต์หรือทูเพิล"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"70.0"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Use sum() to add every element in a list or tuple together\n",
"\n",
"sum(album_ratings)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"ฟังก์ชัน len() ใช้หาขนาดของลิสต์หรือทูเพิล (จำนวนสมาชิก)"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"8"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Show the length of the list or tuple\n",
"\n",
"len(album_ratings)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"∴ หาค่าเฉลี่ยของลิส album_ratings ได้ดังนี้"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"8.75"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"sum(album_ratings)/len(album_ratings)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"เราเรียกข้อมูลที่ส่งให้แก่ฟังก์ชัน (ข้อมูลที่อยู่ในวงเล็บ) เมื่อมีการเรียกฟังก์ชันว่า **อาร์กิวเมนต์ (หรือ Actual Parameter)**"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"นอกจากนี้ยังมีฟังก์ชันที่เคยผ่านตากันมาแล้ว เช่น type(), ascii(), bool(), float(), int(), str(), tuple(), list(), dict(), set(), range(), enumerate(), max(), min(), pow(), abs(), round(), slice(), sorted(), complex( ), help() และอื่นๆ อีก [ดูใน Common Built‐in Functions (Quick Reference Sheet (Python-3.6))](docs/Python3.6_quick_reference_sheet.pdf) หรือศึกษาเพิ่มเติมได้ที่ [Built-in Functions in Python (python.org)](https://docs.python.org/3/library/functions.html)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"
complex( ) มีอาร์กิวเมนต์สองตัว ตัวแรกเป็นจำนวนจริงและตัวที่สองเป็นจำนวนจินตภาพ ดังนั้น complex(3, 5) จึงไม่เท่ากับ complex(5, 3) \n",
"def ตามด้วยชื่อฟังก์ชัน function_name และในวงเล็บ () เป็นการกำหนดพารามิเตอร์ parameters ของฟังก์ชัน \n",
"* พารามิเตอร์ parameters ของฟังก์ชันจะกำหนดให้มีจำนวนเท่าไหร่ก็ได้หรือไม่มีก็ได้ ถ้ามีต้องกำหนดภายในวงเล็บ พารามิเตอร์เป็นตัวแปรภายในฟังก์ชี่น ทำหน้าที่รับค่า/ข้อมูลจากภายนอก (ตอนที่มีการเรียกใช้ฟังก์ชัน)\n",
"* หลังเครื่องหมายวงเล็บปิดจะต้องมีเครื่องหมาย colon (:) ปิดท้าย เพื่อบอกว่า จะเริ่มบล็อกคำสั่งของฟังก์ชันแล้ว\n",
"* บล็อกคำสั่งของฟังก์ชันจะอยู่หลัง : โดยจะอยู่เยื้องย่อหน้าเข้าไป (Indentation)\n",
"* สามารถใส่คำอธิบายการทำงานของฟังก์ชัน (เรียกว่า docstring) ก่อนบล็อกคำสั่งได้โดยเขียนอยู่ภายในเครื่องหมาย triple single quotes ('''...''') หรือ triple double quotes (\"\"\"...\"\"\")\n",
"* คำสั่ง return เป็นการออกจากฟังก์ชัน โดยจะส่งค่ากลับไปยังจุดที่เรียก ฟังก์ชันอาจจะมีหรือไม่มีคำสั่งนี้ก็ได้ (กรณีทีไม่มี ค่าส่งกลับจะเป็น None)\n",
"\n",
"\n",
"ตัวอย่าง การสร้างฟังก์ชันเพิ่มค่าให้กับพารามิเตอร์ a พิมพ์ออกหน้าจอและส่งคืนผลลัพธ์เป็น b "
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [],
"source": [
"# First function example: Add 1 to a and store as b\n",
"def add(a):\n",
" \"\"\"\n",
" add 1 to a\n",
" \"\"\"\n",
" b = a + 1\n",
" print(a, \"if you add one\", b)\n",
" return(b)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"ส่วนประกอบของฟังก์ชัน add( ) "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
" หรือใส่เครื่องหมาย **?** หลังชื่อฟังก์ชัน เพื่อให้แสดงคำอธิบายของฟังก์ชัน (เรียกว่า docstring) ได้\n",
" \n",
"(หากต้องการดู source code ใส่เครื่องหมาย **??** หลังชื่อฟังก์ชัน )"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Help on function add in module __main__:\n",
"\n",
"add(a)\n",
" add 1 to a\n",
"\n"
]
}
],
"source": [
"# Get a help on add function\n",
"\n",
"help(add)"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"\u001b[0;31mSignature:\u001b[0m \u001b[0madd\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0ma\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
"\u001b[0;31mDocstring:\u001b[0m add 1 to a\n",
"\u001b[0;31mFile:\u001b[0m /var/folders/nb/qx4_7k_n2mx3zzwh39qtrg_c0000gn/T/ipykernel_67770/1187279021.py\n",
"\u001b[0;31mType:\u001b[0m function\n"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"add?"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"import \n",
"\n",
"วิธีการเรียกใช้จากโปรแกรมอื่นจะอธิบายในภายหลัง"
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1 if you add one 2\n"
]
},
{
"data": {
"text/plain": [
"2"
]
},
"execution_count": 13,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Call the function add()\n",
"\n",
"add(1)"
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"3 if you add one 4\n"
]
},
{
"data": {
"text/plain": [
"4"
]
},
"execution_count": 14,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Call the function add()\n",
"\n",
"add(3)"
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"3 if you add one 4\n"
]
},
{
"data": {
"text/plain": [
"8"
]
},
"execution_count": 15,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# For Jupyter notebook, you can hit Shift-Tab to bring up the signature and docstring of the function or class\n",
"add(3) + 4"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"เราสามารถสร้างฟังก์ชันใหม่ได้อีก \n",
"\n",
"ยกตัวอย่างเช่น ฟังก์ชันคูณตัวเลขสองตัว โดยจะใช้ตัวแปร a และ b (ฟังก์ชันนี้มีพารามิเตอร์ 2 พารามิเตอร์) รับค่าตัวเลขสองตัว\n"
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"24\n"
]
}
],
"source": [
"# Define a function for multiple two numbers\n",
"\n",
"def Mult(a, b):\n",
" c = a * b\n",
" return(c)\n",
" print('This is not printed')\n",
" \n",
"result = Mult(12,2)\n",
"print(result)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"เรียกฟังก์ชัน Mult( ) ซ้ำอีกครั้ง เพื่อคูณจำนวนเต็ม"
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"6"
]
},
"execution_count": 17,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Use mult() multiply two integers\n",
"\n",
"Mult(2, 3)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"ฟังก์ชัน Mult( ) ใช้กับข้อมูลชนิดอื่นๆ ก็ได้"
]
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"31.400000000000002"
]
},
"execution_count": 18,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Use mult() multiply two floats\n",
"\n",
"Mult(10.0, 3.14)"
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'Michael Jackson Michael Jackson '"
]
},
"execution_count": 19,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Use mult() multiply two different type values together\n",
"\n",
"Mult(2, \"Michael Jackson \")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## ฟังก์ชั้นที่ไม่มีคำสั่ง return (ส่งกลับเป็นค่าพิเศษ None)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"ฟังก์ชันในไพธอนจะคืนค่ากลับมาเสมอ ซึ่งปกติจะใช้ด้วยคำสั่ง return แต่ถ้าไม่มีคำสั่ง return ฟังก์ชันจะส่งกลับเป็น**ค่าพิเศษ None** (By default (NoneType); null value or no value at all เป็นข้อมูลชนิดหนึ่งในไพธอน) ดังนั้น ฟังก์ชันทั้ง 2 ฟังก์ชันต่อไปนี้เหมือนกันมีค่าเท่ากัน"
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {},
"outputs": [],
"source": [
"# Define functions, one with return value None and other without return value\n",
"\n",
"def MJ():\n",
" print('Michael' + ' ' + 'Jackson')\n",
" \n",
"def MJ1():\n",
" MJ()\n",
" return(None)"
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Michael Jackson\n"
]
}
],
"source": [
"# See the output\n",
"\n",
"MJ()"
]
},
{
"cell_type": "code",
"execution_count": 22,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Michael Jackson\n"
]
}
],
"source": [
"# See the output\n",
"\n",
"MJ1()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"ถ้าใช้คำสั่ง print กับฟังก์ชันที่ไม่มีคำสั่ง return (ฟังก์ชันที่ไม่มีค่าคืนกลับ) จะส่งค่าคืนกลับเป็น **None** (By default)"
]
},
{
"cell_type": "code",
"execution_count": 23,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Michael Jackson\n",
"None\n",
"Michael Jackson\n",
"None\n"
]
}
],
"source": [
"# See what functions returns are\n",
"\n",
"print(MJ())\n",
"print(MJ1())"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"ลองสร้างฟังก์ชัน con( ) สำหรับเชื่อม 2 สตริงเข้าด้วยกันโดยใช้โอเปอเรเตอร์ **\"+\"**\n"
]
},
{
"cell_type": "code",
"execution_count": 24,
"metadata": {},
"outputs": [],
"source": [
"# Define the function for combining strings\n",
"\n",
"def con(a, b):\n",
" return(a + ' ' + b)"
]
},
{
"cell_type": "code",
"execution_count": 25,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'Michael Jackson'"
]
},
"execution_count": 25,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Test on the con() function\n",
"\n",
"con(\"Michael\", \"Jackson\")"
]
},
{
"cell_type": "code",
"execution_count": 26,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'Jackson Michael'"
]
},
"execution_count": 26,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Test on the con() function\n",
"\n",
"con(\"Jackson\", \"Michael\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"square( ) และการเรียกใช้ฟังก์ชัน "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"z"
]
},
{
"cell_type": "code",
"execution_count": 30,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"100 if you square + 1 10001\n"
]
},
{
"data": {
"text/plain": [
"10001"
]
},
"execution_count": 30,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Directly enter a number as parameter\n",
"\n",
"square(100)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"ทราบหรือไม่ว่า โค้ดในรูปภาพข้างต้น ตัวแปรใดเป็นพารามิเตอร์ของฟังก์ชัน square() ตัวแปรใดเป็นตัวแปรโลคอล (Local Variable) และตัวแปรใดเป็นตัวแปรโกลบอล (Global Variable) บ้าง??"
]
},
{
"cell_type": "code",
"execution_count": 31,
"metadata": {},
"outputs": [],
"source": [
"# Check your answer\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"รายละเอียดของขอบเขตของตัวแปร (Scope of a Variable) จะอธิบายอีกครั้งภายหลัง\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Equation( ) มีอินพุตสองค่าคือ a และ b หลังประมวลผลเสร็จ จะคืนค่ากลับเป็น c หลังจากที่ประกาศฟังก์ชั้นแล้ว เราก็สามารถเขียนคำสั่งหลายบรรทัดข้างต้นให้สั้นลงได้\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"c1"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Block 4:**\n"
]
},
{
"cell_type": "code",
"execution_count": 36,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"0"
]
},
"execution_count": 36,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"a2 = 0\n",
"b2 = 0\n",
"c2 = Equation(a2, b2)\n",
"c2"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**ฟังก์ชันทำให้การเขียนโปรแกรมทำได้ง่ายขึ้น โปรแกรมสั้นกระชับและอ่านง่ายได้ขึ้น**"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"if/else และคำสั่งลูปในฟังก์ชัน"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"เราสามารถคืนค่ากลับแบบมีเงื่อนไขได้โดยใช้คำสั่ง if และคำสั่ง return() \n"
]
},
{
"cell_type": "code",
"execution_count": 37,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Michael Jackson Thriller 1980\n",
"Oldie\n"
]
}
],
"source": [
"# Function example\n",
"\n",
"def type_of_album(artist, album, year_released):\n",
" print(artist, album, year_released)\n",
" if year_released > 1980:\n",
" return \"Modern\"\n",
" else:\n",
" return \"Oldie\"\n",
" \n",
"x = type_of_album(\"Michael Jackson\", \"Thriller\", 1980)\n",
"print(x)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"เขียนฟังก์ชันสั่งให้ print( ) สมาชิกทุกตัวที่อยู่ในลิสต์โดยใช้คำสั่งวนลูป (For loop)\n"
]
},
{
"cell_type": "code",
"execution_count": 38,
"metadata": {},
"outputs": [],
"source": [
"# Print the list using for loop\n",
"\n",
"def PrintList(the_list):\n",
" for element in the_list:\n",
" print(element)"
]
},
{
"cell_type": "code",
"execution_count": 39,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1\n",
"1\n",
"the man\n",
"abc\n",
"('x', 'y')\n"
]
}
],
"source": [
"# Implement the printlist function\n",
"\n",
"PrintList(['1', 1, 'the man', \"abc\", ('x','y')])"
]
},
{
"cell_type": "code",
"execution_count": 40,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"愛\n",
"し\n",
"て\n",
"い\n",
"る\n"
]
}
],
"source": [
"# Implement the printlist function\n",
"\n",
"PrintList('愛している')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"isGoodRating() ต่อไปนี้ กำหนดค่าปริยายให้กับอาร์กิวเมนต์ (rating) เป็น 4\n"
]
},
{
"cell_type": "code",
"execution_count": 41,
"metadata": {},
"outputs": [],
"source": [
"# Example for setting param with default value\n",
"\n",
"def isGoodRating(rating=4): \n",
" if(rating < 7):\n",
" print(\"this album sucks, it's rating is\",rating)\n",
" \n",
" else:\n",
" print(\"this album is good, its rating is\",rating)\n"
]
},
{
"cell_type": "code",
"execution_count": 42,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"this album sucks, it's rating is 4\n",
"this album is good, its rating is 10\n"
]
}
],
"source": [
"# Test the value with default value and with input\n",
"\n",
"isGoodRating()\n",
"isGoodRating(10)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"อีกตัวอย่าง ฟังก์ชัน greeting() ต่อไปนี้ มี 2 อาร์กิวเมนต์ คือ name และ msg"
]
},
{
"cell_type": "code",
"execution_count": 43,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Hello Michael, Good morning!\n"
]
}
],
"source": [
"# Python Function Arguments: Positional, Keywords and Default\n",
"def greeting(name, msg):\n",
" \"\"\"This function greets to\n",
" the person with the provided message\n",
" The arguments name and msg are expected to be of type str.\"\"\"\n",
" print(\"Hello\", name + ', ' + msg)\n",
"\n",
"greeting(\"Michael\", \"Good morning!\")"
]
},
{
"cell_type": "code",
"execution_count": 44,
"metadata": {},
"outputs": [
{
"ename": "TypeError",
"evalue": "greeting() missing 1 required positional argument: 'msg'",
"output_type": "error",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)",
"Cell \u001b[0;32mIn [44], line 1\u001b[0m\n\u001b[0;32m----> 1\u001b[0m \u001b[43mgreeting\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[38;5;124;43mMichael\u001b[39;49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[43m)\u001b[49m\n",
"\u001b[0;31mTypeError\u001b[0m: greeting() missing 1 required positional argument: 'msg'"
]
}
],
"source": [
"greeting(\"Michael\") # only one argument: TypeError: greeting() missing 1 required positional argument: 'msg'"
]
},
{
"cell_type": "code",
"execution_count": 45,
"metadata": {},
"outputs": [
{
"ename": "TypeError",
"evalue": "greeting() missing 2 required positional arguments: 'name' and 'msg'",
"output_type": "error",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)",
"Cell \u001b[0;32mIn [45], line 1\u001b[0m\n\u001b[0;32m----> 1\u001b[0m \u001b[43mgreeting\u001b[49m\u001b[43m(\u001b[49m\u001b[43m)\u001b[49m\n",
"\u001b[0;31mTypeError\u001b[0m: greeting() missing 2 required positional arguments: 'name' and 'msg'"
]
}
],
"source": [
"greeting() # no arguments: TypeError: greeting() missing 2 required positional arguments: 'name' and 'msg'"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"เพิ่มความยืดหยุ่น โดยการกำหนดค่าเริ่มต้น (ค่าปริยาย) ให้กับอาร์กิวเมนต์ (Default argument)"
]
},
{
"cell_type": "code",
"execution_count": 46,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Hello Michael, Good morning!\n",
"Hello John, How do you do?\n"
]
}
],
"source": [
"# Python Function Arguments: Positional, Keywords and Default\n",
"def greeting(name, msg=\"Good morning!\"):\n",
" \"\"\"This function greets to\n",
" the person with the provided message\n",
" The arguments name and msg are expected to be of type str.\"\"\"\n",
" print(\"Hello\", name + ', ' + msg)\n",
"\n",
"greeting(\"Michael\")\n",
"greeting(\"John\", \"How do you do?\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"แต่ถ้าเราลองสลับตำเหน่งของพารามิเตอร์ จะเกิดอะไรขึ้น? → เกิด SyntaxError: non-default argument follows default argument"
]
},
{
"cell_type": "code",
"execution_count": 47,
"metadata": {},
"outputs": [
{
"ename": "SyntaxError",
"evalue": "non-default argument follows default argument (2100380144.py, line 1)",
"output_type": "error",
"traceback": [
"\u001b[0;36m Cell \u001b[0;32mIn [47], line 1\u001b[0;36m\u001b[0m\n\u001b[0;31m def greeting(msg=\"Good morning!\", name):\u001b[0m\n\u001b[0m ^\u001b[0m\n\u001b[0;31mSyntaxError\u001b[0m\u001b[0;31m:\u001b[0m non-default argument follows default argument\n"
]
}
],
"source": [
"def greeting(msg=\"Good morning!\", name):\n",
" \"\"\"This function greets to\n",
" the person with the provided message\n",
" The arguments name and msg are expected to be of type str.\"\"\"\n",
" print(\"Hello\", name + ', ' + msg)\n",
"\n",
"greeting(\"Michael\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"SyntaxError: non-default argument follows default argument คือ ???\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\\*args และ \\*\\*kwargs แทน \\*tuple_parameter และ \\*\\*dictionary_parameter ตามลำดับ เนื่องจากสะดวกนั่นเอง\n",
"\n",
"* \\*tuple_parameter (*args) - อาร์กิวเมนต์ (Areguments) จำนวนใดๆ \n",
"* \\*\\*dictionary_parameter (**kwargs) - คีย์เวิร์ดอาร์กิวเมนต์ (Keyword arguments) จำนวนใดๆ \n",
"```\n",
"\n",
"ดังนั้น เขียนใหม่ได้ว่า\n",
"\n",
"**Function syntax:**\n",
"\n",
"```python\n",
"def myList ไม่ได้จำกัดอยู่เฉพาะในฟังก์ชันเท่านั้น\n",
"\n",
"เนื่องจากลิสส่งค่าโดยใช้การอ้างอิง (Pass by Reference) ซึ่งการส่งแบบนี้จะไม่มีการสร้างสำเนาเก็บค่าของตัวแปร แต่จะเป็นการอ้างอิงตำแหน่งในหน่วยความจำของตัวแปร ทำให้ตัวแปรที่ส่งไปยังฟังก์ชันและตัวแปรในฟังก์ชันใช้หน่วยความจำร่วมกัน ดังนั้นเมื่อตัวแปรในฟังก์ชันมีการเปลี่ยนค่า ตัวแปรที่ส่งค่าไปก็จะเปลี่ยนค่าด้วย **ดังนั้น ควรระมัดระวังกรณีที่ส่งผ่านอ็อบเจกต์ชนิด mutable ไปยังฟังก์ชัน**\n",
"\n",
"myFavouriteBand เป็นตัวแปรโกลบอล (Global Variable) สามารถเข้าถึงได้จากทุกๆ ส่วนในโปรแกรม เช่น ภายในฟังก์ชัน getBandRating( ) ก็สามารถเข้าถึงตัวแปรนี้ได้"
]
},
{
"cell_type": "code",
"execution_count": 60,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"AC/DC's rating is: 10.0\n",
"Deep Purple's rating is: 0.0\n",
"My favourite band is: AC/DC\n"
]
}
],
"source": [
"# Example of global variable\n",
"\n",
"myFavouriteBand = \"AC/DC\"\n",
"\n",
"def getBandRating(bandname):\n",
" if bandname == myFavouriteBand:\n",
" return 10.0\n",
" else:\n",
" return 0.0\n",
"\n",
"print(\"AC/DC's rating is:\", getBandRating(\"AC/DC\"))\n",
"print(\"Deep Purple's rating is:\",getBandRating(\"Deep Purple\"))\n",
"print(\"My favourite band is:\", myFavouriteBand)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"ตัวอย่างต่อไปนี้ ตัวแปร myFavouriteBand เป็นตัวแปรโลคอล (Local Variable) เนื่องจากถูกประกาศภายในฟังก์ชัน getBandRating( ) นั่นหมายความว่าสามารถเข้าถึงเฉพาะภายในฟังก์ชัน getBandRating( ) เท่านั้น\n",
"(ถ้าเรียกใช้จะเกิดความผิดพลาดหรือเออเรอร์ NameError: name 'myFavouriteBand' is not defined)"
]
},
{
"cell_type": "code",
"execution_count": 61,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"AC/DC's rating is: 10.0\n",
"Deep Purple's rating is: 0.0\n"
]
},
{
"ename": "NameError",
"evalue": "name 'myFavouriteBand' is not defined",
"output_type": "error",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)",
"Cell \u001b[0;32mIn [61], line 16\u001b[0m\n\u001b[1;32m 14\u001b[0m \u001b[38;5;28mprint\u001b[39m(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mAC/DC\u001b[39m\u001b[38;5;124m'\u001b[39m\u001b[38;5;124ms rating is: \u001b[39m\u001b[38;5;124m\"\u001b[39m, getBandRating(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mAC/DC\u001b[39m\u001b[38;5;124m\"\u001b[39m))\n\u001b[1;32m 15\u001b[0m \u001b[38;5;28mprint\u001b[39m(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mDeep Purple\u001b[39m\u001b[38;5;124m'\u001b[39m\u001b[38;5;124ms rating is: \u001b[39m\u001b[38;5;124m\"\u001b[39m, getBandRating(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mDeep Purple\u001b[39m\u001b[38;5;124m\"\u001b[39m))\n\u001b[0;32m---> 16\u001b[0m \u001b[38;5;28mprint\u001b[39m(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mMy favourite band is\u001b[39m\u001b[38;5;124m\"\u001b[39m, \u001b[43mmyFavouriteBand\u001b[49m)\n",
"\u001b[0;31mNameError\u001b[0m: name 'myFavouriteBand' is not defined"
]
}
],
"source": [
"# Deleting the variable \"myFavouriteBand\" from the previous example to demonstrate an example of a local variable \n",
"\n",
"del myFavouriteBand\n",
"\n",
"# Example of local variable\n",
"\n",
"def getBandRating(bandname):\n",
" myFavouriteBand = \"AC/DC\"\n",
" if bandname == myFavouriteBand:\n",
" return 10.0\n",
" else:\n",
" return 0.0\n",
"\n",
"print(\"AC/DC's rating is: \", getBandRating(\"AC/DC\"))\n",
"print(\"Deep Purple's rating is: \", getBandRating(\"Deep Purple\"))\n",
"print(\"My favourite band is\", myFavouriteBand)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"ตัวอย่างสุดท้าย \n",
"\n",
"เรามีตัวแปร myFavouriteBand 2 ตัวแปร (ชื่อเดียวกัน) ตัวแรกเป็นตัวแปรโกลบอล ตัวที่สองเป็นตัวแปรโลคอลอยู่ภายในฟังก์ชัน getBandRating( )\n",
"\n",
"\n",
"**เงื่อนไขการทำงานของตัวแปรกรณีที่ชื่อตัวแปรโกลบอลมีชื่อเดียวกับตัวแปรโลคอล:** \n",
"ถ้ามีการเรียกใช้ตัวแปรที่โปรแกรมหลัก ไพธอนจะประมวลผลกับตัวแปรโกลบอล แต่ถ้าเป็นการเรียกใช้หรือประมวลผลภายในฟังก์ชัน ไพธอนจะประมวลผลที่ตัวแปรโลคอล **(แม้ตัวแปรจะมีชื่อเดียวกัน แต่ถือเป็นตัวแปรคนละตัวกัน มีขอบเขตการใช้งานที่ต่างกัน!)**"
]
},
{
"cell_type": "code",
"execution_count": 62,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"AC/DC's rating is: 0.0\n",
"Deep Purple's rating is: 10.0\n",
"My favourite band is: AC/DC\n"
]
}
],
"source": [
"# Example of global variable and local variable with the same name\n",
"\n",
"myFavouriteBand = \"AC/DC\"\n",
"\n",
"def getBandRating(bandname):\n",
" myFavouriteBand = \"Deep Purple\"\n",
" if bandname == myFavouriteBand:\n",
" return 10.0\n",
" else:\n",
" return 0.0\n",
"\n",
"print(\"AC/DC's rating is:\",getBandRating(\"AC/DC\"))\n",
"print(\"Deep Purple's rating is: \",getBandRating(\"Deep Purple\"))\n",
"print(\"My favourite band is:\",myFavouriteBand)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"global เท่านั้น) \n",
" \n",
"\n",
"* ตัวแปรที่ประกาศภายนอกฟังก์ชันหรือใน Global scope จะเรียกว่า **ตัวแปรโกลบอล (Global Variable)** สามารถเรียกใช้งานได้ทั้งโปรแกรม ไม่ว่าจะภายในหรือภายนอกฟังก์ชัน **แต่การแก้ไขจะทำได้เฉพาะใน Global scope เท่านั้นไม่สามารถแก้ไขภายในฟังก์ชันได้**\n",
"\n",
"printer1( ) ดูผลลัพธ์ที่เกิดขึ้น\n"
]
},
{
"cell_type": "code",
"execution_count": 63,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Michael Jackson is an artist\n"
]
}
],
"source": [
"# Example of global variable\n",
"\n",
"artist = \"Michael Jackson\"\n",
"def printer1(artist):\n",
" internal_var = artist\n",
" print(artist, \"is an artist\")\n",
" \n",
"printer1(artist)\n",
"# try runningthe following code\n",
"#printer1(internal_var) "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"ทำไมถึงเกิดข้อผิดพลาด Name Error: name 'internal_var' is not defined. \n",
"\n",
"เพราะว่าตัวแปรที่ประกาศภายในฟังก์ชันเป็น **ตัวแปรโลคอล (Local Variable)** ไม่สามารถที่จะถูกเรียกจากภายในฟังก์ชันได้\n",
"\n",
"แต่ก็มีวิธีที่จะเปลี่ยนตัวแปรในฟังก์ชันให้เป็น **ตัวแปรโกลบอล (Global Variable)** ได้ ดังตัวอย่างต่อไปนี้\n"
]
},
{
"cell_type": "code",
"execution_count": 64,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Michael Jackson is an artist\n",
"Whitney Houston is an artist\n"
]
}
],
"source": [
"artist = \"Michael Jackson\"\n",
"\n",
"def printer(artist):\n",
" global internal_var \n",
" internal_var= \"Whitney Houston\"\n",
" print(artist,\"is an artist\")\n",
"\n",
"printer(artist) \n",
"printer(internal_var)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"```{Note}\n",
"การเขียนโปรแกรมที่ดีไม่ควรเรียกใช้ตัวแปรนอกเขตของตัวเอง ทั้งนี้เพื่อไม่ให้เกิดความสับสน โดยเฉพาะในกรณีของโปรแกรมที่มีขนาดใหญ่\n",
"```"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## [Exersice] Scope of variables"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"1) หลังจากรันโค้ดต่อไปนี้ Output บนหน้าจอเป็นอย่างไร? (เพราะเหตุใด จงอธิบาย)\n",
"\n",
"```python\n",
"def f(x):\n",
" x *= 5\n",
" return x\n",
"\n",
"def g(x):\n",
" y = f(x**2)\n",
" z = f(x**3)\n",
" return y + z\n",
"\n",
"print(g(2))\n",
"```"
]
},
{
"cell_type": "code",
"execution_count": 65,
"metadata": {},
"outputs": [],
"source": [
"# Write your code below and press Shift+Enter to execute\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"2) หลังจากรันโค้ดต่อไปนี้ Output พรินท์ออกหน้าจอเป็นอย่างไร? (เพราะเหตุใด จงอธิบาย)\n",
"\n",
"```python\n",
"def f(x):\n",
" x += 8\n",
" return round(x / 6)\n",
"\n",
"def g(x):\n",
" x *= 15\n",
" return 2 * f(x)\n",
"\n",
"def h(x):\n",
" x += 2\n",
" return f(x+1) + g(x)\n",
"\n",
"print(h(f(1)))\n",
"```"
]
},
{
"cell_type": "code",
"execution_count": 66,
"metadata": {},
"outputs": [],
"source": [
"# Write your code below and press Shift+Enter to execute\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"3) หลังจากรันโค้ดต่อไปนี้ Output พรินท์ออกหน้าจอเป็นอย่างไร? \n",
"\n",
"```python\n",
"g = 110\n",
"\n",
"def f(x):\n",
" return x + g\n",
"\n",
"print(f(5))\n",
"print(f(10))\n",
"print(g)\n",
"```"
]
},
{
"cell_type": "code",
"execution_count": 67,
"metadata": {},
"outputs": [],
"source": [
"# Write your code below and press Shift+Enter to execute\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"4) หลังจากรันโค้ดก่อนหน้าตามด้วยการรันโค้ดต่อไปนี้ Output พรินท์ออกหน้าจอเป็นอย่างไร?\n",
"\n",
"```python\n",
"def f(x):\n",
" global g\n",
" g += 1\n",
" return x + g\n",
"\n",
"print(f(5))\n",
"print(f(6))\n",
"print(g)\n",
"```"
]
},
{
"cell_type": "code",
"execution_count": 68,
"metadata": {},
"outputs": [],
"source": [
"# Write your code below and press Shift+Enter to execute\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## [Exercise] Functions"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"1 สร้างฟังก์ชัน div( ) ที่คำนวณค่า อินพุตตัวแรกหารด้วยอินพุตตัวที่สอง"
]
},
{
"cell_type": "code",
"execution_count": 69,
"metadata": {},
"outputs": [],
"source": [
"# Write your code below and press Shift+Enter to execute\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"con( ) ที่กำหนดต่อไปนี้ จงตอบคำถาม"
]
},
{
"cell_type": "code",
"execution_count": 70,
"metadata": {},
"outputs": [],
"source": [
"# Use the con function for the following question\n",
"\n",
"def con(a, b):\n",
" return(a + b)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"2.1 ฟังก์ชัน con ที่ประกาศไป สามารถใช้บวกตัวเลขจำนวนเต็ม (int) สองจำนวนหรือสตริง (str) สองข้อความได้หรือไม่\n"
]
},
{
"cell_type": "code",
"execution_count": 71,
"metadata": {},
"outputs": [],
"source": [
"# Write your code below and press Shift+Enter to execute\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"2.2 ฟังก์ชัน con ที่ประกาศไป สามารถใช้กับข้อมูลประเภท Collections เช่น lists หรือ tuples ได้หรือไม่?\n"
]
},
{
"cell_type": "code",
"execution_count": 72,
"metadata": {},
"outputs": [],
"source": [
"# Write your code below and press Shift+Enter to execute\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"---"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\"\"Stay Hungry Stay Foolish\" - Steve Jobs (2005)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"---"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Author\n",
"\n",
"S.C.\n",
"\n",
"### Change Log\n",
"\n",
" \n",
"| Date | Version | Change Description |\n",
"|---|---|---|\n",
"| 08-08-2021 | 0.1 | First edition |\n",
"| | | |\n",
"| | | |\n"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel(3.8.13))",
"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.8.13"
},
"latex_envs": {
"LaTeX_envs_menu_present": true,
"autoclose": false,
"autocomplete": true,
"bibliofile": "biblio.bib",
"cite_by": "apalike",
"current_citInitial": 1,
"eqLabelWithNumbers": true,
"eqNumInitial": 1,
"hotkeys": {
"equation": "Ctrl-E",
"itemize": "Ctrl-I"
},
"labels_anchors": false,
"latex_user_defs": false,
"report_style_numbering": false,
"user_envs_cfg": false
},
"toc": {
"base_numbering": 1,
"nav_menu": {},
"number_sections": true,
"sideBar": true,
"skip_h1_title": true,
"title_cell": "Table of Contents",
"title_sidebar": "Contents",
"toc_cell": false,
"toc_position": {
"height": "calc(100% - 180px)",
"left": "10px",
"top": "150px",
"width": "327.628px"
},
"toc_section_display": true,
"toc_window_display": false
},
"vscode": {
"interpreter": {
"hash": "e921dbf9f2d20a8528fa054ff97aae3eb23f1abc9a6f29b7bcee4307a5b88bad"
}
}
},
"nbformat": 4,
"nbformat_minor": 4
}