Module 3a

Variables and Types, Operators, Math

วันนี้เราจะเรียนรู้ 🚀

  1. โครงสร้างของโปรแกรม Python
  2. ตัวแปร (Variables) และ ชนิดข้อมูล (Data Types)
  3. ตัวดำเนินการ (Operators)
  4. Math Module

Note

Input / Output และ f-string ต่อใน Module 3b 👉

import math

x = 16
y = 4
print(x ** 2)          # operators
print(math.sqrt(x))    # math module

Example of Python Script 🐍

โครงสร้างของโปรแกรม Python

ตัวอย่างโปรแกรม Python

# นำเข้าคำสั่งภายนอก (bring in external functions)
import datetime

print("----- Age Calculate Program -----")
# รับค่าอินพุตนำไปกำหนดค่าตัวแปร (get input, store in a variable)
yob = input("What's your year of birth? (e.g., 2004): ")

# ประมวลผล (process data using variables)
today = datetime.date.today()       # ดึงค่า วัน-เวลา ปัจจุบัน
year = today.year                   # สนใจเฉพาะ ปี ปัจจุบัน
age = year - int(yob)               # คำนวณอายุ

# แสดงผล (display output)
print("You are", age , "years old.")
print()
print("Congratulations on your first Python program.")

Variables 📦

ตัวแปร — การกำหนดชื่อให้พื้นที่ในหน่วยความจำ

ตัวแปร (Variables) คืออะไร?

  • ตัวแปร = ชื่อที่ใช้อ้างอิงพื้นที่ในหน่วยความจำ
  • ใช้เก็บข้อมูลเพื่อนำไปใช้งานภายหลัง
  • ควรตั้งชื่อให้ สอดคล้องกับข้อมูล ที่จัดเก็บ
age = 20
name = "Somchai"
gpa = 3.75
is_student = True

กฎการตั้งชื่อ Python Identifier

  • ใช้ตัวอักษร a-z, A-Z และ _ (underscore)
  • เช่น var_1 print_this_to_screen
  • ห้ามขึ้นต้นด้วยตัวเลข1variable ใช้ไม่ได้
  • ห้ามใช้เครื่องหมายพิเศษ!, @, #, $, %
  • ห้ามตั้งชื่อตรงกับ Keyword ของ Python

Warning

Case-sensitivevar กับ Var เป็นคนละตัว

Python Keywords

คำเหล่านี้ ห้ามใช้เป็นชื่อตัวแปร

