{ "cells": [ { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "# Introduction to Python\n", "\n", "ภาษาไพธอน (Python) เป็นภาษาระดับสูงที่สามารถใช้ในการคำนวณทางคณิตศาสตร์ สถิติ รวมถึงการใช้สร้างโมเดลปัญญาประดิษฐ์ และใช้สำหรับวิทยาศาสตร์ข้อมูลได้อีกด้วย\n", "\n", "ดังนั้นการเรียนรู้ไวยากรณ์ (syntax) ของการเขียนภาษาไพธอนจึงเป็นพื้นฐานสำคัญในการต่อยอดการสร้างโมเดลทางประสาทวิทยาที่อาจใช้ทักษะในสาขาต่างๆนั่นเอง\n", "\n", "เราจะใช้ Jupyter notebook ในการเขียนโค้ดเป็นหลัก โดย Jupyter notebook จะเป็นหน้าเว็บไซต์ที่ทำให้ เราสามารถเขียนโค้ดใน cell (กล่อง) ด้วยโปรแกรมภาษาไพธอนได้ โดยการรันโค้ดในแต่ละ cell จะสามารถกด shift + enter เพื่อรันแต่ละ cell ได้\n", "\n", "Jupyter notebook มีข้อดีคือเราสามารถรันใน local computer หรือว่ารันบนเว็บไซต์ผ่าน Google Colaboratory (Google Colab), Kaggle, หรือ Amazon Sagemaker Studio ก็ได้" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "## Integer และ Float\n", "\n", "เราสามารถสร้างตัวแปร (variable) ที่เป็นชนิด\n", "- integer หรือตัวแปรที่เป็นจำนวนเต็มที่อาจจะมีค่าเป็นบวก ลบ หรือศูนย์ก็ได้\n", "- หรือ float ที่เป็นตัวแปรที่เป็นเลขทศนิยมได้\n", "\n", "และใช้การคำนวณง่ายๆกับตัวแปรของเราได้ เช่น บวก (+), ลบ (-), คูณ (*), ยกกำลัง (**)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "x = 5.\n", "print(type(x)) # float\n", "\n", "x = 10\n", "print(type(x)) # int\n", "\n", "print(x + 1) # 11\n", "print(x - 3) # 7\n", "print(x * 2) # 20\n", "print(x ** 2) # 100\n", "print(x / 2) # 5.0" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "สำหรับตัวแปรชนิด boolean มีค่าเป็น จริง (`True`) หรือ ไม่จริง (`False`)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "is_available = True # boolean\n", "\n", "print(type(is_available))\n", "print(not is_available)\n", "\n", "print(5 != 3)\n", "print(5 == 5)\n", "print(5 == 10)" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "ตัวแปรชนิด string ใช้ในการเก็บตัวอักษรหรือลำดับของตัวอักษร และต่อ string กันได้ด้วยการใช้ \"+\" เช่น" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "s = \"Hello world!\"\n", "print(s)\n", "print(s[0: 2]) # print จาก index 0 ถึง 1\n", "print(s[1:5]) # print จาก index 0 ถึง 4\n", "\n", "name = \"John\"\n", "message = \"Hello! \" + \"My name is \" + name\n", "print(message)\n", "\n", "school = \"Suankularb Wittayalai\"\n", "text = \"I went to {} school\".format(school)\n", "print(text)" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "นอกเหนือจากนั้นยังมีชนิดของ Containers ที่สามารถใส่ข้อมูลต่างๆของ Python ได้เช่น Lists, Dictionaries, Sets และ Tuples ใน cell ถัดๆไปเราจะมาลองสร้างข้อมูลประเภทเหล่านี้กัน\n", "\n", "## Lists\n", "\n", "ลิสต์ (Lists) เป็นการเก็บค่าต่างๆเข้ามาด้วยกัน โดยจะเป็นชนิดอะไรก็ได้ เช่น string, integer, float หรือแม้แต่ dictionary (section ถัดไป)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "numbers = [1, 2, 3, 4, 5]\n", "first_number = numbers[0]\n", "last_number = numbers[-1]\n", "print(first_number)\n", "print(last_number)\n", "\n", "numbers.append(6) # เพิ่มลิสต์ด้วยเลข 6\n", "print(numbers)\n", "\n", "numbers.extend([7, 8, 9]) # เพิ่มลิสต์ด้วย ลิสต์ [7, 8, 9] \n", "print(numbers)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "numbers = list(range(5)) # สร้างลิสต์ของตัวเลขที่มีค่า 0 to 4\n", "print(numbers)\n", "\n", "print(numbers[2:]) # เลือกตำแหน่ง 2 เป็นต้นไป\n", "print(numbers[:2]) # เลือกตำแหน่ง 0 ถึง 1\n", "print(numbers[:-1]) # เลือกตำแหน่ง 0 ถึงก่อนตัวสุดท้าย (-1)" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "ในตัวอย่างถัดไป เราจะสร้างลิสต์ (list) ของผลไม้และพิมพ์ลิสต์ของผลไม้ออกมา และทำการใช้ for loop ร่วมกับการแจกแจง (enumerate) ในการพิมพ์ของจากลิสต์ออกมาพร้อมกับเลขกำกับ " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# create a list of strings\n", "fruits = [\"apple\", \"banana\", \"orange\", \"mango\"]\n", "\n", "print(\"Regular for loop\\n\")\n", "for fruit in fruits:\n", " print(fruit)\n", "print(\"----\")\n", "\n", "# iterate over the list using a for loop and enumerate\n", "print(\"For loop with enumerate\\n\")\n", "for i, fruit in enumerate(fruits):\n", " print(i, fruit)\n", "print(\"----\")" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "บางครั้งเราสามารถใช้ in-line for loop เพื่อเขียน for loop ใน 1 บรรทัดได้ เช่น การนำ build-in function `sum` มาใช้ร่วมกับ `range(10)` เพื่อหาค่าผลบวกจาก 0 ถึง 9" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "s_r = sum([i for i in range(10)])" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "## Dictionaries\n", "\n", "นอกจากนั้น Python ยังสามารถเก็บข้อมูลในรูปแบบของ dictionary ซึ่งเป็นการเก็บข้อมูลแบบที่มีคู่ของ key และ value อยู่ด้วยกัน dictionary เหมาะกับการเก็บข้อมูลและดึงข้อมูลออกมาจาก key บางอย่างที่เราสนใจ โดยถัดไปเราจะลองสร้าง dictionary ที่มี key เป็น id และ value เป็นประเภทของสิ่งของ\n", "\n", "โดยหลังจากที่เราสร้าง dictionary ก็จะอัพเดทด้วย key, value ใหม่โดยการใช้ `id2label[key] = value` เช่น `id2label[4] = \"mango\"` และทำการสลับ key และ value โดยการใช้ for loop ร่วมกับ `.items()`" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "person = {\n", " \"name\": \"John Wick\",\n", " \"age\": 60,\n", " \"city\": \"New York\",\n", " \"status\": \"excommunicado\",\n", "}\n", "person[\"occupation\"] = \"Hitman\"\n", "for key, value in person.items():\n", " print(\"{}: {}\".format(key, value))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "id2label = {0: \"background\", 1: \"apple\", 2: \"orange\", 3: \"banana\"}\n", "print(\"Keys: \", id2label.keys())\n", "print(\"Values: \", id2label.values())\n", "\n", "# อัพเดท dictionary ที่มี key เท่ากับ 4 และ value เท่ากับ \"mango\"\n", "id2label[4] = \"mango\"\n", "print(\"Updated keys: \", id2label.keys())\n", "print(\"Updated values: \", id2label.values())" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "label2id = {v: k for k, v in id2label.items()}" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "## If-else statements\n", "\n", "ถัดมา `if`, `else`, `elif` ใช้ในการเขียนเงื่อนไข (conditions) ที่ใช้ในการแบ่งประเภท เช่น การตัดเกรด (A >= 80, B < 80 หรือ >= 70, ...) หรือการคัดเลือกที่มีเงื่อนไขที่สร้างไว้แล้ว" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "b = 2\n", "if b > 5:\n", " print(\"b is greater than 5\")\n", "else:\n", " print(\"b is less than or equal to 5\") " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "score = 55 # ลองเปล่ี่ยนบรรทัดนี้ และรันเพื่อทดลองใช้เงื่อนไข (condition) if, elif, else \n", "if score >= 80:\n", " print(\"Grade A\")\n", "elif score < 80 and score >= 70:\n", " print(\"Grade B\")\n", "elif score < 70 and score >= 60:\n", " print(\"Grade C\")\n", "elif score < 60 and score >= 50:\n", " print(\"Grade C\")\n", "else:\n", " print(\"Grade D\")" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "## Functions\n", "\n", "Python มี built-in functions ต่างๆมากมาย เช่น `sum`, `pow`, `max`, `abs`\n", "นอกจากนั้นเราสามารถเขียน function ใน Python ขึ้นมาเองได้อีกด้วย ฟังก์ชั่นเปรียบเสทอนการสร้างชุดโค้ด (blocks of code) ที่สามารถนำมาใช้งานใหม่ได้ โดยการเขียนฟังก์ชันใน Python จะรับ input parameters และให้ output โดยการเขียน return\n", "\n", "เราสามารถเขียนฟังก์ชั่นได้ดังนี้:\n", "\n", "```py\n", "def do_something(input1, input2, ...):\n", " # เขียน ฟังก์ชั่นในนี้\n", " ...\n", " return output1, output2\n", "```" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# เขียนฟังก์ชันชื่อ exponential ที่รับ x และ y จากนั้นคำนวณค่า x ** y\n", "def exponential(x, y):\n", " \"\"\"Calculate x ** y\"\"\"\n", " return x ** y\n", "\n", "result = exponential(3, 4) # 81\n", "print(result)\n", "\n", "# เขียนฟังก์ชันที่ใช้ในการต้อนรับ โดยให้ input เป็น name (default เป็น Alice)\n", "def greet(name=\"Alice\"):\n", " print(\"Greeting {}!\".format(name))\n", " \n", "greet()\n", "greet(\"John Wick\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# (optional) บางครั้งเราอาจจะพบการเขียนแบบใช้ keyword arguments\n", "# คือรับ input ที่เป็น key, value เข้ามา\n", "# กรณีนี้เราจะบังคับใส่ name (string), age (integer), และ keyword arguments\n", "def describe_person(name: str, age: int, **kwargs):\n", " print(\"Name: \" + name)\n", " print(\"Age: \" + str(age))\n", " for key, value in kwargs.items():\n", " print(key.capitalize() + \": \" + value)\n", "\n", "describe_person(\"John Wick\", 60, occupation=\"Hitman\", city=\"New York\")" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "## More to come\n", "\n", "นอกเหนือจากฟังก์ชั่นหลักของ Python แล้ว Python ยังสามารถนำไปใช้ในงานประเภทต่างๆได้อีกมากมาย หนึ่งในนั้นคือการนำมาช่วยในการสร้างโมเดลทางคณิตศาสตร์และการคำนวณทางสถิติที่เราจะได้เรียนกันนั่นเอง Python มีไลบรารี่ต่างๆที่ทำให้การคำนวณทำได้ง่าย และสามารถนำมาแก้ปัญหาทางการวิจัยได้ในอนาคต" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**ผู้จัดเตรียม code ใน tutorial**: ดร. ฐิติพัทธ อัชชะกุลวิสุทธิ์" ] } ], "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.7.13" } }, "nbformat": 4, "nbformat_minor": 2 }