สำหรับวันนี้มา Recap live Class เรื่อง Python ครับ โดยวันนี้แอดสอน 5 เรื่องครับ ผมจดมาตามนี้ครับ
Python vs R
- R เกิดมาสำหรับ Data / Stat
- Python เป็น General Purpose เอาไปใช้งานต่างๆได้ เช่น ทำ web / data / process ข้อมูลต่างๆได้ ส่วนตัวนั่ง main ซากอารยธรรม python อยู่เหมือนกัน เลยเห็นภาพการใช้งาน
Google Colab
- เป็นเว็บไว้ให้ลองเขียน Code + Document ด้วย Mark Down ไปในตัวครับ
- ตัว Google Collab ตอนนี้รองรับหลายภาษา
- R
- Python
- Julia สำหรับงาน High Performance ผมเองเพิ่มเคยได้ยินเหมือนกัน เห็นเค้าตีๆกันเรื่อง Go Rust
ปกติ Run ใน vscode แก้งาน ตอนนี้ได้ลองของใหม่เป็น Web แล้ว
Variable & Data Type
📌 การประกาศตัวแปรตัวที่ได้เรียนจะมี string / integer / float / boolean
# name variable -> snake case # data type my_name = "ping" # string my_age = 34 # integer cs_gpa = 3.55 # float single = True # boolean print(my_name, my_age, cs_gpa, single)
📌 การลบตัวแปร ใช้คำสั่ง del ลบตัวแปร //เอาจริงๆ ผมเพิ่งรู้
del my_name
📌 การแปลงข้อมูล (Casting)
# Data Type Conversion # int() float() str() bools() bool(0) # False str(555) # "555" int("555") # 555 float("3.41") # 3.41
📌 การรับข้อมูล Input ใช้ input โดยจะได้ผลลัพธ์เป็น String เสมอ
# Get Input from user input("What is your age:" ) # ถ้าต้องการ Data Type อื่นๆให้แปลงข้อมูล age = int(input("What is your age:" )) print(type(age)) print(age)
📌 String Template จัดรูปแบบ String เติมตามช่องที่เว้นไว้ f"ข้อความ {ตัวแปร}"
# fstring template my_name = "Ping" my_age = 34 text = f"Hi my name is {my_name} and age is {my_age}" print(text)
Python ตัวนี้มีมานานมากแล้ว แต่ dotnet csharp เพิ่มมา 3-4 ปีนี้เอง
function
📌 แยกส่วน Code ให้ดูง่าย โดยใช้ keyword def
ประกาศ ตัวอย่าง simple function
## function def say_hello(): print("Hello!")
📌 การเรียกใช้งาน
say_hello()
📌 กรณีที่มี parameter ส่งเข้าไป
def double(x): return x * 2 double(10) # 20 double(6.5) # 13.0
📌 default argument ถ้าไม่ส่งเข้ามาใช้ค่า default
# default arg # parameter name food # argument = pizza def greeting(name, food="pizza"): text = f"Hi {name}, I like {food}" print("this is side effect") # useful for debug return text # ================================ greeting("Ping") # this is side effect # Hi Ping, I like pizza # ================================ greeting("Ping", "Chicken Rice") # this is side effect # Hi Ping, I like Chicken Rice
📌 return multiple value ใช้ turple เป็นตัวอย่างนึง แต่มีข้อแม้ว่าตัวที่ return กับตัวแปรที่มารับต้องจำนวนเท่ากัน
def greeting2T(x): return (x**2, x+2, x-2) # ================================ x, y, z = greeting2T(5) print(x, y, z) # 25 7 3 # ================================ # ถ้าไม่ต้องการใช้ ให้ใช้ _ เพื่อละไว้ เหมือนกับของ Go เลย x, y, _ = greeting2T(5)
📌 ถ้าไม่อยากให้ Return
# None pass def sampleNone(): return None # special keyword def samplePass(): pass
📌 ตัวอย่าง function ช่วยแบ่งานให้ modular ดูพวก Coupling Cohesion เพิ่มเติมได้ครับ
def f1(): print("Load") def f2(): print("Process") def f3(): print("save") # ================================ def f4(): f1() f2() f3() print("done") # ================================ # Sample Call f4()
control flow - if
📌 ตัวอย่างการใช้ if / else / elif
# control flow def grade(score): if score >= 90: return 'A' elif score >= 80: return 'B' elif score >= 70: return 'C' else: return 'Please retake exam !!!' # ================================ grade(49) # Please retake exam !!!
📌 ถ้ามีเงื่อนไขที่ซับซ้อนใช้ and / or ได้
# multiple condition # and or def testingAnd(x): if (1+x ==4 ) and (2*x == 6): print("Match") else: print("Not Match") def testingOr(x): if (1+x == 4 ) or (2*x == 6): print("Match") else: print("Not Match")
# Not not True # False not False # True
data structure
- mutable vs immutable
- mutable - can be update
- immutable - read only eg. turple / string
- List
# List = Vector in R my_shopping = ["egg", "milk", "bread"] print(my_shopping) # ================================= # Access by Index print(my_shopping[0]) print(my_shopping[1]) print(my_shopping[2]) # ================================= # update value in list my_shopping[0] = "orange" my_shopping[1] = "milk 2 gallons" print(my_shopping)
📌 นอกจากนี้ list เองมี Function
- append ต่อท้าย
my_shopping.append('apple') print(my_shopping) print(my_shopping.count) # บอก Memory Location print(len(my_shopping)) # Len เป็น General Purpose Function
- remove เอาตามที่ key ป้อนออกไป
my_shopping.remove('apple') print(my_shopping)
- pop เอาตัวท้ายสุดออกไป
my_shopping.pop()
- insert แทรกตามตำแหน่งที่ต้องการ
# insert at index my_shopping.insert(1, 'mama') print(my_shopping) # ['orange', 'mama', 'bread', 'apple', 'apple', 'apple', 'apple']
- reverse เรียงจากท้ายมาหน้า
📌 combine list
# combine list full_list = ['egg','milk'] + ['mama', 'orelo'] for item in full_list: print(item)
- Turple
📌 เหมือน List แต่แก้ไขค่าไม่ได้
# turple is imutable faster than list x = (1,2,3) print(x, type(x), x[0]) x[0] = 5 # ถ้าลองแก้ค่า มันจะ Error
# turple and List # multiple data type ["ping", True, 34, ["csharp", "vue", "sql"], ("ComSci", "SoftwareEng")]
- Set
# Set (no duplications) fruits = {'Orange', 'Orange', 'Apple'}
📌 Set เอาไว้เก็บข้อมูลที่ไม่ซ้ำ โดยมี Opertion ที่สำคัญ
- Intersect หาที่เหมือนกัน
- union เทรวม
- dfference หาที่ต่างกัน
a = {'Orange', 'Orange', 'Apple'} b = {'Banana', 'Grape', 'Orange'} print(a) # {'Orange','Apple'} # ================================= # union a | b # {'Apple', 'Banana', 'Grape', 'Orange'} # ================================= # dfference a - b {'Apple'}
- Dictionary
📌 เก็บข้อมูลในรูปแบบ Key Value โดยคล้าย json ถ้าใน R จะเป็น List
# Dictionary ## key value paire like json ## key is immutable user = { "name": "Ping", "age": 34, "location": "BKK", "Language" : ['csharp', 'vue','sql'], "steaming" : { "netlifx": True, "amazon": False } } # Access By Key user['age'] # 34 # Update By Key user['age'] = 35 # Add new Key user['gender'] = 'male' # Remove Key # - ใช้ del del user['gender'] # - ใช้ pop user.pop('gender')
Control Flow - Loop
📌 for วนตามจำนวนที่กำหนดไว้
- วนตาม Object ใน List
# list naming pruals fruits = ['apple', 'banana', 'strawberry'] for fruit in fruits: if (fruit == 'strawberry'): print(fruit.upper() + "is delicous") else: print(fruit)
- วนตาม range
for i in range(5): print("hello" , i+1)
📌 while วนจนกว่าเงื่อนไขจะเป็นเท็จ
while True: user_input = input("What do you want to eat? ") print(user_input) if (user_input == "I am full"): print("Byes!") break #or you can use bool varaible as a flag
Import Lib
📌 รูปแบบการ import
## import code from math import pi, log, exp หรือ import ตรงๆก็ได้ import random
📌 การใช้งาน
exp(5)
from random import choice choice(["ค้อน","กรรไกร", "กระดาษ"])
ปิดท้าย
📌 มีลองแปลง Code เกมเป่ายิงฉุบ จากเดิมที่ทำไว้เป็น R มาเป็น Python Version และอีกข้อ Order Pizza ครับ เป็นการบ้านครับ
📌 และถ้าสนใจเพิ่มเติมลองอ่านจาก Blog เก่าๆที่ ผมเรียนจาก MITx: 6.00.1x ที่ผมเรียนเมื่อหลายปีก่อนได้ครับ มีพวก Python 101, OOP และ Plot ครับ
[MITx: 6.00.1x] Introduction to Computer Science and Programming Using Python (Week 1)
[MITx: 6.00.1x] Introduction to Computer Science and Programming Using Python (Week 2)
[MITx: 6.00.1x] Introduction to Computer Science and Programming Using Python (Week 3)
[MITx: 6.00.1x] Introduction to Computer Science and Programming Using Python (Week 4)
[MITx: 6.00.1x] Introduction to Computer Science and Programming Using Python (Week 5)
[MITx: 6.00.1x] Introduction to Computer Science and Programming Using Python (Week 6)
[MITx: 6.00.1x] Introduction to Computer Science and Programming Using Python (Week 7)
[MITx: 6.00.1x] Introduction to Computer Science and Programming Using Python (Final Exam)
[MITx: 6.00.1x] Introduction to Computer Science and Programming Using Python
Discover more from naiwaen@DebuggingSoft
Subscribe to get the latest posts sent to your email.