import keyword
print(keyword.kwlist)
['False', 'None', 'True', 'and', 'as', 'assert', 'async',
 'await', 'break', 'class', 'continue', 'def', 'del', 'elif',
 'else', 'except', 'finally', 'for', 'from', 'global', 'if',
 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or',
 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']

Data Types 🏷️

ชนิดข้อมูลพื้นฐาน — str, int, float, bool

ชนิดข้อมูลพื้นฐาน 4 ประเภท

ชนิด คำอธิบาย ตัวอย่าง
str ข้อความ (string) 'hello', "2345"
int เลขจำนวนเต็ม 50000, 1_000_000
float เลขทศนิยม 3.14, 1.23e9
bool ค่าความจริง True, False
str1 = 'hello' # ข้อความ (string)
str2 = "2345"  # ข้อความ (string)
var1 = 50000   # จำนวนเต็ม (int)
var2 = 10/2    # จำนวนจริง (float)
var3 = 1.23e9  # จำนวนจริง (float)
var4 = False   # ค่าความจริง (boolean)

โจทย์ #1

สร้างตัวแปรชื่อ var1 เพื่อเก็บค่า ผลคูณ ของ 100 กับ 2 แล้ว แสดงผล

var1 = 100 * 2
print(var1)
200

Note

วิธีคิด

  1. สร้างตัวแปรชื่อ var1
  2. assign ค่า 100*2 ให้กับ var1
  3. แสดงผล var1 ด้วยคำสั่ง print

โจทย์ #2

สร้างตัวแปรชื่อ var2 เพื่อเก็บค่า ผลบวก ของ 1,000,000 กับ 1 แล้ว แสดงผล

var2 = 1_000_000 + 1
print(var2)
1000001

Tip

Python ใช้ _ คั่นหลักตัวเลขเพื่อให้อ่านง่ายขึ้นได้

โจทย์ #3

สร้างตัวแปรชื่อ var3 เพื่อเก็บค่าของ 10 หาร ด้วย 2 แล้ว แสดงผล

คิดก่อน: var3 จะเป็น int หรือ float?

var3 = 10 / 2
print(var3)
5.0

ได้ float ไม่ใช่ int! — การหาร / ใน Python ให้ผลเป็น float เสมอ

Note

วิธีคิด

  1. สร้างตัวแปรชื่อ var3
  2. assign ค่า 10/2 ให้กับ var3
  3. แสดงผล var3 ด้วยคำสั่ง print

โจทย์ #4

สร้างตัวแปรชื่อ s1 เพื่อเก็บข้อความ "this is a string" แล้ว แสดงผล

s1 = "this is a string"
print(s1)
this is a string

ข้อความ (String) — เครื่องหมาย Quote

ข้อความ (String) ต้องอยู่ภายใต้เครื่องหมาย quote

Quote ใช้เมื่อ ตัวอย่าง
'...' ข้อความทั่วไป 'hello'
"..." มี apostrophe ในข้อความ "isn't"
'''...''' ข้อความหลายบรรทัด '''line1\nline2'''

โจทย์ #5

แสดงผลข้อความ this is a simple string.

คิดก่อน: ใช้คำสั่งอะไรในการแสดงผล?

print('this is a simple string.')
this is a simple string.

โจทย์ #6

แสดงผลข้อความ this isn't a simple string.

คิดก่อน: ใช้ ' ' ได้ไหม?

ใช้ไม่ได้ เพราะจะเจอ ' ตรงคำว่า isn't — ต้องใช้ "..."

print("this isn't a simple string.")
this isn't a simple string.

โจทย์ #7

แสดงผลข้อความ this is how to print "double quote" in sentence.

print('this is how to print "double quote" in sentence.')
this is how to print "double quote" in sentence.

Note

วิธีคิด

  1. เขียนข้อความ this is how to print “double quote” in sentence.
  2. ครอบประโยคด้วยเครื่องหมาย ‘…’
  3. ใช้คำสั่ง print เพื่อแสดงผล

โจทย์ #8

แสดงผลข้อความ 3 บรรทัด ดังนี้

this is another string
this is 2nd line
this is 3rd line
print('''this is another string
this is 2nd line
this is 3rd line''')

Escape Code — อักขระพิเศษ

  • ในภาษาคอมพิวเตอร์ มักมีการใช้งานอักขระพิเศษร่วมกับข้อความ (string) เพื่อให้เกิดการแสดงผลแบบต่าง ๆ เช่น การขึ้นบรรทัดใหม่ การแท็บ การลบอักขระ
  • อักขระเหล่านี้
    • ขึ้นต้นด้วย Escape Character ( \ )
    • ใช้ภายใน " ", ' ' หรือ ''' '''
  • ที่ใช้งานบ่อย ๆ ได้แก่ \n, \t
Escape Code Description
\n newline (ขึ้นบรรทัดใหม่)
\r carriage return
\t tab (แท็บ)
\v vertical tab
\b backspace
Escape Code Description
\f form feed (page feed)
\a alert (beep)
\' single quote (')
\" double quote (")
\\ backslash (\)

ตัวอย่างการใช้ Escape Code

print('This is the 1st line')
print('This is the 2nd line \nThis is the 3rd line')
print()
print('This is the 5th line \t\tand it \'is\' separated by 2 tabs')
print("This is the \"6th\" line ")
print("\\\\\\\\")    # There are 8 backslash here
This is the 1st line
This is the 2nd line 
This is the 3rd line

This is the 5th line        and it 'is' separated by 2 tabs
This is the "6th" line 
\\\\

Warning

ทำไมบรรทัดสุดท้ายถึงพิมพ์ backslash แค่ 4 ตัว แทนที่จะเป็น 8 ตัว

Dynamic Typing — ชนิดข้อมูลไม่ตายตัว

