{ "cells": [ { "cell_type": "code", "execution_count": 1, "metadata": { "tags": [] }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "zsh:1: unknown file attribute: i\n" ] } ], "source": [ "![](images/python_with_Birds.gif)\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": [ "
\n", " \n", "**\"ลำดับ (ตำแหน่ง) ของอาร์กิวเมนต์ที่ส่งให้แก่ฟังก์ชัน\" สำคัญ !!**\n", "\n", "ถ้าลำดับผิดอาจจะทำให้การประมวลผลผิดพลาด ((Logic Errors) กล่าวคือ ได้ผลลัพธ์ที่ไม่ถูกต้องตามที่ต้องการหรือตามที่ควรจะเป็น โดยที่โปรแกรมยังทำงานต่อตามปกติ (ไม่แสดงข้อผิดพลาดหรือเออเร่อ)\n", " \n", "ยกตัวอย่างเช่น จำนวนเชิงซ้อน complex( ) มีอาร์กิวเมนต์สองตัว ตัวแรกเป็นจำนวนจริงและตัวที่สองเป็นจำนวนจินตภาพ ดังนั้น complex(3, 5) จึงไม่เท่ากับ complex(5, 3) \n", "
" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(3+5j)" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "complex(3, 5) " ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Help on class complex in module builtins:\n", "\n", "class complex(object)\n", " | complex(real=0, imag=0)\n", " | \n", " | Create a complex number from a real part and an optional imaginary part.\n", " | \n", " | This is equivalent to (real + imag*1j) where imag defaults to 0.\n", " | \n", " | Methods defined here:\n", " | \n", " | __abs__(self, /)\n", " | abs(self)\n", " | \n", " | __add__(self, value, /)\n", " | Return self+value.\n", " | \n", " | __bool__(self, /)\n", " | self != 0\n", " | \n", " | __divmod__(self, value, /)\n", " | Return divmod(self, value).\n", " | \n", " | __eq__(self, value, /)\n", " | Return self==value.\n", " | \n", " | __float__(self, /)\n", " | float(self)\n", " | \n", " | __floordiv__(self, value, /)\n", " | Return self//value.\n", " | \n", " | __format__(...)\n", " | complex.__format__() -> str\n", " | \n", " | Convert to a string according to format_spec.\n", " | \n", " | __ge__(self, value, /)\n", " | Return self>=value.\n", " | \n", " | __getattribute__(self, name, /)\n", " | Return getattr(self, name).\n", " | \n", " | __getnewargs__(...)\n", " | \n", " | __gt__(self, value, /)\n", " | Return self>value.\n", " | \n", " | __hash__(self, /)\n", " | Return hash(self).\n", " | \n", " | __int__(self, /)\n", " | int(self)\n", " | \n", " | __le__(self, value, /)\n", " | Return self<=value.\n", " | \n", " | __lt__(self, value, /)\n", " | Return self complex\n", " | \n", " | Return the complex conjugate of its argument. (3-4j).conjugate() == 3+4j.\n", " | \n", " | ----------------------------------------------------------------------\n", " | Static methods defined here:\n", " | \n", " | __new__(*args, **kwargs) from builtins.type\n", " | Create and return a new object. See help(type) for accurate signature.\n", " | \n", " | ----------------------------------------------------------------------\n", " | Data descriptors defined here:\n", " | \n", " | imag\n", " | the imaginary part of a complex number\n", " | \n", " | real\n", " | the real part of a complex number\n", "\n" ] } ], "source": [ "help(complex)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "อย่างไรก็ตาม ภาษาไพธอนสามารถเรียกใช้ฟังก์ชันแบบ **Keyword Arguments** ได้ ความสามารถนี้ทำให้เราไม่ต้องส่งอาร์กิวเมนต์ตามลำดับก็ได้ ดังตัวอย่างต่อไปนี้\n", " " ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(3+5j)" ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "complex(imag=5, real=3)" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "complex(imag=5, real=3) == complex(3, 5)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## การสร้างฟังก์ชัน" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "**Function syntax:**\n", "\n", "```python\n", "def ([]):\n", " \n", " .\n", " .\n", " .\n", " \n", "```\n", "\n", "เราสามารถสร้างฟังก์ชันขึ้นเองได้ รูปแบบการประกาศฟังก์ชันมีกฎง่ายๆ มีดังนี้\n", "\n", "\n", "ใช้คำสั่ง def และหลังจากนั้น function_name เป็นชื่อของฟังก์ชัน และในวงเล็บ () เป็นการกำหนดพารามิเตอร์ของฟังก์ชัน พารามิเตอร์ของฟังก์ชันนั้นสามารถมีจำนวนเท่าไหร่ก็ได้หรือไม่มีก็ได้ และเช่นเดียวกับภาษาอื่นๆ ฟังก์ชันอาจจะมีหรือไม่มีการส่งค่ากลับก็ได้ (สำหรับฟังก์ชันที่ไม่มีการ return ค่ากลับนั้น เราจะเรียกว่า Procedure)\n", "\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": [ "![](images/FuncsDefinition.png\" width=\"350\" /> \n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "เราสามารถใช้คำสั่ง help() หรือใส่เครื่องหมาย **?** หลังชื่อฟังก์ชัน เพื่อให้แสดงคำอธิบายของฟังก์ชัน (เรียกว่า 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": [ "
\n", " ถ้าใช้ Jupyter notebook หรือ Google colab ดู DocString ของฟังก์ชันได้โดยการกดคีย์ shift+tab\n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "การเรียกใช้ฟังก์ชันสามารถทำได้ 2 วิธี คือ \n", "\n", "1. เรียกใช้จากโปรแกรมเดียวกัน (จากไฟล์เดียวกัน) และ \n", "2. เรียกใช้จากโปรแกรมอื่น (จากไฟล์อื่น) \n", "\n", "ณ ที่นี้ เราจะเรียกใช้ฟังก์ชันจากโปรแกรมเดียวกัน (จากไฟล์เดียวกัน)\n", "\n", "ส่วนวิธีเรียกใช้จากโปรแกรมอื่น (จากไฟล์อื่น) เป็นวิธีสำหรับการเขียนโปรแกรมที่มีขนาดใหญ่และมีความซับซ้อน ซึ่งมักจะนำฟังก์ชันจัดเก็บเป็นโมดูล (Module) เพื่อให้โปรแกรมต่างๆ สามารถเรียกใช้ผ่านคำสั่ง 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": [ "
\n", " \n", "**ลำดับของอาร์กิวเมนต์ที่อินพุตลงในฟังก์ชันต้องตรงกับลำดับของพารามิเตอร์หรือตัวแปรที่ประกาศภายในฟังก์ชัน (∵ Positional Argument)**\n", " \n", "หากว่าเราใส่อาร์กิวเมนต์ไม่ตรงกับลำดับของพารามิเตอร์ในขณะเรียกใช้ฟังก์ชัน อาจทำให้ประมวลผลผิดพลาด (ผลลัพธ์ที่ได้ไม่ถูกต้อง ไม่เป็นไปตามที่ต้องการหรือที่ควรจะเป็น) โดยที่โปรแกรมยังทำงานต่อได้ตามปกติ (ไม่ Error) **แต่หากเรากำหนดข้อมูลไม่ครบตามจำนวนพารามิเตอร์ โปรแกรมก็จะเกิดข้อผิดพลาด (Error) และหยุดการทำงาน** \n", " \n", "
\n" ] }, { "cell_type": "code", "execution_count": 27, "metadata": {}, "outputs": [ { "ename": "TypeError", "evalue": "con() missing 1 required positional argument: 'b'", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)", "Cell \u001b[0;32mIn [27], line 3\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[38;5;66;03m# Test on the con() function\u001b[39;00m\n\u001b[0;32m----> 3\u001b[0m \u001b[43mcon\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: con() missing 1 required positional argument: 'b'" ] } ], "source": [ "# Test on the con() function\n", "\n", "con('Michael')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## ตัวแปร (Variables) ในฟังก์ชัน\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**รูปแบบในการเรียกฟังก์ชัน**\n", "\n", "```python\n", "()\n", "```\n", "\n", "โดยที่ \n", "* function_name คือ ชื่อของฟังก์ชันที่ประกาศไว้ก่อนหน้านี้\n", "* agument คือ ค่าของข้อมูลที่เราใส่ไปในฟังก์ชัน (โดยค่าดังกล่าวจะถูกส่งผ่านไปให้ตัวแปร (parameter) ของใช้ฟังก์ชันนั้นๆ) \n", "\n", "**[ข้อควรระวัง]**\n", "ลำดับของอาร์กิวเมนต์ต้องตรงกับลำดับตำแหน่งของพารามิเตอร์ที่ประกาศภายไว้ (∵ Positional Argument) ถ้าฟังก์ชันที่เรียกใช้ไม่มีพารามิเตอร์ก็ไม่ต้องใส่ค่าอาร์กิวเมนต์" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "เมื่อมีการเรียกฟังก์ชัน ค่าของข้อมูลที่ส่งไปให้ฟังก์ชันจะถูกเก็บในตัวแปรที่ประกาศไว้ในวงเล็บหลังชื่อของฟังก์ชัน เราเรียกตัวแปรนี้ว่า **Function parameter หรือ Formal parameter** \n", "\n", "\n", "ตัวแปรที่ประกาศภายในฟังก์ชันรวมถึงพารามิเตอร์ของฟังก์ชันซึ่งถือเป็นส่วนหนึ่งของฟังก์ชั้นเป็น **ตัวแปรโลคอล (Local Variable)** **มีขอบเขตการใช้งาน (ทั้งการเรียกใช้และการแก้ไข) เฉพาะภายในฟังก์ชันเท่านั้น!** หากมีการเรียกใช้จากภายนอกฟังก์ชัน จะเกิดข้อผิดพลาดเนื่องจากไม่มีข้อมูลของตัวแปร (ยกเว้นแต่จะถูกกำหนดให้เป็นตัวแปรร่วม (ตัวแปรโกลบอล (Global Variable) เท่านั้น)\n", "\n", "รายละเอียดระหว่าง **ตัวแปรโลคอล (Local Variable)** และ **ตัวแปรโกลบอล (Global Variable)** จะอธิบายภายหลัง" ] }, { "cell_type": "code", "execution_count": 28, "metadata": {}, "outputs": [], "source": [ "# Function Definition\n", "\n", "def square(a):\n", " '''\n", " Square the input and add 1\n", " '''\n", " # Local variable b\n", " b = 1\n", " c = a*a + b\n", " print(a, \"if you square + 1\", c) \n", " return(c)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "รูปด้านล่างแสดงส่วนประกอบของฟังก์ชัน square( ) และการเรียกใช้ฟังก์ชัน " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "![](images/FuncsVar.png\" width=\"450\" />\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "เราสามารถเรียกฟังก์ชันโดยส่งอินพุต 22 ผ่านตัวแปร x" ] }, { "cell_type": "code", "execution_count": 29, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "22 if you square + 1 485\n" ] }, { "data": { "text/plain": [ "485" ] }, "execution_count": 29, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Initializes Global variable \n", "\n", "x = 22\n", "# Makes function call and return function to z\n", "z = square(x)\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": [ "
\n", " \n", "**
อาร์กิวเมนต์ (Argument) และ พารามิเตอร์ (Parameter) ต่างกัน/?
**\n", " \n", "**อาร์กิวเมนต์ (หรือ Actual Parameter)** คือข้อมูลที่ส่งให้แก่ฟังก์ชันเมื่อมีการเรียกใช้ฟังก์ชัน เมื่อมีการเรียกใช้ฟังก์ชันโดยการส่งอาร์กิวเมนต์ให้แก่ฟังก์ชัน ค่าของอาร์กิวเมนต์จะถูกก๊อปปี้ให้กับพารามิเตอร์ที่สัมพันธ์กันภายในฟังก์ชัน (ฉะนั้น Argument != Parameter)\n", "\n", "**พารามิเตอร์ (หรือ Formal parameter)** คือตัวแปร (Parameter variable) ที่รับข้อมูลจากภายนอกเข้ามาใช้ภายในฟังก์ชัน.\n", "\n", "__ต่างกันตรงที่มุมมอง__ ว่ามองจากมุมไหน ถ้ามองในมุมของโปรแกรมย่อย (ฟังก์ชัน) จะเรียกว่าพารามิเตอร์ แต่ถ้ามองในมุมของโปรแกรมที่เรียกใช้จะเรียกว่าอาร์กิวเมนต์\n", "\n", "Src: [Programming FAQ: What is the difference between arguments and parameters?](https://docs.python.org/3/faq/programming.html#what-is-the-difference-between-arguments-and-parameters)\n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## ฟังก์ชันทำให้การเขียนโปรแกรมทำได้ง่ายขึ้น" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "เรามาพิจารณาบล๊อก Block 1 และ Block 2 ทั้งสองบล็อกทำงานเหมือนกัน ต่างกันเพียงชื่อตัวแปรและค่าต่างๆ\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Block 1:**" ] }, { "cell_type": "code", "execution_count": 32, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "5" ] }, "execution_count": 32, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# a and b calculation block1\n", "\n", "a1 = 4\n", "b1 = 5\n", "c1 = a1 + b1 + 2 * a1 * b1 - 1\n", "if(c1 < 0):\n", " c1 = 0 \n", "else:\n", " c1 = 5\n", "c1 " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Block 2:**" ] }, { "cell_type": "code", "execution_count": 33, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "0" ] }, "execution_count": 33, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# a and b calculation block2\n", "\n", "a2 = 0\n", "b2 = 0\n", "c2 = a2 + b2 + 2 * a2 * b2 - 1\n", "if(c2 < 0):\n", " c2 = 0 \n", "else:\n", " c2 = 5\n", "c2 " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "เนื่องจากทั้งสองบล็อกทำงานเหมือนกัน เราสามารถเขียนเป็นฟังก์ชันแทนได้ เมื่อกำหนดฟังก์ชันแล้ว จะเรียกใช้ซ้ำกี่ครั้งก็ได้ตามที่ต้องการ นอกจากนี้ ยังสามารถเซฟไฟล์เพื่อเรียกใช้ในโปรแกรมอื่นหรือในฟังก์ชันอื่นก็ได้\n", "\n", "โค้ดใน Block 1 และ code Block 2 ข้างต้น เขียนเป็นฟังก์ชันได้ดังนี้\n" ] }, { "cell_type": "code", "execution_count": 34, "metadata": {}, "outputs": [], "source": [ "# Make a Function for the calculation above\n", "\n", "def Equation(a,b):\n", " c = a + b + 2 * a * b - 1\n", " if(c < 0):\n", " c = 0 \n", " else:\n", " c = 5\n", " return(c) " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "ฟังก์ชัน Equation( ) มีอินพุตสองค่าคือ a และ b หลังประมวลผลเสร็จ จะคืนค่ากลับเป็น c หลังจากที่ประกาศฟังก์ชั้นแล้ว เราก็สามารถเขียนคำสั่งหลายบรรทัดข้างต้นให้สั้นลงได้\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "![](images/FuncsPros.gif\" width=\"700\" />\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "โค้ด Block 1 และ code Block 2 เขียนใหม่เป็น Block 3 และ code Block 4 " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Block 3:**" ] }, { "cell_type": "code", "execution_count": 35, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "5" ] }, "execution_count": 35, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a1 = 4\n", "b1 = 5\n", "c1 = Equation(a1, b1)\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": [ "
\n" ] }, { "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": [ "
\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## การกำหนดค่าเริ่มต้น (ค่าปริยาย) ให้กับอาร์กิวเมนต์ (Default argument)\n", "\n", "ในภาษา Python เราสามารถสร้างฟังก์ชันโดยการกำหนด Default Argument ให้กับพารามิเตอร์ของฟังก์ชันได้ ซึ่งเป็นการการกำหนดค่าเริ่มต้นให้กับอาร์กิวเมนต์ที่ส่งเข้ามายังฟังก์ชัน ทำให้เราสามารถเรียกใช้งานฟังก์ชันโดยส่งอาร์กิวเมนต์น้อยกว่าจำนวนที่กำหนดไว้ในฟังก์ชันได้ ซึ่งส่งผลให้การเรียกใช้ฟังก์ชันมีความยืดหยุ่นมากขึ้น\n", "\n", "รูปแบบในการกำหนดค่าปริยายให้กับอาร์กิวเมนต์ : อาร์กิวเมนต์ที่มีการกำหนดค่าเริ่มต้น (ค่าปริยาย) จะต้องอยู่ทางขวาสุดเสมอ นั่นหมายความว่า **อาร์กิวเมนต์ที่ไม่มีกำหนดค่าเริ่มต้นจะต้องอยู่ทางซ้ายสุดเสมอ**" ] }, { "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": [ "
\n", "
\n", "อาร์กิวเมนต์ที่มีการกำหนดค่าเริ่มต้น (ค่าปริยาย) จะต้องอยู่ทางขวาสุด **ส่วนอาร์กิวเมนต์ที่ไม่มีกำหนดจะต้องอยู่ทางซ้ายสุดเสมอ**\n", "
\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## การเรียกฟังก์ชันในรูปแบบระบุคีย์เวิร์ด (Keyword Arguments)\n", "\n", "ตามที่ได้อธิบายไว้ข้างต้น โดยทั่วไปแล้วอาร์กิวเมนต์ที่ส่งให้กับฟังก์ชัน (หรือที่เรียกว่า อาร์กิวเมนต์ตำแหน่ง) จะต้องเรียงตามลำดับตามที่กำหนดไว้ในฟังก์ชัน\n", "\n", "แต่ถ้าใช้อาร์กิวเมนต์แบบระบุคีย์เวิร์ด ในรูปแบบ \"keyword = value\" แล้วหละก็ ฟังก์ชันจะสามารถรับชื่อตัวแปรและค่าของตัวแปรเป็นเซ็ทๆ ได้ทำให้สามารถส่งผ่านอาร์กิวเมนต์ไปยังฟังก์ชันได้โดยที่ไม่ต้องเรียงตามลำดับตามที่กำหนดไว้ในฟังก์ชัน\n" ] }, { "cell_type": "code", "execution_count": 48, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello How do you do?, John\n" ] } ], "source": [ "# No Keyword Argument\n", "greeting(\"How do you do?\", \"John\")" ] }, { "cell_type": "code", "execution_count": 49, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello John, How do you do?\n" ] } ], "source": [ "# with Keyword Arguments\n", "greeting(msg = \"How do you do?\", name = \"John\")" ] }, { "cell_type": "code", "execution_count": 50, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello Jan, Good morning!\n" ] } ], "source": [ "greeting('Jan')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## ฟังก์ชันและตัวแปรประเภท Collections** (Arbitrary Arguments)\n", "\n", "\n", "**ตัวแปรประเภท Collections เป็นประเภทที่จัดเก็บข้อมูลรวมกันเป็นชุดเดียว และใช้ชื่อตัวแปรเดียว โดยในกลุ่ม Collections จะมีตัวแปร 4 ชนิดได้แก่ List, Tuple, Set, Dictionary\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**ในกรณีที่เราไม่ต้องการระบุจำนวนอาร์กิวเมนต์ของฟังก์ชัน** เราสามารถ\n", "ระบุอาร์กิวเมนต์แบบอ้างอิง (Reference) โดยมีรูปแบบคือ\n", "\n", "**Function syntax:**\n", "\n", "```python\n", "def ([, <*tuple_parameter>, <**dictionary_parameter>]):\n", " \n", " \n", " ...\n", " \n", "```\n", "\n", "ใช้เครื่องหมายดอกจันทร์ (asterisk) หนึ่งอัน (\\*) และสองอัน (\\*\\*) นำหน้าชื่อของพารามิเตอร์ \n", "\n", "แต่โปรเกรมเมอร์ส่วนใหญ่จะใช้ \\*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 ([, <*argsr>, <**kwargs>]):\n", " \n", " \n", " ...\n", " \n", "```\n", "\n", "(ในภาษาไพธอนไม่มีการใช้พอยน์เตอร์ [(pointer)](https://en.wikipedia.org/wiki/Pointer_(computer_programming)) เหมือนในภาษาอื่นๆ เช่น C, C++, Java)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**ตัวอย่าง ฟังก์ชันที่มีอาร์กิวเมนต์ที่เป็นทูเปิล** (อาร์กิวเมนต์ทั้งหมดถูกบรรจุลงเป็นสมาชิกในทูเพิล) ทั้งสองตัวอย่างต่อไปนี้ทำงานเหมือนกัน แต่การเรียกใช้งานต่างกัน!" ] }, { "cell_type": "code", "execution_count": 51, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Number of arguments: 3\n", "Horsefeather\n", "Adonis\n", "Bone\n", "Number of arguments: 4\n", "Sidecar\n", "Long Island\n", "Mudslide\n", "Carriage\n" ] } ], "source": [ "def printAll(*args): # All the arguments are 'packed' into args which can be treated like a tuple\n", " #print(\"Type of arguments:\", type(args)) \n", " print(\"Number of arguments:\", len(args)) \n", " for argument in args:\n", " print(argument)\n", " \n", "#printAll with 3 arguments\n", "printAll('Horsefeather','Adonis','Bone')\n", "#printAll with 4 arguments\n", "printAll('Sidecar','Long Island','Mudslide','Carriage')\n" ] }, { "cell_type": "code", "execution_count": 52, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Number of arguments: 3\n", "Horsefeather\n", "Adonis\n", "Bone\n", "Number of arguments: 4\n", "Sidecar\n", "Long Island\n", "Mudslide\n", "Carriage\n" ] } ], "source": [ "def printAll(args: tuple):\n", " print(\"Number of arguments:\", len(args)) \n", " for argument in args:\n", " print(argument)\n", " \n", "#printAll with 3 arguments\n", "printAll(('Horsefeather','Adonis','Bone')) # กรณีนี้ ตอนส่ง ต้องส่งในรูปของ Tuple!!\n", "#printAll with 4 arguments\n", "printAll(('Sidecar','Long Island','Mudslide','Carriage'))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**ตัวอย่าง ฟังก์ชันที่มีอาร์กิวเมนต์ที่เป็นดิกชันนารี** (อาร์กิวเมนต์ทั้งหมดถูกแพ็คลงในดิกชันนารี) ทั้งสองตัวอย่างต่อไปนี้ทำงานเหมือนกัน แต่การเรียกใช้งานต่างกัน!" ] }, { "cell_type": "code", "execution_count": 53, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "CountryID : CA\n", "Country : Canada\n", "City : Toronto\n", "CountryID : TH\n", "Country : Thailand\n", "City : Bangkok\n" ] } ], "source": [ "def printDictionary(**kwargs):\n", " #print(\"Type of arguments:\", type(kwargs)) \n", " for key in kwargs:\n", " print(key + \" : \" + kwargs[key])\n", "\n", "printDictionary(CountryID='CA', Country='Canada', City='Toronto')\n", "printDictionary(CountryID='TH', Country='Thailand', City='Bangkok')\n" ] }, { "cell_type": "code", "execution_count": 54, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'CountryID': 'TH', 'Country': 'Thailand', 'City': 'Bangkok'}" ] }, "execution_count": 54, "metadata": {}, "output_type": "execute_result" } ], "source": [ "dic_t = {'CountryID':'TH', 'Country':'Thailand','City':'Bangkok'}\n", "dic_t" ] }, { "cell_type": "code", "execution_count": 55, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "CountryID : TH\n", "Country : Thailand\n", "City : Bangkok\n" ] } ], "source": [ "def printDictionary(kwargs: dict):\n", " for key in kwargs:\n", " print(key + \" : \" + kwargs[key])\n", "\n", "printDictionary(dic_t)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "แต่ถ้าเรียกแบบนี้ เกิด TypeError เนื่องจากอาร์กิวเมนต์ที่ส่งไม่เป็นข้อมูลชนิด dict" ] }, { "cell_type": "code", "execution_count": 56, "metadata": {}, "outputs": [], "source": [ "#printDictionary(CountryID='TH', Country='Thailand', City='Bangkok')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "ต้องส่งอาร์กิวเมนต์ที่เป็นข้อมูลชนิด dict เท่านั้น" ] }, { "cell_type": "code", "execution_count": 57, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "CountryID : TH\n", "Country : Thailand\n", "City : Bangkok\n" ] } ], "source": [ "printDictionary(dict(CountryID='TH', Country='Thailand', City='Bangkok'))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**ข้อควรระวัง กรณีของฟังก์ชันที่มีอาร์กิวเมนต์ที่เป็นลิสต์**" ] }, { "cell_type": "code", "execution_count": 58, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['One', 'Two', 'Three', 'Four']" ] }, "execution_count": 58, "metadata": {}, "output_type": "execute_result" } ], "source": [ "def addItems(list):\n", " list.append(\"Three\")\n", " list.append(\"Four\")\n", "\n", "myList = [\"One\",\"Two\"]\n", "\n", "addItems(myList)\n", "\n", "myList\n", " " ] }, { "cell_type": "code", "execution_count": 59, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['One', 'Two', 'Three', 'Four', 'Three', 'Four']" ] }, "execution_count": 59, "metadata": {}, "output_type": "execute_result" } ], "source": [ "addItems(myList)\n", "myList" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**ข้อสังเกต** จะเห็นว่าการเปลี่ยนแปลงที่เกิดขึ้นกับลิสต์ myList ไม่ได้จำกัดอยู่เฉพาะในฟังก์ชันเท่านั้น\n", "\n", "เนื่องจากลิสส่งค่าโดยใช้การอ้างอิง (Pass by Reference) ซึ่งการส่งแบบนี้จะไม่มีการสร้างสำเนาเก็บค่าของตัวแปร แต่จะเป็นการอ้างอิงตำแหน่งในหน่วยความจำของตัวแปร ทำให้ตัวแปรที่ส่งไปยังฟังก์ชันและตัวแปรในฟังก์ชันใช้หน่วยความจำร่วมกัน ดังนั้นเมื่อตัวแปรในฟังก์ชันมีการเปลี่ยนค่า ตัวแปรที่ส่งค่าไปก็จะเปลี่ยนค่าด้วย **ดังนั้น ควรระมัดระวังกรณีที่ส่งผ่านอ็อบเจกต์ชนิด mutable ไปยังฟังก์ชัน**\n", "\n", "
\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "\n", " ตัวอย่างข้างต้นเป็นฟังก์ชันที่มีอาร์กิวเมนต์ *args หรือ **kwargs อย่างใดอย่างหนึ่งเท่านั้น แต่เรายังสามารถสร้างฟังก์ชันที่มีอาร์กิวเมนต์ทั้ง *args และ **kwargs รวมกันได้ เพรียงแต่ *args จะต้องอยู่ก่อน (อยู่ทางซ้าย) **kwargs เสมอ\n", "\n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## ขอบเขตของตัวแปร (Scope of a Variable)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "“ขอบเขตของตัวแปร” คือสิ่งที่ใช้กำหนดว่า ตัวแปรที่ประกาศขึ้นมา จะสามารถเรียกใช้งานจากที่ไหนได้บ้าง. \n", "\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": [ "
\n", "\n", "* ตัวแปรที่ประกาศภายในฟังก์ชันหรือใน Local scope จะเรียกว่า **ตัวแปรโลคอล (Local Variable)** มีขอบเขตการใช้งาน (ทั้งการเรียกใช้และการแก้ไข) เฉพาะภายในฟังก์ชันเท่านั้น ดังนั้น **ตัวแปรที่ประกาศภายในฟังก์ชันรวมถึงพารามิเตอร์ของฟังก์ชันซึ่งถือเป็นส่วนหนึ่งของฟังก์ชั้น จะมีขอบเขตการใช้งานเฉพาะภายในฟังก์ชันเท่านั้น!** หากทำการเรียกจากภายนอกฟังก์ชัน จะเกิดข้อผิดพลาดเนื่องจากไม่มีข้อมูลของตัวแปร (เว้นแต่จะถูกกำหนดให้เป็นตัวแปรร่วมโดยใช้คีย์เวิร์ด global เท่านั้น) \n", " \n", "\n", "* ตัวแปรที่ประกาศภายนอกฟังก์ชันหรือใน Global scope จะเรียกว่า **ตัวแปรโกลบอล (Global Variable)** สามารถเรียกใช้งานได้ทั้งโปรแกรม ไม่ว่าจะภายในหรือภายนอกฟังก์ชัน **แต่การแก้ไขจะทำได้เฉพาะใน Global scope เท่านั้นไม่สามารถแก้ไขภายในฟังก์ชันได้**\n", "\n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### ตัวแปรโกลบอล (Global Variable)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "ตัวแปรที่ประกาศภายนอกฟังก์ชันเป็น **ตัวแปรโกลบอล (Global Variable)** สามารถที่จะถูกเรียกดูข้อมูลหรือเรียกใช้งานได้ทั้งภายในและภายนอกฟังก์ชันได้ ในขณะที่ตัวแปรที่ประกาศภายในฟังก์ชันเป็น **ตัวแปรโลคอล (Local Variable)** สามารถที่จะถูกเรียกหรือแก้ไขได้เฉพาะภายในฟังก์ชันเท่านั้น\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": [ "
\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "2 จากฟังก์ชัน 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 }