{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "![](images/python_with_Birds.gif)\n" ] }, { "cell_type": "markdown", "metadata": { "cell_style": "center", "id": "waZDna5nPCfT" }, "source": [ "# ใช้งานไพธอนเป็นเครื่องคิดเลข (Python as a Calculator)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**10** minutes\n", "\n", "\n", "## วัตถุประสงค์\n", "\n", "**หลังจากทำทำแล็บ นศ.จะสามารถ**\n", "\n", "* ใช้ [Jupyter Notebook](https://jupyter.org) ขั้นพื้นฐานได้\n", "\n", "* ใช้ Python เป็นเครื่องคิดเลข (ตัวดำเนินการทางคณิตศาสตร์) ได้\n", "\n", "* เข้าใจลำดับการรทำงานของตัวดำเนินการทางคณิตศาสตร์\n", "\n", "* ใช้ฟังก์ชันทางคณิตศาสตร์ (Import math) อย่างง่ายได้\n", "\n", "* ใช้ Python จัดดการสตริง/แสดงสตริงขั้นพื้นฐานได้\n", "\n", "* เชื่อมและก็อปปี้สตริงด้วยเครื่องหมาย `+` และ `*` ได้" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "ไพธอน (Python) เป็นภาษาอินเตอร์พรีเตอร์ (Interpreted Programming Languages) ทำงานโดยการแปลคำสั่งทีละคำสั่งด้วยตัวแปลภาษาไพธอน (Python Interpreter) ซึ่งแตกต่างจากภาษาอื่นเช่น C C++ หรือ Java (Compiled Programming Languages) ที่ต้องผ่านกระบวนแปลคำสั่งทั้งหมดในคราวเดียวก่อน (โดยคอมไพเลอร์ของภาษานั้นๆ) จึงจะเรียกใช้งานโปรแกรมได้ การสั่งงานคอมพิวเตอร์ด้วยภาษาไพธอนจึงสามารถทำได้ทั้งในโหมดโต้ตอบ (Interactive mode) และโหมดสคริปต์ (Script mode) ในปัจจุบัน มีเครื่องมือบางอย่างเช่น Jupyter Notebook (Ipython Notebook) ทำให้เราสามารถใช้งานทั้งสองโหมดผสมผสานกันได้\n", "\n", "* โหมดโต้ตอบ (Interactive mode) เหมาะกับการเขียนคำสั่งไพธอนที่มีความยาวบรรทัดเดียวหรือบล็อกเดียว ตัวแปลภาษาจะแปลคำสั่งทันที ทำให้เราสามารถเห็นผลลัพธ์ของแต่ละคำสั่งได้โดยไม่ต้องเสียเวลาสร้างไฟล์และคอมไพล์โปรแกรม\n", "* โหมดสคริปต์ (Script mode) เหมาะกับการเขียนคำสั่งที่มีความยาวหลายบรรทัดหรือหลายบล็อก โดยคำสั่งทั้งหมดต้องบันทึกเป็นไฟล์ไว้ก่อน เพื่อจะสั่งให้ตัวแปลภาษาทำงานตามคำสั่งตั้งแต่คำสั่งแรก จนถึงคำสั่งสุดท้าย\n", "\n", "\n", "ในบทนี้ เราจะใช้ไพธอนเป็นเครื่องคิดเลขอย่างง่าย โดยเขียนนิพจน์ (Expression) ซึ่งประกอบไปด้วย ตัวดำเนินการ (Operators) เช่น ```+, -, *, /``` และตัวถูกดำเนินการ (Operands) ลงไปในเซลล์ แล้วรันโดยกดคีย์ Shift + Enter ไพธอนจะทำการประมวลผลและแสดงผลลัพธ์ให้เราดูทันที\n" ] }, { "cell_type": "markdown", "metadata": { "cell_style": "center", "id": "waZDna5nPCfT", "jp-MarkdownHeadingCollapsed": true, "tags": [] }, "source": [ "**Ref:** \n", "* https://docs.python.org/3/tutorial/introduction.html#using-python-as-a-calculator\n", "* https://docs.python.org/3/tutorial/modules.html\n", "* https://docs.python.org/3/library/numeric.html\n", "* https://docs.python.org/3/library/math.html\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n" ] }, { "cell_type": "markdown", "metadata": { "id": "53d6jDxhPCfX" }, "source": [ "## ตัวเลข - การคำนวณทางคณิตศาสตร์อย่างง่าย" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "เนื่องจากไพธอนเป็นอินเตอร์พรีเตอร์ ทำงานโดยการแปลคำสั่งทีละคำสั่งด้วยตัวแปลภาษาไพธอน จึงทำงานเหมือนกับเครื่องคิดเลข กล่าวคือ คีย์ตัวเลข/สูตรเข้าไป ก็จะได้ผลลัพธ์ทันที\n", "\n", "เราจะลองเขียนคำสั่งไพธอนแบบง่ายๆ โดยคำนวณ 20 + 50 \n", "\n", "ลองพิมพ์ 20 + 50 ลงในเซลล์ถัดไป จากนั้นทำการรันโดยกดคีย์ Shift ค้างไว้ แล้วกด Enter ผลลัพธ์ของการประมวลผลจะแสดงอยู่ใต้เซลล์\n", "\n", "```{note}\n", "รัน Code cell โดยการกดคีย์ Shift + Enter (กดพร้อมกัน) หรือกดที่ไอคอน \"Play (Run)\" ใต้แถบเมนู\n", "```" ] }, { "cell_type": "code", "execution_count": 84, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "70" ] }, "execution_count": 84, "metadata": {}, "output_type": "execute_result" } ], "source": [ "20 + 50" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "แค่นี้ เราก็สามารถใช้ Python แทนเครื่องคิดเลขได้แล้ว \n", "\n", "เราเรียกสิ่งที่อยู่ในเซลล์ว่า ```นิพจน์ (Expression)```\n", "\n", "นิพจน์ (Expression) จะประกอบด้วยส่วนประกอบ 2 ส่วน 1. ตัวดำเนินการ (Operators) และ 2. ตัวถูกดำเนินการ (Operands) โดย**นิพจน์จะให้ผลลัพธ์เสมอ**" ] }, { "cell_type": "markdown", "metadata": { "id": "D0MHckbYPCfY" }, "source": [ "นิพจน์ข้างต้นมี ``` + ``` (การบวก) เป็นตัวดำเนินการ และมีตัวเลขซ้ายและขวา (20, 50) เป็นตัวถูกดำเนินการ โดยให้ผลลลัพธ์เป็น 70" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "วิธีการเขียนนิพจน์ในภาษาไพธอนก็เหมือนภาษาอื่นๆ (เช่น C, C++ และ Java) ใช้ตัวดำเนินการ ```+,-, *, /``` สำหรับการบวก การลบ การคูณ การหารใช้วงเล็บ ```( )``` สำหรับการจัดกลุ่ม" ] }, { "cell_type": "markdown", "metadata": { "tags": [] }, "source": [ "ตัวถูกดำเนินการอาจจะเป็นค่าคงที่ (```*``` การคูณ)" ] }, { "cell_type": "code", "execution_count": 85, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "1000" ] }, "execution_count": 85, "metadata": {}, "output_type": "execute_result" } ], "source": [ "20 * 50" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "หรืออาจจะเป็นตัวแปรก็ได้" ] }, { "cell_type": "code", "execution_count": 86, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "executionInfo": { "elapsed": 5, "status": "ok", "timestamp": 1628484559273, "user": { "displayName": "Suti Chai", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GgarRF-CZdRj7Ua_bTKi26VaUhYO8IIsLS2x2oP=s64", "userId": "07754154546807752175" }, "user_tz": -420 }, "id": "5Rto0uS8PCfY", "outputId": "3164ec11-84ba-4140-ca43-40037cc1e38b", "scrolled": true }, "outputs": [ { "data": { "text/plain": [ "1000" ] }, "execution_count": 86, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a = 20\n", "b = 50\n", "a * b" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "```{attention}\n", "ในกรณีของสูตรในคณิตศาสตร์เราจะเขียน $a \\cdot b$ หรือ $ab$ แสดงถึงการคูณระหว่าง a และ b แต่ในการเขียนโค้ดต้องเขียนตัวดำเนินการคูณ ```*``` ให้ชัดเจน\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "ตัวถูกดำเนินการอาจอยู่ในรูปนิพจน์ที่มีความซับซ้อน เช่น\n", "$7 \\left( {\\frac{a\\cdot{b}}{a+b}} \\right)$ (การหารใช้เครื่องหมาย $/$ )" ] }, { "cell_type": "code", "execution_count": 87, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "100.0" ] }, "execution_count": 87, "metadata": {}, "output_type": "execute_result" } ], "source": [ "7*((a * b) / (a + b))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "หรือเป็นรูปนิพจน์แบบยาวๆ เช่นการบวกเลขอนุกรม 1, 2, 3, ...., 50 แบบนี้ก็ได้" ] }, { "cell_type": "code", "execution_count": 88, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "1275" ] }, "execution_count": 88, "metadata": {}, "output_type": "execute_result" } ], "source": [ "1+2+3+4+5+6+7+8+9+10+11+12+13+14+15+16+17+18+19+20+21+22+23+24+25+26+27+28+29+30+31+32+33+34+35+36+37+38+39+40+41+42+43+44+45+46+47+48+49+50\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "```{tip}\n", "ในกรณีของไพธอน เราสามารถเขียนคำสั่งแบบหลายบรรทัดได้ โดยใช้อักขระ ```\"\\\"``` (Backslash) แยกบรรทัด (ไพธอนไม่สนเครื่องหมาย ```\"\\\"``` จะตีความว่า มีต่อในบรรทัดถัดไป (Ignored (a continuation) ```“\\“```))\n", "```" ] }, { "cell_type": "code", "execution_count": 89, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "1275" ] }, "execution_count": 89, "metadata": {}, "output_type": "execute_result" } ], "source": [ "1+2+3+4+5+6+7+8+9+10+11+12+13+14+15+16+17+18+19+20+21+22+23+24+25+26+ \\\n", "27+28+29+30+31+32+33+34+35+36+37+38+39+40+41+42+43+44+45+46+47+48+49+50\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "```{note}\n", "ระหว่างตัวดำเนินการและตัวถูกดำเนินการ จะเขียนติดๆ กันโดยไม่เว้นระยะห่างเลย หรือจะเว้นระยะห่างกี่ช่องก็ได้ แต่ต้องอยู่ในบรรทัดเดียวกัน (เพราะในบางกรณี การเขียนหลายบรรทัด อาจทำให้การประมวลผลผิดพลาด) ในกรณีที่จำเป็นต้องแยกบรรทัด ให้ใช้ เครื่องหมาย ```\"\\\"```\n", "\n", "อย่างไรก็ตาม เราความปรับระยะห่างระหว่างตัวดำเนินการและตัวถูกดำเนินการให้เหมาะสม ให้สามารถอ่านโค้ดได้ง่าย\n", "```" ] }, { "cell_type": "code", "execution_count": 90, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "362880" ] }, "execution_count": 90, "metadata": {}, "output_type": "execute_result" } ], "source": [ "1*2*3*4*5*6*7*8*9" ] }, { "cell_type": "code", "execution_count": 91, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "362880" ] }, "execution_count": 91, "metadata": {}, "output_type": "execute_result" } ], "source": [ "1*2*3*4* \\\n", "5*6*7*8*9" ] }, { "cell_type": "code", "execution_count": 92, "metadata": {}, "outputs": [ { "ename": "SyntaxError", "evalue": "invalid syntax (2229763452.py, line 1)", "output_type": "error", "traceback": [ "\u001b[0;36m Cell \u001b[0;32mIn [92], line 1\u001b[0;36m\u001b[0m\n\u001b[0;31m 1*2*3*4*\u001b[0m\n\u001b[0m ^\u001b[0m\n\u001b[0;31mSyntaxError\u001b[0m\u001b[0;31m:\u001b[0m invalid syntax\n" ] } ], "source": [ "1*2*3*4* \n", "5*6*7*8*9" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "```{note} **[PEP8]**\n", "\n", "ผู้สร้าง (Guido van Rossum) และนักพัฒนาหลักภาษาไพธอนได้เขียน \"หลักเกณฑ์หรือสไตล์การเขียนโปรแกรมของภาษา Python\" หรือที่รู้จักกันในชื่อ Python PEP8 ได้แนะนำจำนวนอักษรต่อบรรทัดให้ไม่เกิน 79 ตัวอักษร (รวมช่องว่าง (Space)) \n", "\n", "\n", "รายละเอียดของ PEP8 ดูได้ใน [Python.org: PEP 8 – Style Guide for Python Code](https://www.python.org/dev/peps/pep-0008/) เนื่องจากสไตล์การเขียนที่กำหนดใน PEP8 มีหลักการมากมาย ทำให้การเขียนโค้ดที่ถูกต้องตาม PEP8 แบบครบถ้วนเป็นไปได้ยาก ในปัจจุบัน มีเครื่องมือที่ใช้ในการตรวจเช็คโค้ดว่าถูกต้องตาม PEP8 หรือไม่ เช่น [pycodestyle](https://pypi.org/project/pycodestyle/), เครื่องมือสำหรับปรับโค้ดให้ถูกต้องตาม PEP8 อัตโนมัติ เช่น [autopep8](https://pypi.org/project/autopep8/) ที่ต้องติดตั้งเอง หรือ [PEP8 online](http://pep8online.com/) ที่เป็นบริการออนไลน์ก็มี\n", "\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "(ch0-ArithmeticOperators)=\n", "## ตัวดำเนินการทางคณิตศาสตร์ (Arithmetic Operators)\n", "\n", "\n", "ตัวดำเนินการทางคณิตศาสตร์ (Arithmetic operators) คือตัวดำเนินการที่ใช้สำหรับการคำนวณทางคณิตศาสตร์ขั้นพื้นฐาน เช่น การบวก การลบ การคูณ และการหาร นอกจากนี้ ภาษา Python ยังมีตัวดำเนินการทางคณิตศาสตร์เพิ่มเติม เช่น การหารเอาเศษ (Modulo (mod)) การหารแบบปัดเศษทิ้ง และการยกกำลัง เป็นต้น" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "ตัวดำเนินการทางคณิตศาสตร์ในภาษาไพธอน\n", " \n", "* โอเปอร์เรเตอร์ยูนารี (Unary Operators) เป็นโอเปอร์เรเตอร์ที่กระทํากับข้อมูลหรือนิพจน์เดียว : -, +\n", " \n", "* โอเปอร์เรเตอร์ไบนาร (Binary Operators) เป็นโอเปอร์เรเตอร์ที่กระทํากับข้อมูลหรือนิพจน์สองตัว : -, +, *, / ...\n", " " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**ตารางสรุปตัวดำเนินการทางคณิตศาสตร์ในภาษา Python**\n", "\n", "| ตัวดำเนินการ | ตัวอย่าง | ความหมาย | ผลลัพธ์ |\n", "| ----------- | -------| ------------------------- | ----------------------------- |\n", "| + (unary) | +a | **เครื่องหมายแสดงจำนวนลบ** | a
มีไว้สำหรับแสดงความเป็นจำนวนบวก แต่ไม่มีผลใดๆ (เนื่องจาก แม้ไม่ใส่ก็ถือว่าเป็นจำนวนบวก)|\n", "| + (binary) | a + b | **การบวก** | ผลรวมระหว่าง a และ b |\n", "| - (unary) | -a | **เครื่องหมายแสดงจำนวนลบ** | มีไว้สำหรับแสดงความเป็นจำนวนลบ |\n", "| - (binary) | a - b | **การลบ** | ผลต่างระหว่าง a และ b (a ลบออกด้วย b) |\n", "| * | a * b | **การคูณ** | ผลคูณระหว่าง a และ b |\n", "| / | a / b | **การหาร** | ผลหารของการหาร a ด้วย b
โดยผลลัพธ์เป็นเลขทศนิยมเสมอ |\n", "| % | a % b | **การหารเอาเศษ (Modulus)** | เศษที่ได้จากการหาร a ด้วย b |\n", "| // | a // b | **การหารปัดเศษทิ้ง (Floor Division)** (หรือ **หารปัดเศษ**) | ผลหารของการหาร a ด้วย b โดยปัดเศษทิ้ง ได้ผลลัพธ์เป็นเลขจำนวนเต็ม **(หารแบบไม่เอาเศษ (ปัดเศษทิ้ง))** |\n", "| ** | a ** b | **การคูณยกกำลัง** | a ยกกำลัง b |\n", "\n", "src: https://realpython.com/python-operators-expressions/" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "```{attention}\n", "\n", "ภาษาไพธอนไม่มีตัวดำเนินการ ```++``` (Increment operator), และ ```--``` (Decrement operator) เหมือนในภาษา C/C++, Java\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "```+, -``` ยังสามารถใช้เป็นโอเปอร์เรเตอร์ยูนารี (Unary Operators) ได้อีกด้วย" ] }, { "cell_type": "code", "execution_count": 93, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "-3" ] }, "execution_count": 93, "metadata": {}, "output_type": "execute_result" } ], "source": [ "-3" ] }, { "cell_type": "code", "execution_count": 94, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "3" ] }, "execution_count": 94, "metadata": {}, "output_type": "execute_result" } ], "source": [ "+3" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "การหารในภาษาไพธอน จะใช้ ```/``` เป็นการหารทศนิยม โดยผลหารจะเป็นเลขทศนิยมเสมอ" ] }, { "cell_type": "code", "execution_count": 95, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "5.666666666666667" ] }, "execution_count": 95, "metadata": {}, "output_type": "execute_result" } ], "source": [ "17 / 3" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "ใช้ ```//``` (เขียนติดกัน ห้ามเว้นเช่องว่าง) เป็นการหารแบบไม่เอาเศษ (ปัดเศษทศนิยมทิ้ง))\n", "\n", "ถ้าเป็นจำนวนเต็ม ```//```กัน ผลหารจะเป็นจำนวนเต็ม " ] }, { "cell_type": "code", "execution_count": 96, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "5" ] }, "execution_count": 96, "metadata": {}, "output_type": "execute_result" } ], "source": [ "17 // 3" ] }, { "cell_type": "code", "execution_count": 97, "metadata": {}, "outputs": [ { "ename": "SyntaxError", "evalue": "invalid syntax (2165325252.py, line 1)", "output_type": "error", "traceback": [ "\u001b[0;36m Cell \u001b[0;32mIn [97], line 1\u001b[0;36m\u001b[0m\n\u001b[0;31m 17 / / 3\u001b[0m\n\u001b[0m ^\u001b[0m\n\u001b[0;31mSyntaxError\u001b[0m\u001b[0;31m:\u001b[0m invalid syntax\n" ] } ], "source": [ "17 / / 3" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "หากต้องการหา **เศษ** ของการหารเลขจำนวนเต็ม ให้ใช้ตัวดำเนินการ **`%`**\n", "จำนวนเต็ม ```%```กัน ได้เศษของการหาร (แน่นอนเป็นจำนวนเต็ม) " ] }, { "cell_type": "code", "execution_count": 98, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "2" ] }, "execution_count": 98, "metadata": {}, "output_type": "execute_result" } ], "source": [ "17 % 3" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "ผลหารปัดเศษ * ตัวหาร + เศษ" ] }, { "cell_type": "code", "execution_count": 99, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "17" ] }, "execution_count": 99, "metadata": {}, "output_type": "execute_result" } ], "source": [ "5 * 3 + 2" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "การยกกำลังในภาษาไพธอน จะใช้ตัวดำเนินการ ```**``` (เขียนติดกัน ห้ามเว้นเช่องว่าง)\n", "\n", "ตัวอย่าง $2^7$" ] }, { "cell_type": "code", "execution_count": 100, "metadata": { "scrolled": true }, "outputs": [ { "data": { "text/plain": [ "128" ] }, "execution_count": 100, "metadata": {}, "output_type": "execute_result" } ], "source": [ "2 ** 7" ] }, { "cell_type": "code", "execution_count": 101, "metadata": {}, "outputs": [ { "ename": "SyntaxError", "evalue": "invalid syntax (3091056297.py, line 1)", "output_type": "error", "traceback": [ "\u001b[0;36m Cell \u001b[0;32mIn [101], line 1\u001b[0;36m\u001b[0m\n\u001b[0;31m 2 * * 7\u001b[0m\n\u001b[0m ^\u001b[0m\n\u001b[0;31mSyntaxError\u001b[0m\u001b[0;31m:\u001b[0m invalid syntax\n" ] } ], "source": [ "2 * * 7" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "การยกกำลังในบางภาษาจะใช้ตัวดำเนินการ ```^``` (เช่น MATLAB, Latex) \n", "\n", "แต่ในภาษาไพธอน ```^``` เป็นโอเปอเรเตอร์ระดับบิต (Bitwise Operator) เป็น **Exclusive OR (XOR)**\n", "\n", "ถ้าไม่คุ้นเคยกับตัวดำเนินการ **XOR** ให้ดูรายละเอียดใน [BitwiseOperators](https://wiki.python.org/moin/BitwiseOperators)\n", "\n", "(โอเปอเรเตอร์ระดับบิต (Bitwise Operator) ในภาษาไพธอน \"Bitwise AND\": ```&```, \"Bitwise OR\": ```|```, \"Bitwise NOT\": ```~```, \"Bitwise XOR\": ```^``` )" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "ถ้าเขียน ```2 ^ 7``` จะได้ผลลัพธ์เป็น 5 เนื่องจาก\n", "\n", "2 (Decimal) => 0010 (Binary)\n", "7 (Decimal) => 0111 (Binary)\n", "\n", "0010 XOR 0111 = 0101 (Binary) => 5 (Decimal)\n" ] }, { "cell_type": "code", "execution_count": 102, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "5" ] }, "execution_count": 102, "metadata": {}, "output_type": "execute_result" } ], "source": [ "2 ^ 7 " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "```{tip}\n", "พิเศษเฉพาะในโหมด Interactive Mode\n", "\n", "ค่าที่ถูกพิมพ์ออกมาเป็นครั้งสุดท้าย จะถูกเก็บไว้ในตัวแปรพิเศษคือ ```\"_\"``` เราอาจนำตัวแปรนี้ไปใช้ในการคำนวนค่าต่อๆ ไปได้\n", "```\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "หากต้องการเปรียบเทียบผลการรันล่าสุดว่ามีค่าเท่ากับ ```2**7``` หรือไม่ เราจะใช้ตัวดำเนินการเปรียบเทียบ ```==``` (รายละเอียดจะอธิบายภายหลัง)" ] }, { "cell_type": "code", "execution_count": 103, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 103, "metadata": {}, "output_type": "execute_result" } ], "source": [ "_ == 2**7" ] }, { "cell_type": "markdown", "metadata": { "tags": [] }, "source": [ "## จำนวนเต็ม (Integer number) และจำนวนจริง (Floating point number)\n", "\n", "สำหรับเลขจำนวนเต็มและเลขจำนวนจริง (หรือเลขทศนิยม) ในภาษาไพธอน ถึงแม้ว่าในทางคณิตศาสตร์จะมีค่าเท่ากัน แต่รูปแบบของข้อมูลที่ถูกจัดเก็บในคอมฯ นั้นต่างกัน ดังนั้นการแสดงผลจึงต่างกัน" ] }, { "cell_type": "code", "execution_count": 104, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "17.0" ] }, "execution_count": 104, "metadata": {}, "output_type": "execute_result" } ], "source": [ "17 / 1" ] }, { "cell_type": "code", "execution_count": 105, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "17" ] }, "execution_count": 105, "metadata": {}, "output_type": "execute_result" } ], "source": [ "17 // 1" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "แต่ถ้าเปรียบเทียบผลลัพธ์ที่ได้ จะพบว่าทั้งคู่มีค่าเท่ากัน ดังแสดงต่อไปนี้ (การตรวจสอบว่าค่าเท่ากันหรือไม่ เราจะใช้ตัวดำเนินการ ```==``` ซึ่งจะอธิบายภายหนัง)" ] }, { "cell_type": "code", "execution_count": 106, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 106, "metadata": {}, "output_type": "execute_result" } ], "source": [ "17/1 == 17//1" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "การหารด้วย ```/``` จะได้ผลลัพธ์เป็นทศนิยมเสมอ" ] }, { "cell_type": "code", "execution_count": 107, "metadata": { "scrolled": true }, "outputs": [ { "data": { "text/plain": [ "1.0" ] }, "execution_count": 107, "metadata": {}, "output_type": "execute_result" } ], "source": [ "17 / 17" ] }, { "cell_type": "code", "execution_count": 108, "metadata": { "scrolled": true }, "outputs": [ { "data": { "text/plain": [ "5.666666666666667" ] }, "execution_count": 108, "metadata": {}, "output_type": "execute_result" } ], "source": [ "17 / 3" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "ในกรณีของ ``` +, -, *, //, %, ** ``` ถ้าตัวเลขทั้งสองตัวเป็นเลขจำนวนเต็ม ผลลัพธ์ที่ได้จะเป็นจำนวนเต็ม แต่ถ้าตัวใดตัวหนึ่งเป็นเลขจำนวนจริง ผลลัพธ์ที่ได้จะกลายเป็นจำนวนจริง\n", "\n", "หารปัดเศษทิ้งของเลขจำนวนเต็ม" ] }, { "cell_type": "code", "execution_count": 109, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "5" ] }, "execution_count": 109, "metadata": {}, "output_type": "execute_result" } ], "source": [ "17 // 3 " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "หารเอาเศษของเลขจำนวนเต็ม" ] }, { "cell_type": "code", "execution_count": 110, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "2" ] }, "execution_count": 110, "metadata": {}, "output_type": "execute_result" } ], "source": [ "17 % 3" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "แต่ถ้าตัวใดตัวหนึ่งเป็นเลขจำนวนจริง ผลลัพธ์จะกลายเป็นจำนวนจริง" ] }, { "cell_type": "code", "execution_count": 111, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "20.0" ] }, "execution_count": 111, "metadata": {}, "output_type": "execute_result" } ], "source": [ "17 + 3.0" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "ลองคีย์ตัวเลข (อะไรก็ได้) และเครื่องหมาย ``` +, -, *, //, %, ** ``` ทดสอบดูว่าผลลัพธ์เป็นอย่างที่คิดหรือไม่" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## เลขทศนิยมในรูปของเลขยกกำลังฐานสิบ (Scientific Notation/Exponential Notation)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "ลองคำนวณว่า 1000 บิต (bits) จะเก็บข้อมูลได้กี่รูปแบบ (คำตอบคือ $2^{1000}$)" ] }, { "cell_type": "code", "execution_count": 112, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "1.0715086071862673e+301" ] }, "execution_count": 112, "metadata": {}, "output_type": "execute_result" } ], "source": [ "2.0 ** 1000" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "ผลลัพธ์ที่ได้เป็นจำนวนจริง เนื่องจากมี ```2.0``` เป็นจำนวนจริง\n", "\n", "ไพธอนจะแสดงเลขจำนวนจริงที่มีค่ามากๆ ในรูปของเลขทศนิยมยกกำลังฐานสิบ (สัญกรณ์วิทยาศาสตร์ (อังกฤษ: Scientific Notation หรือ Exponential Notation)) \n", "\n", "ในภาษาไพธอน ```e``` หรือ ```E``` หมายถึง 10 ยกกำลัง\n", "\n", "ดังนั้นผลคำนวณข้างต้น $e+301$ จึงหมายถึง $\\times 10^{301}$\n" ] }, { "cell_type": "code", "execution_count": 113, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "9.332636185032189e-302" ] }, "execution_count": 113, "metadata": {}, "output_type": "execute_result" } ], "source": [ "2.0 ** -1000" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "จำนวนจริงที่มีค่าน้อยมากๆ ก็แสดงในรูปของเลขทศนิยมยกกำลังสิบเช่นกัน\n", "\n", "\n", "\n", "$9.332636185032189e{+}302 \\Leftrightarrow 9.332636185032189 \\times 10^{302}$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## จำนวนเต็มในไพธอนมีขนาดไม่สิ้นสุด!" ] }, { "cell_type": "code", "execution_count": 114, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376" ] }, "execution_count": 114, "metadata": {}, "output_type": "execute_result" } ], "source": [ "2 ** 1000" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "กรณีข้างต้นได้ผลลัพธ์เป็นจำนวนเต็ม **ตัวเลขเยอะ (301 หลัก)!!!**\n", "\n", "ในภาษาไพธอน จำนวนเต็มมีขนาดไม่สิ้นสุด! (แต่แน่นอน ได้ไม่เกินหน่วยความจำ (Memory) ของคอมฯ ที่ใช้เก็บข้อมูล)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "ลองคำนวน 2 ยกกำลัง 2 ยกกำลัง 2 ยกกำลัง 2 $ \\left(2^{2^{2^{2}}}\\right)$" ] }, { "cell_type": "code", "execution_count": 115, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "65536" ] }, "execution_count": 115, "metadata": {}, "output_type": "execute_result" } ], "source": [ "2**2**2**2" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "2 ยกกำลังซ้อนกัน 4 ตัวยังไม่เท่าไหร่ ลอง 5 ตัวดู $ \\left(2^{2^{2^{2^{2}}}}\\right)$ ..." ] }, { "cell_type": "code", "execution_count": 116, "metadata": {}, "outputs": [], "source": [ "# ลองเขียนโค้ดลงในเซลล์นี้\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## การเปลี่ยนชนิดข้อมูลระหว่างจำนวนเต็มและจำนวนจริง\n", "\n", "ในการแปลงชนิดข้อมูล (Typecasting) จากจำนวนจริงให้เป็นจำนวนเต็ม ให้ใช้ฟังก์ชัน ```int()``` (รายละเอียดจะอธิบายภายหลัง) \n", "ฟังก์ชั่น ```int()``` คืนค่าผลลัพธ์เป็นจำนวนเต็มโดยการ**ปัดทศนิยมทิ้ง** (ปัดเศษทิ้ง)" ] }, { "cell_type": "code", "execution_count": 117, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "2" ] }, "execution_count": 117, "metadata": {}, "output_type": "execute_result" } ], "source": [ "int(2.718281828459045)" ] }, { "cell_type": "code", "execution_count": 118, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "-2" ] }, "execution_count": 118, "metadata": {}, "output_type": "execute_result" } ], "source": [ "int(-2.718281828459045)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "ในทางกลับกัน ถ้าต้องการเปลี่ยนจำนวนเต็มให้เป็นจำนวนจริง ให้ใช้ฟังก์ชัน ```float()``` \n", "\n", "(รายละเอียดจะอธิบายภายหลัง [เขียนโค้ดแรกในภาษาไพธอน (Python)(การแปลงชนิดของออบเจกต์ (Typecasting)](Ch1.ipynb#การแปลงชนิดของออบเจกต์ (Typecasting))" ] }, { "cell_type": "code", "execution_count": 119, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "2.0" ] }, "execution_count": 119, "metadata": {}, "output_type": "execute_result" } ], "source": [ "float(2)" ] }, { "cell_type": "code", "execution_count": 120, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "-2.0" ] }, "execution_count": 120, "metadata": {}, "output_type": "execute_result" } ], "source": [ "float(-2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "ได้ผลลัพธ์เช่นเดียวกับการบวกด้วย 0.0" ] }, { "cell_type": "code", "execution_count": 121, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "-2.0" ] }, "execution_count": 121, "metadata": {}, "output_type": "execute_result" } ], "source": [ "-2 + 0.0" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## ลำดับการประมวลผลของตัวดำเนินการและวงเล็บ ( )\n", "\n", "ในการประมวลผล ``` \\*, \\/ ``` จะถูกดำเนินการก่อน ``` +, - ``` กล่าวคือ ภาษาไพธอนกำหนดให้ ``` \\*, \\/ ``` มีลำดับความสำคัญสูงกว่า ``` +, - ```\n" ] }, { "cell_type": "code", "execution_count": 122, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "-18" ] }, "execution_count": 122, "metadata": {}, "output_type": "execute_result" } ], "source": [ "9 - 9 * 3" ] }, { "cell_type": "code", "execution_count": 123, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "0" ] }, "execution_count": 123, "metadata": {}, "output_type": "execute_result" } ], "source": [ "(9 - 9) * 3" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "ตัวอย่างข้างต้นแสดงให้เห็นว่า 9 - 9 * 3 มีค่าเท่ากับ 9 - (9 * 3) " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**ลำดับความสำคัญเรียงจากสูงไปต่ำ** ได้ดังนี้ :\n", "\n", "``` ()วงเล็บ ``` $\\rightarrow$ ``` ** ``` $\\rightarrow$ ``` *, /, //, % ``` $\\rightarrow$ ``` +, - ``` ตามลำดับ" ] }, { "cell_type": "code", "execution_count": 124, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "8" ] }, "execution_count": 124, "metadata": {}, "output_type": "execute_result" } ], "source": [ "22 // 3 + 5 - 2 ** 2" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "จากตัวอย่างข้างต้น การยกกำลัง 2**2 จะถูกประมวลผลก่อน จากนั้น ประมวลผลการหาร 22 // 3 และประมวลผลการบวกลบ (7) + 5 - (4) เป็นลำดับสุดท้าย" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "ตัวอย่างข้างต้น เราสามารถใช้วงเล็บ ```()``` กำหนดลำดับได้" ] }, { "cell_type": "code", "execution_count": 125, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "8" ] }, "execution_count": 125, "metadata": {}, "output_type": "execute_result" } ], "source": [ "(22 // 3) + 5 - (2 ** 2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "ถ้าลำดับความสำคัญเท่ากัน จะประมวลผลจากซ้ายไปขวาเสมอ " ] }, { "cell_type": "code", "execution_count": 126, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "9.0" ] }, "execution_count": 126, "metadata": {}, "output_type": "execute_result" } ], "source": [ "2 / 2 * 9" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "ยกเว้น ```**``` ประมวลผลจากขวาไปซ้าย" ] }, { "cell_type": "code", "execution_count": 127, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "2417851639229258349412352" ] }, "execution_count": 127, "metadata": {}, "output_type": "execute_result" } ], "source": [ "2 ** 3 ** 4" ] }, { "cell_type": "code", "execution_count": 128, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "2417851639229258349412352" ] }, "execution_count": 128, "metadata": {}, "output_type": "execute_result" } ], "source": [ "2 ** (3 ** 4)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**ตัวดำเนินการทางคณิตศาตร์มีลำดับในการประมวลผล ดังนั้นต้องระวัง!!**\n", "\n", "ลองทดสอบดู" ] }, { "cell_type": "code", "execution_count": 129, "metadata": {}, "outputs": [], "source": [ "# เขียนโค้ดด้านล่าง แล้วกด Shift+Enter\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "```{attention}\n", " \n", "* ต้องเข้าใจลำดับการประมวลผลของตัวดำเนินการ (operator)\n", " **(จำ) ลำดับความสำคัญ (สูง $\\rightarrow$ ต่ำ) : ( ) วงเล็บ $\\rightarrow$ \\*\\* $\\rightarrow$ \\*, \\/, \\//, % $\\rightarrow$ +, - ตามลำดับ**\n", "\n", "* ถ้าลำดับความสำคัญเท่ากัน จะประมวลผลจากซ้ายไปขวาเสมอ เช่น 20\\/2\\*9 จะได้ (20\\/2)\\*9 \n", " (**ยกเว้น** เครื่องหมายยกกำลัง \\*\\* จะประมวลผลจากขวาไปซ้าย!)\n", "\n", "* ถ้าต้องการให้ชัวร์ ใส่วงเล็บ เช่น (22//3)+5-(2**2) สามารถช่วยป้องกันความผิดพลาดได้\n", "\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Ternary conditional operator ```(condition)?([on_true]:[on_false]``` ในภาษาไพธอน\n", "\n", "ในภาษาไพธอนไม่มีโอเปอร์เรเตอร์เทอร์นารี (Ternary Operator (Conditional operator)) ```(condition)?([on_true]:[on_false]``` เหมือนในภาษา C/C++, Java หรือ JavaScript แต่สามารถเขียนแทนด้วยคำสั่ง ```if-else``` บรรทัดเดียวได้\n", "\n", "**Syntax :**\n", "```\n", "[on_true] if [expression(condition)] else [on_false] \n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "[ในกรณีภาษา C/C++]\n", "\n", "/* Ternary Operator (Conditional operator) - C/Cpp ternary operator. */ \n", "\n", "a = True\n", "\n", "a?100:60\n", "\n", "----------\n", "\n", "Output: 100" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "ในกรณีภาษาไพธอน ใช้คำสั่ง ```if-else``` เขียนแทนได้ (รายละเอียดของคำสั่ง if-else บรรทัดเดียวจะอธิบายทีหลัง)" ] }, { "cell_type": "code", "execution_count": 130, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "60" ] }, "execution_count": 130, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a = True\n", "60 if a == True else 100" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Error (ข้อผิดพลาด) ตัวแรก...\n", "\n", "หลังจากได้ลองเขียนโค้ดกันมา ก็น่าจะเกิด ** Error ** (ความผิดพลาด/ข้อผิดพลาด) บ้างไม่มากก็น้อย \n", "\n", "Error คือ ข้อผิดพลาดที่ทำให้โปรแกรมหยุดทำงาน หรือไม่สามารถทำงานต่อได้\n", "\n", "Error ต่อไปนี้เป็นตัวอย่างของข้อผิดพลาดที่อาจเกิดขึ้นได้ขณะเขียนโปรแกรม" ] }, { "cell_type": "code", "execution_count": 131, "metadata": {}, "outputs": [ { "ename": "ZeroDivisionError", "evalue": "division by zero", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mZeroDivisionError\u001b[0m Traceback (most recent call last)", "Cell \u001b[0;32mIn [131], line 1\u001b[0m\n\u001b[0;32m----> 1\u001b[0m \u001b[38;5;241;43m22\u001b[39;49m\u001b[38;5;241;43m/\u001b[39;49m\u001b[38;5;241;43m0\u001b[39;49m\n", "\u001b[0;31mZeroDivisionError\u001b[0m: division by zero" ] } ], "source": [ "22/0" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "ข้อผิดพลาดนี้เกิดขึ้นเนื่องจากหารด้วยศูนย์ (ZeroDivisionError) เป็น **ข้อผิดพลาดที่เกิดในขณะรันโปรแกรม (Runtime Errors)**\n", "\n", "ในกรณีที่ Error เกิดขึ้น เราสามารถทำการแก้ไขแล้วรันใหม่ได้\n", "\n", "ในตัวอย่างข้างต้น ลองแก้โค้ดใหม่โดยเปลี่ยนตัวหารจาก 0 เป็น 7 แล้วลองรันใหม่ดู" ] }, { "cell_type": "code", "execution_count": 169, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "3.142857142857143" ] }, "execution_count": 169, "metadata": {}, "output_type": "execute_result" } ], "source": [ "22/7" ] }, { "cell_type": "markdown", "metadata": {}, "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "ข้อผิดพลาดนี้เป็น ** ข้อผิดพลาดที่เกิดจากไวยากรณ์ (Syntax Errors) ** กล่าวคือ \n", "เขียนคำสั่งผิดรูปแบบไวยากรณ์ (Syntax) ไม่ตรงตามรูปแบบของภาษาที่กำหนดไว้ ทำให้ไม่สามารถประมวลผลได้ \n", "(เป็นข้อผิดพลาดที่เกิดขึ้นบ่อยที่สุด ขณะเรียนรู้เขียนโปรแกรม โดยจะมีเครื่องหมาย ```^``` ระบุตำแหน่งที่ผิด (คร่าวๆ))\n", "\n", "รายละเอียดของข้อผิดพลาดอยู่ในบทถัดไปในหัวข้อ [ไพธอนจะแจ้ง Error ก่อนทําการรันหรือไม่?](ch1-errors)\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## [Exercise]: ตัวเลขและตัวดำเนินการทางคณิตศาสตร์" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "`1.` จงเขียนโด้ดเพื่อคำนวณ $ 9^{2 \\times 3.1415} + 2^{0.5} + 9/2 $\n", "\n", "\n", "`2.` จงเขียนโด้ดเพื่อแสดงผลลัพธ์ของสมการต่อไปนี้\n", " 1. $2^3 + 9 \\times 7$\n", " \n", " 2. $\\dfrac{1}{2} + \\dfrac{1}{3} + \\dfrac{1}{4} +\\dfrac{1}{5} $\n", " \n", " 3. $\\sqrt{3^2 - 4 \\times 1 \\times 2} $\n", " \n", " 4. $\\dfrac{\\sqrt{4 \\times 3 \\times 7}}{2 \\times 3} $\n", " \n", " \n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "```{tip}\n", "สามารถเพิ่มเซลล์ (cell) ได้โดย\n", "* 1) กดปุ่ม + ในแถบเครื่องมือเพื่อเพิ่มเซลล์ด้านล่างเซลล์ที่กำลังเลือกอยู่ หรือ \n", "* 2) กดคำสั่งที่เมนู Insert >> Insert Cell Above เพื่อเพิ่มเซลล์ด้านบน หรือ Insert Cell Below เพื่อเพิ่มเซลล์ด้านล่างเซลล์ที่กำลังเลือกอยู่ หรือ\n", "* 3) กดคีย์ **A** (**A**bove) หรือ **B** (**B**elow) ในโหมด Command mode เพื่อพิ่มเซลล์ด้านบน หรือด้านล่างเซลล์ที่กำลังเลือกอยู่\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## ฟังก์ชันทางคณิตศาสตร์ - **math module** (Import module)" ] }, { "cell_type": "code", "execution_count": 133, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "1.4142135623730951" ] }, "execution_count": 133, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import math\n", "\n", "math.sqrt(2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "ภาษาไพธอนมีฟังก์ชันทางคณิตศาสตร์ต่างๆ ที่ถูกจัดเตรียมไว้ในรูปของไลบรารี (Library หรือ Module (โมดูล)) ที่ชื่อ ```math``` หากต้องการใช้ก็สามารถทำได้โดยใช้รันคำสั่ง ```import library_name``` ดังที่แสดงไว้ข้างต้น\n", "\n", "คำสั่ง ```import math``` เป็นคำสั่งนำเข้าไลบรารี่ ```math``` เข้ามาในโปรแกรม หลังจากรันคำสั่งแล้ว เราจะสามารถใช้ฟังก์ชันในรูปแบบ ```math.function_name()``` ได้ \n", "\n", "ในตัวอย่างข้างต้น เราเรียกใช้ฟังก์ชัน ```math.sqrt()``` เพื่อคำนวณรากที่สองของ $(\\sqrt{2})$\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "นอกจากนี้ ยังมีฟังก์ชั่น ```sin()```, ```cos()``` ดังตัวอย่างต่อไปนี้\n", "\n", "ศึกษารายละเอียดฟังก์ชันต่างๆ ที่อยู่ในไลบรารี ```math``` ได้ที่ [Python.org (math — Mathematical functions)](https://docs.python.org/3/library/math.html)" ] }, { "cell_type": "code", "execution_count": 134, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "0.0" ] }, "execution_count": 134, "metadata": {}, "output_type": "execute_result" } ], "source": [ "math.sin(0)" ] }, { "cell_type": "code", "execution_count": 135, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "3.141592653589793" ] }, "execution_count": 135, "metadata": {}, "output_type": "execute_result" } ], "source": [ "math.pi" ] }, { "cell_type": "code", "execution_count": 136, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "1.2246467991473532e-16" ] }, "execution_count": 136, "metadata": {}, "output_type": "execute_result" } ], "source": [ "math.sin(math.pi)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "ในความเป็นจริง sin($\\pi$) มีค่าศูนย์ แต่ไพธอนคำนวณได้ $1.2246467991473532 \\times 10^{-16} $ แม้จะเข้าใกล้ศูนย์ แต่ไม่เท่ากับศูนย์ เพราะเหตุใด??\n", "\n", "ทั้งนี้เพราะค่า $\\pi$ ที่ใช้ในการคำนวณมีค่า $3.141592653589793\n", "$ ซึ่งเป็นค่าโดยประมาณ ไม่ใช่ค่าของ $\\pi$ ที่แท้จริง [[Stackoverflow]](https://stackoverflow.com/questions/18646477/why-is-sin180-not-zero-when-using-python-and-numpy)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "หากต้องการดูว่าโมดูล (ไลบรารี) **math** มีฟังก์ชั่นอะไรให้ใช้บ้าง ให้ใช้คำสั่ง ```help()``` ดังตัวอย่างต่อไปนี้" ] }, { "cell_type": "code", "execution_count": 137, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Help on module math:\n", "\n", "NAME\n", " math\n", "\n", "MODULE REFERENCE\n", " https://docs.python.org/3.8/library/math\n", " \n", " The following documentation is automatically generated from the Python\n", " source files. It may be incomplete, incorrect or include features that\n", " are considered implementation detail and may vary between Python\n", " implementations. When in doubt, consult the module reference at the\n", " location listed above.\n", "\n", "DESCRIPTION\n", " This module provides access to the mathematical functions\n", " defined by the C standard.\n", "\n", "FUNCTIONS\n", " acos(x, /)\n", " Return the arc cosine (measured in radians) of x.\n", " \n", " acosh(x, /)\n", " Return the inverse hyperbolic cosine of x.\n", " \n", " asin(x, /)\n", " Return the arc sine (measured in radians) of x.\n", " \n", " asinh(x, /)\n", " Return the inverse hyperbolic sine of x.\n", " \n", " atan(x, /)\n", " Return the arc tangent (measured in radians) of x.\n", " \n", " atan2(y, x, /)\n", " Return the arc tangent (measured in radians) of y/x.\n", " \n", " Unlike atan(y/x), the signs of both x and y are considered.\n", " \n", " atanh(x, /)\n", " Return the inverse hyperbolic tangent of x.\n", " \n", " ceil(x, /)\n", " Return the ceiling of x as an Integral.\n", " \n", " This is the smallest integer >= x.\n", " \n", " comb(n, k, /)\n", " Number of ways to choose k items from n items without repetition and without order.\n", " \n", " Evaluates to n! / (k! * (n - k)!) when k <= n and evaluates\n", " to zero when k > n.\n", " \n", " Also called the binomial coefficient because it is equivalent\n", " to the coefficient of k-th term in polynomial expansion of the\n", " expression (1 + x)**n.\n", " \n", " Raises TypeError if either of the arguments are not integers.\n", " Raises ValueError if either of the arguments are negative.\n", " \n", " copysign(x, y, /)\n", " Return a float with the magnitude (absolute value) of x but the sign of y.\n", " \n", " On platforms that support signed zeros, copysign(1.0, -0.0)\n", " returns -1.0.\n", " \n", " cos(x, /)\n", " Return the cosine of x (measured in radians).\n", " \n", " cosh(x, /)\n", " Return the hyperbolic cosine of x.\n", " \n", " degrees(x, /)\n", " Convert angle x from radians to degrees.\n", " \n", " dist(p, q, /)\n", " Return the Euclidean distance between two points p and q.\n", " \n", " The points should be specified as sequences (or iterables) of\n", " coordinates. Both inputs must have the same dimension.\n", " \n", " Roughly equivalent to:\n", " sqrt(sum((px - qx) ** 2.0 for px, qx in zip(p, q)))\n", " \n", " erf(x, /)\n", " Error function at x.\n", " \n", " erfc(x, /)\n", " Complementary error function at x.\n", " \n", " exp(x, /)\n", " Return e raised to the power of x.\n", " \n", " expm1(x, /)\n", " Return exp(x)-1.\n", " \n", " This function avoids the loss of precision involved in the direct evaluation of exp(x)-1 for small x.\n", " \n", " fabs(x, /)\n", " Return the absolute value of the float x.\n", " \n", " factorial(x, /)\n", " Find x!.\n", " \n", " Raise a ValueError if x is negative or non-integral.\n", " \n", " floor(x, /)\n", " Return the floor of x as an Integral.\n", " \n", " This is the largest integer <= x.\n", " \n", " fmod(x, y, /)\n", " Return fmod(x, y), according to platform C.\n", " \n", " x % y may differ.\n", " \n", " frexp(x, /)\n", " Return the mantissa and exponent of x, as pair (m, e).\n", " \n", " m is a float and e is an int, such that x = m * 2.**e.\n", " If x is 0, m and e are both 0. Else 0.5 <= abs(m) < 1.0.\n", " \n", " fsum(seq, /)\n", " Return an accurate floating point sum of values in the iterable seq.\n", " \n", " Assumes IEEE-754 floating point arithmetic.\n", " \n", " gamma(x, /)\n", " Gamma function at x.\n", " \n", " gcd(x, y, /)\n", " greatest common divisor of x and y\n", " \n", " hypot(...)\n", " hypot(*coordinates) -> value\n", " \n", " Multidimensional Euclidean distance from the origin to a point.\n", " \n", " Roughly equivalent to:\n", " sqrt(sum(x**2 for x in coordinates))\n", " \n", " For a two dimensional point (x, y), gives the hypotenuse\n", " using the Pythagorean theorem: sqrt(x*x + y*y).\n", " \n", " For example, the hypotenuse of a 3/4/5 right triangle is:\n", " \n", " >>> hypot(3.0, 4.0)\n", " 5.0\n", " \n", " isclose(a, b, *, rel_tol=1e-09, abs_tol=0.0)\n", " Determine whether two floating point numbers are close in value.\n", " \n", " rel_tol\n", " maximum difference for being considered \"close\", relative to the\n", " magnitude of the input values\n", " abs_tol\n", " maximum difference for being considered \"close\", regardless of the\n", " magnitude of the input values\n", " \n", " Return True if a is close in value to b, and False otherwise.\n", " \n", " For the values to be considered close, the difference between them\n", " must be smaller than at least one of the tolerances.\n", " \n", " -inf, inf and NaN behave similarly to the IEEE 754 Standard. That\n", " is, NaN is not close to anything, even itself. inf and -inf are\n", " only close to themselves.\n", " \n", " isfinite(x, /)\n", " Return True if x is neither an infinity nor a NaN, and False otherwise.\n", " \n", " isinf(x, /)\n", " Return True if x is a positive or negative infinity, and False otherwise.\n", " \n", " isnan(x, /)\n", " Return True if x is a NaN (not a number), and False otherwise.\n", " \n", " isqrt(n, /)\n", " Return the integer part of the square root of the input.\n", " \n", " ldexp(x, i, /)\n", " Return x * (2**i).\n", " \n", " This is essentially the inverse of frexp().\n", " \n", " lgamma(x, /)\n", " Natural logarithm of absolute value of Gamma function at x.\n", " \n", " log(...)\n", " log(x, [base=math.e])\n", " Return the logarithm of x to the given base.\n", " \n", " If the base not specified, returns the natural logarithm (base e) of x.\n", " \n", " log10(x, /)\n", " Return the base 10 logarithm of x.\n", " \n", " log1p(x, /)\n", " Return the natural logarithm of 1+x (base e).\n", " \n", " The result is computed in a way which is accurate for x near zero.\n", " \n", " log2(x, /)\n", " Return the base 2 logarithm of x.\n", " \n", " modf(x, /)\n", " Return the fractional and integer parts of x.\n", " \n", " Both results carry the sign of x and are floats.\n", " \n", " perm(n, k=None, /)\n", " Number of ways to choose k items from n items without repetition and with order.\n", " \n", " Evaluates to n! / (n - k)! when k <= n and evaluates\n", " to zero when k > n.\n", " \n", " If k is not specified or is None, then k defaults to n\n", " and the function returns n!.\n", " \n", " Raises TypeError if either of the arguments are not integers.\n", " Raises ValueError if either of the arguments are negative.\n", " \n", " pow(x, y, /)\n", " Return x**y (x to the power of y).\n", " \n", " prod(iterable, /, *, start=1)\n", " Calculate the product of all the elements in the input iterable.\n", " \n", " The default start value for the product is 1.\n", " \n", " When the iterable is empty, return the start value. This function is\n", " intended specifically for use with numeric values and may reject\n", " non-numeric types.\n", " \n", " radians(x, /)\n", " Convert angle x from degrees to radians.\n", " \n", " remainder(x, y, /)\n", " Difference between x and the closest integer multiple of y.\n", " \n", " Return x - n*y where n*y is the closest integer multiple of y.\n", " In the case where x is exactly halfway between two multiples of\n", " y, the nearest even value of n is used. The result is always exact.\n", " \n", " sin(x, /)\n", " Return the sine of x (measured in radians).\n", " \n", " sinh(x, /)\n", " Return the hyperbolic sine of x.\n", " \n", " sqrt(x, /)\n", " Return the square root of x.\n", " \n", " tan(x, /)\n", " Return the tangent of x (measured in radians).\n", " \n", " tanh(x, /)\n", " Return the hyperbolic tangent of x.\n", " \n", " trunc(x, /)\n", " Truncates the Real x to the nearest Integral toward 0.\n", " \n", " Uses the __trunc__ magic method.\n", "\n", "DATA\n", " e = 2.718281828459045\n", " inf = inf\n", " nan = nan\n", " pi = 3.141592653589793\n", " tau = 6.283185307179586\n", "\n", "FILE\n", " /Users/tube.sc/.pyenv/versions/3.8.13/lib/python3.8/lib-dynload/math.cpython-38-darwin.so\n", "\n", "\n" ] } ], "source": [ "help(math)\n" ] }, { "cell_type": "code", "execution_count": 138, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "1.0" ] }, "execution_count": 138, "metadata": {}, "output_type": "execute_result" } ], "source": [ "math.sin(math.pi/2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "เนื่องจากหน่วยของมุมในโมดูล ```math``` มีหน่วยเป็นเรเดียน ถ้าหน่วยของมุมเป็นองศา ต้องใช้ฟังก์ชัน ```math.radians())``` แปลงเป็นเรเดียนก่อน แล้วคำนวณค่า sin จากฟังก์ชัน ```math.sin()```" ] }, { "cell_type": "code", "execution_count": 139, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "1.0" ] }, "execution_count": 139, "metadata": {}, "output_type": "execute_result" } ], "source": [ "math.sin(math.radians(90))" ] }, { "cell_type": "markdown", "metadata": { "tags": [] }, "source": [ "## [Exercise]: โมดูล ```math``` \n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "```1.``` จงใช้่ไลบรารี ```math``` เขียนโด้ดหาค่า**อัตราส่วนทอง (Golden ratio)** [WIKI](https://th.wikipedia.org/wiki/อัตราส่วนทอง) โดยอัตราส่วนทองมีค่าเท่ากับ รากที่สองของ 5 บวกกับ 1 แล้วหารด้วย 2 ซึ่งจะมีค่าประมาณ 1.618 \n", "\n", "$$\n", "\\dfrac{1+\\sqrt{5}} {2}\n", "$$\n" ] }, { "cell_type": "code", "execution_count": 140, "metadata": {}, "outputs": [], "source": [ "# เขียนโค้ดด้านล่าง แล้วกด Shift+Enter\n", "import math\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "```2.``` จงใช้่ไลบรารี ```math``` เขียนโด้ดเพื่อแสดงผลลัพธ์ของสมการต่อไปนี้" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "```2.1)``` $2^3 + 9 \\times 7$\n", " \n", "```2.2)``` $ ln(\\dfrac{1}{2} + \\dfrac{1}{3} + \\dfrac{1}{4} +\\dfrac{1}{5}) $\n", " \n", "```2.3)``` $\\sqrt{3^2 - 4 \\times 1 \\times 2} $\n", " \n", "```2.4)``` $\\left(\\dfrac{\\sqrt{4 \\times 3 \\times 7}}{2 \\times 3} \\right)^{10}$\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "```{tip}\n", "สามารถเพิ่มเซลล์ (cell) ได้โดย\n", " 1. กดปุ่ม + ในแถบเครื่องมือเพื่อเพิ่มเซลล์ด้านล่างเซลล์ที่กำลังเลือกอยู่ หรือ \n", " 2. กดคำสั่งที่เมนู Insert >> Insert Cell Above เพื่อเพิ่มเซลล์ด้านบน หรือ Insert Cell Below เพื่อเพิ่มเซลล์ด้านล่างเซลล์ที่กำลังเลือกอยู่ หรือ\n", " 3. กดคีย์ **A** (**A**bove) หรือ **B** (**B**elow) ในโหมด Command mode เพื่อพิ่มเซลล์ด้านบน หรือด้านล่างเซลล์ที่กำลังเลือกอยู่\n", "```" ] }, { "cell_type": "code", "execution_count": 141, "metadata": {}, "outputs": [], "source": [ "# เขียนโค้ดด้านล่าง แล้วกด Shift+Enter\n", "import math\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "```3.``` จงหาพื้นผิวของโลกในหน่วยตารางเมตร กำหนดให้รัศมีของโลกมีค่าเป็น 6,371 km\n" ] }, { "cell_type": "code", "execution_count": 142, "metadata": {}, "outputs": [], "source": [ "# เขียนโค้ดด้านล่าง แล้วกด Shift+Enter\n", "import math\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "```4.``` ให้เขียนโค้ดกำหนดค่าให้กับตัวแปร $n$ (จะกำหนดค่าเป็นเท่าไหร่ก็ได้) แล้วคำนวณสมการ $\\left(1+\\dfrac{1}{n}\\right)^n$\n", "ถามว่า ถ้า $n$ มีค่าเพิ่มมากขึ้นๆ ผลลัพธ์ของสมการจะมีค่าเท่าไหร่\n", "\n", "_[Hint] เปลี่ยนค่า n ให้เพิ่มมากขึ้น (ด้วยมือ) แล้วดูว่าผลลัพธ์ของสมการจะลู่เข้าสู่ค่าอะไร?_\n", "\n", "$$\n", "\\lim_{n\\to\\infty}(1+\\frac{1}{n})^n\n", "$$\n" ] }, { "cell_type": "code", "execution_count": 143, "metadata": {}, "outputs": [], "source": [ "# เขียนโค้ดด้านล่าง แล้วกด Shift+Enter\n", "import math\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "---" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## (เพิ่มเติม) สตริง (Strings; ข้อความ/สายอักขระ) " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "นอกจากตัวเลขแล้ว Python ยังสามารถจัดการกับสตริงได้อย่างง่ายๆ เช่นกัน \n", "\n", "\n", "สตริง (String) คือ ชนิดของข้อมูลที่เป็นข้อความหรือตัวอักษร/อักขระ (Character) หลายๆ ตัวเรียงต่อๆ กัน\n", "\n", "ซึ่งสามารถแสดงได้หลายวิธี เช่น\n", "\n", "1) อยู่ในเครื่องหมายคำพูดเดี่ยว single quotes ('...') หรือ\n", "\n", "2) อยู่ในเครื่องหมายคำพูดคู่ double quotes (\"...\")\n", "\n", "ซึ่งทั้งสองวิธีให้ผลลัพธ์เหมือนกัน" ] }, { "cell_type": "markdown", "metadata": {}, "source": [] }, { "cell_type": "code", "execution_count": 144, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Scrambled egg'" ] }, "execution_count": 144, "metadata": {}, "output_type": "execute_result" } ], "source": [ "'Scrambled egg'" ] }, { "cell_type": "code", "execution_count": 145, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'ไข่คน หรือ ไข่กวน'" ] }, "execution_count": 145, "metadata": {}, "output_type": "execute_result" } ], "source": [ "\"ไข่คน หรือ ไข่กวน\" " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Escape Sequences ในภาษาไพธอน\n", "\n", "รหัสพิเศษ (Escape Sequences) ในภาษาไพธอนจะเริ่มต้นด้วยเครื่องหมาย ```\"\\\"``` (Back slash/Backslash) \n", "\n", "ภาษาไพธอนจะใช้เครื่องหมายคำพูด single quotes ```' '``` หรือ double quotes ```\" \"``` คล่อมข้อความเพื่อสร้างสตริง แต่ในกรณีที่ภายในข้อความมีเครื่องหมายคำพูดปนอยู่ด้วย จะต้องใช้รหัสพิเศษ ```\"\\\"``` นำหน้า \n", "\n", "ยกตัวอย่าง ในกรณีที่ข้อความมีเครื่องหมายคำพูด ```'``` ปนอยู่ด้วย ถ้าเขียนแบบนี้" ] }, { "cell_type": "code", "execution_count": 146, "metadata": {}, "outputs": [ { "ename": "SyntaxError", "evalue": "invalid syntax (551072150.py, line 1)", "output_type": "error", "traceback": [ "\u001b[0;36m Cell \u001b[0;32mIn [146], line 1\u001b[0;36m\u001b[0m\n\u001b[0;31m 'I doesn't care'\u001b[0m\n\u001b[0m ^\u001b[0m\n\u001b[0;31mSyntaxError\u001b[0m\u001b[0;31m:\u001b[0m invalid syntax\n" ] } ], "source": [ "'I doesn't care' " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "จะเกิด ```ข้อผิดพลาดที่เกิดจากไวยากรณ์ (Syntax Errors)``` \n", "\n", "ในกรณีนี้ เราจะใช้รหัสพิเศษ ``` \\' ``` แทน ```'``` ดังนี้" ] }, { "cell_type": "code", "execution_count": 147, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "\"I doesn't care\"" ] }, "execution_count": 147, "metadata": {}, "output_type": "execute_result" } ], "source": [ "'I doesn\\'t care' " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "หรือจะใช้ Double quotes คล่อมทั้งข้อความแทน Single quotes แบบนี้ก็ได้ " ] }, { "cell_type": "code", "execution_count": 148, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "\"I doesn't care\"" ] }, "execution_count": 148, "metadata": {}, "output_type": "execute_result" } ], "source": [ "\"I doesn't care\" " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " ในภาษาไพทอน เราสามารถใช้ Single quote สลับกับ Double quote ได้ โดยไม่จำเป็นว่าจะต้องเป็นตัวไหนขึ้นก่อน กล่าวคือ ถ้าภายในข้อความมี Double quote ก็ให้ใช้ Single quotes คล่อม " ] }, { "cell_type": "code", "execution_count": 149, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'\"Yes,\" he said.'" ] }, "execution_count": 149, "metadata": {}, "output_type": "execute_result" } ], "source": [ "'\"Yes,\" he said.'" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "แต่ถ้าภายในข้อความมี Single quote ก็ให้ใช้ Double quotes คล่อม " ] }, { "cell_type": "code", "execution_count": 150, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "\"'Yes,' he said. \"" ] }, "execution_count": 150, "metadata": {}, "output_type": "execute_result" } ], "source": [ "\"'Yes,' he said. \"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "แต่ถ้าเป็นข้อความมีทั้ง Double quotes และ Single quote หรือเป็นประโยคยาวๆ การใช้รหัสพิเศษ ```\\``` เข้ามาช่วย ก็จะช่วยทำให้โค้ดอ่านได้ง่ายขึ้นเยอะทีเดียว\n" ] }, { "cell_type": "code", "execution_count": 151, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'\"It isn\\'t\", he said.'" ] }, "execution_count": 151, "metadata": {}, "output_type": "execute_result" } ], "source": [ "'\"It isn\\'t\", he said.'" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "นอกจากนี้ \n", "ยังมีรหัสพิเศษ (Escape Sequences) อื่นๆ อีก เช่น ```\\n``` คือ **n**ewline (ขึ้นบรรทัดใหม่)" ] }, { "cell_type": "code", "execution_count": 152, "metadata": {}, "outputs": [], "source": [ "s = 'First line.\\nSecond line.' " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "ฟังก์ชั่น ```print()``` เป็นฟังก์ชั่นที่ใช้สร้างสตริงและแสดงข้อมูลสตริงออกทางจอภาพ สามารถใช้ได้กับทั้งสตริงและตัวเลข\n", "\n", "รายละเอียดดูใน [[python.org > tutotial > Input and Output]](https://docs.python.org/3/tutorial/inputoutput.html)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "ถ้าเราไม่ใช้คำสั่ง print() เอาต์พุตที่ได้จะมีรหัสพิเศษ ```\\n``` รวมอยู่ในข้อความ" ] }, { "cell_type": "code", "execution_count": 153, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'First line.\\nSecond line.'" ] }, "execution_count": 153, "metadata": {}, "output_type": "execute_result" } ], "source": [ "s" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "ถ้าใช้คำสั่ง print() ```\\n``` จะขึ้นบรรทัดใหม่" ] }, { "cell_type": "code", "execution_count": 154, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "First line.\n", "Second line.\n" ] } ], "source": [ "print(s) " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "ยกตัวอย่างในกรณีของ Path directory เช่น ```C:\\some\\name``` \n", "\n", "ถ้าเราเขียนโค้ดแบบนนี้ จะแสดงข้อความเป็น ..." ] }, { "cell_type": "code", "execution_count": 155, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "C:\\some\n", "ame\n" ] } ], "source": [ "print('C:\\some\\name') " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "เนื่องจาก ```\\n``` เป็นการขึ้นบรรทัดใหม่ ฉะนั้น ในกรณีนี้ ต้องเขียนเป็นรหัสพิเศษ ```\\\\n```" ] }, { "cell_type": "code", "execution_count": 156, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "C:\\some\\name\n" ] } ], "source": [ "print('C:\\some\\\\name') " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "หรือจะใช้ตัวอักษร ```r``` ก่อนหน้าเครื่องหมาย Single quotes หรือ Double quotes ก็ได้\n" ] }, { "cell_type": "code", "execution_count": 157, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "C:\\some\\name\n" ] } ], "source": [ "print(r'C:\\some\\name') " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "ณ ที่นี้ **r** ใช้ในการกำหนดค่าแบบ \"**r**aw string\" ซึ่งคือ การกำหนดค่าแบบที่เป็นข้อความที่ไม่มีการตัดคำออกจากข้อความ" ] }, { "cell_type": "code", "execution_count": 158, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'C:\\\\temp\\\\parts'" ] }, "execution_count": 158, "metadata": {}, "output_type": "execute_result" } ], "source": [ "dirname = r'C:\\temp\\parts'\n", "dirname" ] }, { "cell_type": "code", "execution_count": 159, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "C:\\temp\\parts\n" ] } ], "source": [ "print(dirname)" ] }, { "cell_type": "code", "execution_count": 160, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "C:\\temp\\parts\n" ] } ], "source": [ "print('C:\\\\temp\\\\parts')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### สตริงหลายบรรทัด (โดยใช้ Triple-quotes)\n", "\n", "สตริงสามารถมีหลายบรรทัดได้ วิธีการหนึ่งคือการใช้ triple-quotes: ```\"\"\"...\"\"\"``` หรือ ```'''...'''```." ] }, { "cell_type": "code", "execution_count": 161, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'\\nเวลาคือเงิน\\nTime is money\\nTime is ฿\\n'" ] }, "execution_count": 161, "metadata": {}, "output_type": "execute_result" } ], "source": [ "'''\n", "เวลาคือเงิน\n", "Time is money\n", "Time is ฿\n", "'''" ] }, { "cell_type": "code", "execution_count": 162, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "เวลาคือเงิน\n", "Time is money\n", "Time is ฿\n", "\n" ] } ], "source": [ "print('\\nเวลาคือเงิน\\nTime is money\\nTime is ฿\\n')" ] }, { "cell_type": "code", "execution_count": 163, "metadata": { "tags": [] }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "\"เวลาคือเงิน\"\n", "Time is money\n", "Time is ฿'\n", "\n" ] } ], "source": [ "triple_double_quoted = \"\"\"\n", "\"เวลาคือเงิน\"\n", "Time is money\n", "Time is ฿'\n", "\"\"\"\n", "print(triple_double_quoted)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### การเชื่อมและการก็อปปี้สตริง (ด้วยเครื่องหมาย +, *)\n", "\n", "สตริงสามารถต่อกัน (ติดกาวเข้าด้วยกัน) ด้วยตัวดำเนินการ ```+``` และสามารถทำซ้ำ (ก็อปปี้) ด้วยตัวดำเนินการ ```*```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " \n", "ยกตัวอย่างเช่น '(^_^)' (Joyful face) 3 ครั้ง ต่อท้ายด้วย '(>_<)' (Troubled face)" ] }, { "cell_type": "code", "execution_count": 164, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'(^_^)(^_^)(^_^)(>_<)'" ] }, "execution_count": 164, "metadata": {}, "output_type": "execute_result" } ], "source": [ "3 * '(^_^)' + '(>_<)'" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "ถ้าสตริงตั้งแต่สองตัวขึ้นไป อยู่ในบรรทัดเดียวกัน จะถูกเชื่อมติดกันโดยอัตโนมัติ" ] }, { "cell_type": "code", "execution_count": 165, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Python'" ] }, "execution_count": 165, "metadata": {}, "output_type": "execute_result" } ], "source": [ "'Py' 'thon' " ] }, { "cell_type": "code", "execution_count": 166, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Python\n" ] } ], "source": [ "print('Py' 'thon')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## [Exercise]: สตริง" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "```1.``` จงเขียนโด้ดแสดงผลลัพธ์ให้เป็นรูปสามเหลี่ยมแบบนี้ (ระหว่าง * ในบรรทัดเดียวกัน ไม่มีช่องว่าง)\n", "\n", "$$\n", "*\\\\\n", "***\\\\\n", "*****\\\\\n", "*******\\\\\n", "*********\\\\\n", "***********\\\\\n", "$$" ] }, { "cell_type": "code", "execution_count": 167, "metadata": {}, "outputs": [], "source": [ "# เขียนโค้ดด้านล่าง แล้วกด Shift+Enter\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "```2.``` จงเขียนโด้ดเพื่อแสดงผลลัพธ์ต่อไปนี้ โดยใช้คำสั่ง ```print```\n", "\n", "$$ \"I\\ think\\ it's\\ sad\\ if\\ it\\ isn't,\"\\ he\\ said.$$\n" ] }, { "cell_type": "code", "execution_count": 168, "metadata": {}, "outputs": [], "source": [ "# เขียนโค้ดด้านล่าง แล้วกด Shift+Enter\n" ] }, { "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", "| 05-05-2022 | 0.2 | Fix the typo, minor change |\n", "| | | |\n", "| | | |\n" ] } ], "metadata": { "author": "me", "colab": { "collapsed_sections": [ "77G0KQCTPCfv" ], "name": "Ch1_1-1_Write_your_first_python_code.ipynb", "provenance": [] }, "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": "195.675px" }, "toc_section_display": false, "toc_window_display": true }, "vscode": { "interpreter": { "hash": "e921dbf9f2d20a8528fa054ff97aae3eb23f1abc9a6f29b7bcee4307a5b88bad" } } }, "nbformat": 4, "nbformat_minor": 4 }