Python ไม่บังคับ ชนิดข้อมูลตายตัว (ต่างจาก C/C++, Java) ตัวแปรสามารถเปลี่ยนไปเก็บข้อมูลชนิดอื่นได้อัตโนมัติ (dynamic typing)

x = 42          # int
x = "hello"     # เปลี่ยนเป็น str ได้!
x = 3.14        # เปลี่ยนเป็น float ได้!

ตรวจสอบชนิดด้วย type()

type('Hello')   # <class 'str'>
type(1)         # <class 'int'>
type(1.234)     # <class 'float'>

ถ้าเป็นภาษาอื่น เช่น C++ เราจะต้องระบุตั้งแต่ต้นว่าจะให้ตัวแปรเก็บอะไร 😱 (static typing)

#include <string>
int x = 0;
float y = 3.14
std::string z = "hello"

พักสมอง 😄

ที่มา: xkcd #353 — “Python” (CC BY-NC 2.5)

โจทย์ #9

1.234 และ 1.23e11 เป็นข้อมูลประเภทใด?

print(type(1.234))
print(type(1.23e11))
<class 'float'>
<class 'float'>

ทั้งคู่เป็น float1.23e11 คือ \(1.23 \times 10^{11}\) (scientific notation)

โจทย์ #10

สร้างตัวแปร s2 เก็บผลบวกของ 2500 กับ 1000 แล้วแสดงค่า s2 และตรวจสอบ type

คิดก่อน: s2 จะเป็นชนิดใด?

s2 = 2500 + 1000
print(s2, type(s2))
3500 <class 'int'>

int + intint

โจทย์ #11

ต่อจากข้อก่อน — หาค่า s2 หารด้วย 2 แล้วเก็บกลับใน s2

คิดก่อน: s2 จะเป็นชนิดใด?

s2 = s2 / 2
print(s2, type(s2))
1750.0 <class 'float'>

การหาร / ได้ float เสมอ! แม้หารลงตัว

โจทย์ #12

สร้างตัวแปร s3 เก็บผลบวกของข้อความ 'hello' กับ 'there' (เว้นวรรคด้วย)

คิดก่อน: s3 จะเป็นชนิดใด?

s3 = 'hello' + ' ' + 'there'
print(s3, type(s3))
hello there <class 'str'>

string + string = concatenation (นำข้อความมาต่อกัน)

โจทย์ #13: ชวนคิด

ทดลองหาผลบวกของ s3 (string) กับ 1 (int)

คิดว่าบวกกันได้ไหม?

s3 + 1
TypeError: can only concatenate str (not "int") to str

Important

string + number ไม่ได้! ต้องแปลงชนิดข้อมูลให้ตรงกันก่อน

Type Conversions 🔄

การเปลี่ยนชนิดข้อมูล — int(), float(), str()

ฟังก์ชันแปลงชนิดข้อมูล

ฟังก์ชัน แปลงเป็น
int() จำนวนเต็ม
float() ทศนิยม
str() ข้อความ
bool() True/False
c = float('30.5')    # 30.5
d = int('100')       # 100
e = str(42)          # '42'
f = float(7)         # 7.0
g = int(9.99)        # 9 (ตัดทศนิยมทิ้ง)

Note

Automatic conversion: int + float → Python แปลง int เป็น float ให้อัตโนมัติ

โจทย์ #14

99 (int) + 1.23 (float) → ผลลัพธ์เป็น type อะไร?

print(type(99), type(1.23))
print(type(99 + 1.23))
<class 'int'> <class 'float'>
<class 'float'>

int + floatfloat อัตโนมัติ

Note

แล้ว 4 กับ 4.00 เป็น type เดียวกันหรือไม่🤔

โจทย์ #15

หาผลบวกของ 42 กับ 3.5 แล้วเก็บเป็น integer ในตัวแปร i

i = int(42 + 3.5)
print(i, type(i))
45 <class 'int'>

int() ตัดทศนิยมทิ้ง (ไม่ใช่ปัดเศษ) — int(45.5)45

โจทย์ #16

แปลงตัวแปร i จาก integer ให้เป็น float

f = float(i)
print(f, type(f))
45.0 <class 'float'>

โจทย์ #17

กำหนด s = '1234' (string) — แปลงเป็น integer แล้วแสดงผล

