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