s = '1234'
i = int(s)
print(int(i), type(i))
1234 <class 'int'>

โจทย์ #18

กำหนด str1 = '1234.50' — หาผลบวกของ str1 กับ 1000 เก็บในตัวแปร x

ลองคิด: จะแปลง str1 เป็น int หรือ float ดี?

str1 = '1234.50'
x = float(str1) + 1000
print(x, type(x))
2234.5 <class 'float'>

Warning

int('1234.50')error! เพราะมีจุดทศนิยม ต้องใช้ float()

โจทย์ #19: ชวนคิด

แปลง string 'Hello' เป็น integer ได้หรือไม่?

int('Hello')
ValueError: invalid literal for int() with base 10: 'Hello'

Important

ข้อความที่ ไม่ใช่รูปแบบตัวเลข แปลงเป็น number ไม่ได้ → ValueError

Operators ➕

ตัวดำเนินการ — Arithmetic, Comparison, Logical, Assignment

Operator คืออะไร?

  • Operator คือสัญลักษณ์ที่แทนการคำนวณต่าง ๆ
  • ข้อมูลที่ operator ใช้ในการคำนวณเรียกว่า operand
2 + 3
5
  • เครื่องหมาย + คือ operator สำหรับการบวก
  • ตัวเลข 2 และ 3 คือ operand และ 5 คือ ผลลัพธ์

เลือกใช้ Operator ให้สอดคล้องกับชนิดข้อมูล

  • number + number → ได้ตามหลักคณิตศาสตร์
  • string + string → นำข้อความมา เรียงต่อกัน (concatenation)
  • string + numberไม่ได้! จะเกิด TypeError

Arithmetic Operators

กำหนด x = 16, y = 4

Operator ความหมาย ผลลัพธ์
x + y บวก 20
x - y ลบ 12
x * y คูณ 64
x / y หาร (ได้ float เสมอ) 4.0
x // y หารปัดเศษทิ้ง (floor division) 4
x % y เศษของการหาร (modulus) 0
x ** y ยกกำลัง 65536

โจทย์ #20

แบ่งคนในห้อง 85 คน ออกเป็น 7 กลุ่ม — เหลือเศษกี่คน?

people = 85
group = 7
r = people % group
print('The number of remaining students =', r)
The number of remaining students = 1

โจทย์ #21

แบ่งคนในห้อง 85 คน เป็นกลุ่มละ 12 คน — ได้กี่กลุ่มที่มีสมาชิกครบ?

people = 85
member = 12
g = people // member
print('The number of groups =', g)
The number of groups = 7

โจทย์ #22

คำนวณ \(x^y\) เมื่อ \(x = 33\), \(y = 1.5\)

x = 33
y = 1.5
expo = x ** y
print('x^y =', expo)
x^y = 189.63109108996087

Tip

ทศนิยมเยอะไปไหม ถ้าต้องการทศนิยม 2 ตำแหน่งล่ะ🤔 ทำแบบนี้เลย…

print(f'x^y = {expo:.2f}')

อยากรู้เพิ่ม 👉 ดูที่หัวข้อ f-string

Comparison Operators

ให้ผลลัพธ์เป็น True หรือ False — กำหนด x = 10, y = 12

Expression ผลลัพธ์
x > y False
x < y True
x >= y False
x <= y True
Expression ผลลัพธ์
x == y False
x != y True

Warning

== เปรียบเทียบ = กำหนดค่า (assign) อย่าสับสน!

Note

True กับ False เป็นข้อมูล type ไหน🤔

โจทย์ #23

กำหนด x=10, y=12 — ประโยค x > y และ x < y เป็นจริงหรือเท็จ? และเป็น type ไหน

x = 10
y = 12
print('x > y is', x > y)
print('x < y is', x < y)
print('x > y is of type', type(x > y))
print('x < y is of type', type(x < y))
x > y is False
x < y is True
x > y is of type <class 'bool'>
x < y is of type <class 'bool'>

โจทย์ #24

จากข้อก่อน — จะตรวจสอบว่า

  • x เท่ากับ y หรือไม่?
  • x ไม่เท่ากับ y หรือไม่?
z = (x == y)
print('"x is equal to y" is', z)

z = (x != y)
print('"x is not equal to y" is', z)
"x is equal to y" is False
"x is not equal to y" is True

Note

ผลของ comparison operator ได้ตรรกะ True หรือ False แสดงว่าต้องมี operator ที่ใช้กระทำทางตรรกะแน่ ๆ เลย (👉 ดูหน้าต่อไป)

Logical Operators

ใช้รวมเงื่อนไขหลายตัวเข้าด้วยกัน

  • and — ทั้งคู่ต้อง True
  • or — แค่ตัวใดตัวหนึ่ง True
  • not — กลับค่า

Note

👉 ใน Module 3 เราเจอ Logical Operators แค่นิดเดียว — แต่จะได้ใช้งานจริงจังมากใน Module 5 (if) และ Module 6 (while loop) ตอนสร้าง เงื่อนไข control flow 🔀

โจทย์ #25

กำหนด x = True, y = False — หาค่า x and y, x or y, not y

x = True
y = False
print('x and y is', x and y)
print('x or y is', x or y)
print('not y is', not y)
x and y is False
x or y is True
not y is True

Assignment Operators

แบบพื้นฐาน — กำหนดค่า (=) 📌

x = 10        # assign

ตัวย่อ — assign + คำนวณในตัวเดียว ⚡

ตัวย่อ เทียบเท่ากับ ผลลัพธ์ (คิดจาก x = 10)
x += 5 x = x + 5 x = 15
x -= 3 x = x - 3 x = 7
x *= 2 x = x * 2 x = 20
x /= 4 x = x / 4 x = 2.5
x **= 2 x = x ** 2 x = 100
x //= 4 x = x // 4 x = 2
x %= 3 x = x % 3 x = 1

ตัวย่อช่วยให้เขียนสั้นลง 👉 x += 5 มีความหมายเหมือน x = x + 5

อ่านว่า: “เอาค่า x เดิม มาบวก 5 แล้วเก็บกลับเข้า x

ดังนั้นต้องมี x = 10 (กำหนดค่าเริ่มต้น) มาก่อนเสมอ ไม่งั้นจะไม่มีค่าเดิมให้บวกเพิ่ม

Operator Precedence (ลำดับความสำคัญ)

ลำดับจาก สูงสุด → ต่ำสุด

Operators Description Associativity (การจับคู่)
() Parentheses
** Exponentiation (raise to the power) ขวา → ซ้าย
+x, -x, ~x Unary plus, Unary minus, Bitwise NOT ขวา → ซ้าย
*, /, //, % Multiplication, Division, Floor division, Modulus ซ้าย → ขวา
+, - Addition, subtraction ซ้าย → ขวา
<<, >> Bitwise shift operators ซ้าย → ขวา
& Bitwise AND ซ้าย → ขวา
^, \| Bitwise XOR and OR ซ้าย → ขวา
>, >=, <, <= Comparison operators ซ้าย → ขวา
==, != Equality operators ซ้าย → ขวา
=, +=, -=, *=, **=, /=, //= Assignment operators ขวา → ซ้าย
is, is not Identity operators ซ้าย → ขวา
in, not in Membership operators ซ้าย → ขวา
not, or, and Logical operators ซ้าย → ขวา

โจทย์ #26

กำหนด \(a=20, b=10, c=15, d=5\)คำนวณในใจก่อน

  1. a + b * c / d = ?
  2. (a + b) * c / d = ?
  3. a + b * (c / d) = ?
  4. a + (b * c) / d = ?
  1. 20 + (10×15/5) = 50.0
    1. × 15 / 5 = 90.0
  2. 20 + 10×(15/5) = 50.0
  3. 20 + (150/5) = 50.0

Tip

ใส่ () ให้ชัดเจน ดีกว่าท่องลำดับ! แต่ถ้าไม่มีวงเล็บ ก็ควรจะเข้าใจได้!

โจทย์ #27

กำหนด \(y = -3x - \dfrac{2}{10^2}\) — จงหา \(y\) เมื่อ \(x = 5\)

วิธีคิด

  1. assign ค่าให้ตัวแปร x
  2. assign ค่าให้ตัวแปร y
  3. แสดงผลคำนวณด้วยคำสั่ง ด้วย print()

จากวิธีคิดข้างบน ถ้าสลับขั้นที่ 1. กับ 2. จะมีผลกับการรันโค้ดยังไง?

x = 5
y = -3*x - 2/10**2
print(y)
-15.02

Warning

ต้อง assign ค่า x ก่อน y เสมอ!

ถ้าสลับบรรทัด → NameError: name 'x' is not defined

Math Module 🧮

ชุดคำสั่งคณิตศาสตร์ — import math

math module — ภาพรวม

  • การคำนวณทางคณิตศาสตร์ที่ซับซ้อนทำได้ยากด้วย operator พื้นฐาน
  • Python เตรียมชุดคำสั่ง (หรือฟังก์ชัน) ในการคำนวณที่จำเป็นทางคณิตศาสตร์เพิ่มเติมให้ผู้พัฒนาโปรแกรมได้เรียกใช้งาน
  • คำสั่งเหล่านี้ถูกจัดเตรียมรวมกันไว้ในโมดูล (module) ที่ชื่อว่า math
  • ก่อนจะใช้งานคำสั่งเหล่านี้เราต้อง import โมดูลเข้าสู่โปรแกรมเสียก่อน
import math

Note

ในการทำงานจริง เรา import module เข้ามาเพียงครั้งเดียวก็สามารถใช้งานต่อได้ ไม่จำเป็นต้อง import ทุกครั้ง

math — ฟังก์ชันและค่าคงที่

ฟังก์ชัน

  • math.sqrt(x)\(\sqrt{x}\)
  • math.sin(x), cos(x), tan(x)
  • math.log(x), log2(x), log10(x)
  • math.factorial(n)\(n!\)
  • math.ceil(x) — ปัดขึ้น
  • math.floor(x) — ปัดลง

ค่าคงที่

  • math.pi\(\pi = 3.14159...\)
  • math.e\(e = 2.71828...\)

แปลงมุม

  • math.degrees(rad) — rad → degree
  • math.radians(deg) — degree → rad

โจทย์ #28

คำนวณ \(\sqrt{25}\) — ทำได้กี่วิธี?

import math
# วิธีที่ 1
print(math.sqrt(25))
# วิธีที่ 2
print(25 ** 0.5)
# วิธีที่ 3
print(math.pow(25, 0.5))
5.0
5.0
5.0

โจทย์ #29

คำนวณพื้นที่วงกลมที่มีรัศมี 10 หน่วย

\[area = \pi r^2\]

import math
r = 10
area = math.pi * r**2
print('Area of the circle =', area)
Area of the circle = 314.1592653589793

โจทย์ #30

แปลงมุม 2 radian เป็นหน่วย องศา (degree)

import math
print(math.degrees(2))
114.59155902616465

โจทย์ #31

แปลงมุม 60 องศา เป็นหน่วย radian

print(math.radians(60))
1.0471975511965976

โจทย์ #32

ให้คำนวณค่าของ ① \(\sin\) ของมุมขนาด 30 เรเดียน, ② \(\cos\) ของมุมขนาด 60 องศา

print(math.sin(30))
print(math.cos(math.radians(60)))
-0.9880316240928618
0.5000000000000001

\(\cos(60°)\) — มุมเป็นองศา ต้องแปลงเป็น radian ก่อน!

Warning

sin, cos, tan รับค่าเป็น radian เสมอ!

ตัวอย่าง math เพิ่มเติม

Factorial\(4! = 1 \times 2 \times 3 \times 4\)

print(math.factorial(4))
24

Rounding — ปัดขึ้น / ปัดลง

print(math.ceil(5.23))
print(math.floor(5.99))
6
5

Summary 🎯

สรุป Module 3a 🎉

ตัวแปรและชนิดข้อมูล

  • str, int, float, bool
  • ตรวจสอบด้วย type()
  • แปลงด้วย int(), float(), str()

Operators

  • Arithmetic: + - * / // % **
  • Comparison: > < == !=
  • Logical: and or not
  • Assignment: = += -=

Math Module

  • import math
  • sqrt, sin, cos, pi, …
  • ceil, floor, factorial

Note

ต่อ Module 3b: Input / Output และ f-string 👉