Python 3 · ភាសាខ្មែរ

Python
ពីចំនុចចាប់ផ្តើមដល់ Expert

មេរៀន Python ជាភាសាខ្មែរ — Variables, OOP, Decorators, Generators, Async, Data Science Libraries
Beginner → Advanced Data Science OOP Async / Generators
22+មេរៀន
3កម្រឹត
80+ឧទាហរណ៍
100%ខ្មែរ
🟢 កម្រឹតចាប់ផ្តើម — Beginner
01

Python ទិដ្ឋភាពទូទៅ & Program ដំបូង

What is Python · Why Python · Installation · Hello World

Beginner

Python គឺជាភាសា Programming High-Level ដែលបង្កើតដោយ Guido van Rossum ឆ្នាំ ១៩៩១។ Python ពេញនិយមណាស់ ពីព្រោះ Syntax ងាយ Code តិច ហើយ Powerful.

Python ប្រើក្នុង:

  • Web Development — Django, Flask, FastAPI
  • Data Science & AI — NumPy, Pandas, TensorFlow, PyTorch
  • Automation / Scripting — Task Automation
  • Cybersecurity — Penetration Testing
  • Game Development — Pygame
hello.py
# Python Program ដំបូងបំផុត
print("Hello, World! 🐍")
print("សួស្តី ពិភពលោក!")

# Python គ្មាន Semicolon គ្មាន {} Braces
# Indentation (ចន្លោះ) = Structure

name = "វណ្ណា"
age  = 20
print(f"ឈ្មោះ: {name}, អាយុ: {age}")

# Multi-line Comment
"""
នេះជា Docstring / Multi-line Comment
ប្រើពណ៌នា Function ឬ Module
"""
Hello, World! 🐍
សួស្តី ពិភពលោក!
ឈ្មោះ: វណ្ណា, អាយុ: 20
🐍
Python ប្រើ Indentation (ចន្លោះ 4 Space ឬ Tab) ជំនួស {} Braces — ការដាក់ Indentation ខុស = Error!
02

Variables & Data Types

Dynamic Typing · int · float · str · bool · None · type()

Beginner

Python ជា Dynamically Typed — មិនចាំបាច់ប្រកាស Type ទេ Python ស្វែងរក Type ដោយស្វ័យប្រវត្តិ!

Typeន័យឧទាហរណ៍type()
intចំនួនគត់x = 42<class 'int'>
floatចំនួនទស្សភាគf = 3.14<class 'float'>
strខ្សែអក្សរs = "Hello"<class 'str'>
boolTrue/Falseb = True<class 'bool'>
Noneគ្មានតម្លៃn = None<class 'NoneType'>
complexចំនួន Complexc = 2+3j<class 'complex'>
variables.py
# Dynamic Typing
x = 42           # int
x = "hello"    # ផ្លាស់ Type បានដោយ Python!
x = 3.14        # float

# Multiple Assignment
a, b, c = 1, 2, 3
name, age = "វណ្ណា", 20

# Swap variables
a, b = b, a         # Python magic!

# Constants (convention = UPPERCASE)
PI      = 3.14159265
MAX_AGE = 120

# Type checking
print(type(42))          # <class 'int'>
print(type("hello"))     # <class 'str'>
print(isinstance(42, int)) # True

# Type Conversion
print(int("100"))     # 100
print(float("3.14"))  # 3.14
print(str(42))        # "42"
print(bool(0))        # False (0, "", None, [] = Falsy)
03

Operators

Arithmetic · Comparison · Logical · Bitwise · Walrus (:=)

Beginner
operators.py
# Arithmetic
print(10 + 3)     # 13
print(10 - 3)     # 7
print(10 * 3)     # 30
print(10 / 3)     # 3.3333 (Float division)
print(10 // 3)    # 3 (Floor division)
print(10 % 3)     # 1 (Modulo)
print(2 ** 10)    # 1024 (Exponent — Python ពិសេស!)

# Comparison → ត្រឡប់ Boolean
print(5 == 5)     # True
print(5 != 3)     # True
print(1 < 2 < 3)  # True (Chained comparison!)

# Logical
print(True and False)  # False
print(True or False)   # True
print(not True)         # False

# Identity & Membership
x = [1, 2, 3]
print(2 in x)         # True
print(5 not in x)     # True
y = x
print(x is y)          # True (ចង្អុលទៅ Object ដូចគ្នា)

# Walrus Operator := (Python 3.8+)
nums = [1,2,3,4,5]
if (n := len(nums)) > 3:
    print(f"List ធំ: {n} items")  # List ធំ: 5 items
04

Input / Output & String Formatting

input() · print() · f-strings · format() · sep · end

Beginner
io_format.py
# INPUT — ទទួល String ជានិច្ច
name  = input("ឈ្មោះ: ")
age   = int(input("អាយុ: "))   # Convert to int
score = float(input("GPA: "))

# OUTPUT Methods

# 1. f-string (Python 3.6+) — BEST ✅
print(f"ឈ្មោះ: {name} | អាយុ: {age}")
print(f"GPA: {score:.2f}")          # 2 decimal places
print(f"{name:>10}")               # Right align 10 chars
print(f"{age:04d}")                 # Zero padded: 0020
print(f"{1_000_000:,}")            # 1,000,000 (commas)

# 2. .format()
print("{} មានអាយុ {}".format(name, age))

# 3. print() options
print("a", "b", "c", sep="-")     # a-b-c
print("Hello", end=" | ")
print("World")                      # Hello | World

# Multi-line input parsing
data = input().split()           # "1 2 3" → ["1","2","3"]
nums = list(map(int, data))       # ["1","2","3"] → [1,2,3]
05

Control Flow — if / elif / else / match

Conditional Statements · Ternary · match-case (Python 3.10+)

Beginner
control_flow.py
# if / elif / else
score = 85

if score >= 90:
    print("ថ្នាក់ A ★")
elif score >= 80:
    print("ថ្នាក់ B")
elif score >= 70:
    print("ថ្នាក់ C")
else:
    print("ថ្នាក់ F")

# Ternary (One-liner if-else)
result = "ជាប់" if score >= 50 else "ធ្លាក់"
print(result)  # ជាប់

# Truthy / Falsy values
if []:         # Empty list = Falsy
    print("List")
if "hello":  # Non-empty string = Truthy
    print("String")  # String

# match-case (Python 3.10+) — like switch
day = 3
match day:
    case 1:  print("ចន្ទ")
    case 2:  print("អង្គារ")
    case 3:  print("ពុធ")
    case 6 | 7: print("ថ្ងៃឈប់")
    case _:  print("ថ្ងៃផ្សេង")
ថ្នាក់ B
ជាប់
String
ពុធ
06

Loops — for / while

for · while · range() · enumerate() · zip() · break · continue · else

Beginner
loops.py
# for loop + range()
for i in range(5):               # 0,1,2,3,4
    print(i, end=" ")
print()

for i in range(1, 10, 2):       # 1,3,5,7,9 (step=2)
    print(i, end=" ")

# Iterate over List
fruits = ["ប៉ោម", "ស្វាយ", "ក្រូច"]
for fruit in fruits:
    print(f"🍎 {fruit}")

# enumerate() — index + value
for i, fruit in enumerate(fruits, start=1):
    print(f"{i}. {fruit}")

# zip() — loop 2 lists together
names  = ["វណ្ណា", "សុភា", "ដារ៉ា"]
scores = [95, 87, 92]
for name, sc in zip(names, scores):
    print(f"{name}: {sc}")

# while loop
n = 1
while n <= 5:
    print(n, end=" ")
    n += 1

# Loop else — ដំណើរការបើ loop ចប់ធម្មតា
for i in range(3):
    print(i)
else:
    print("Loop ចប់! ✓")

# Reverse iteration
for x in reversed([1,2,3]):
    print(x, end=" ")  # 3 2 1
07

Functions

def · args · kwargs · *args · **kwargs · Default Params · Recursion

Beginner
functions.py
# Basic Function
def greet(name):
    """ស្វាគមន៍អ្នកប្រើ"""
    print(f"សួស្តី, {name}! 👋")

# Default Parameters
def power(base, exp=2):
    return base ** exp

print(power(3))    # 9 (3²)
print(power(2, 10))  # 1024

# *args — Variable positional arguments
def total(*nums):
    return sum(nums)

print(total(1,2,3))          # 6
print(total(10,20,30,40))   # 100

# **kwargs — Variable keyword arguments
def profile(**info):
    for k, v in info.items():
        print(f"  {k}: {v}")

profile(name="វណ្ណា", age=20, city="ភ្នំពេញ")

# Multiple Return Values
def min_max(nums):
    return min(nums), max(nums)

lo, hi = min_max([3,1,9,4,7])
print(f"Min={lo}, Max={hi}")   # Min=1, Max=9

# Recursion — Fibonacci
def fib(n):
    if n <= 1: return n
    return fib(n-1) + fib(n-2)

print([fib(i) for i in range(8)])  # [0,1,1,2,3,5,8,13]
🟡 កម្រឹតមធ្យម — Intermediate
08

Lists & Tuples

List Methods · Slicing · Sorting · Tuple Unpacking · Named Tuples

Inter
lists_tuples.py
# ===== LIST ===== (Mutable)
nums = [5, 2, 8, 1, 9, 3]

# Slicing [start:stop:step]
print(nums[1:4])        # [2, 8, 1]
print(nums[::-1])       # Reverse: [3,9,1,8,2,5]
print(nums[:3])         # First 3: [5,2,8]
print(nums[-2:])        # Last 2: [9,3]

# List Methods
nums.append(7)           # បន្ថែមចុងក្រោយ
nums.insert(0, 0)        # Insert at index 0
nums.remove(8)           # លុបតម្លៃ
popped = nums.pop()     # លុបចុងក្រោយ
nums.sort()              # Sort in-place
nums.sort(reverse=True) # Sort descending
s = sorted(nums)         # Return new sorted list

# List Operations
a = [1,2,3]; b = [4,5]
print(a + b)             # [1,2,3,4,5]
print(a * 3)             # [1,2,3,1,2,3,1,2,3]
print(len(a), sum(a), min(a), max(a))

# ===== TUPLE ===== (Immutable)
point = (10, 20)
x, y = point             # Unpacking

colors = ("red", "green", "blue")
first, *rest = colors    # first="red", rest=["green","blue"]

# namedtuple
from collections import namedtuple
Point = namedtuple("Point", ["x", "y"])
p = Point(3, 4)
print(f"x={p.x}, y={p.y}")
09

Dictionaries & Sets

dict methods · defaultdict · Counter · set operations

Inter
dict_set.py
# ===== DICTIONARY ===== Key-Value
student = {
    "name": "វណ្ណា",
    "age":  20,
    "gpa":  3.8
}

# Access
print(student["name"])              # វណ្ណា
print(student.get("phone", "N/A"))  # N/A (safe)

# Modify
student["age"] = 21
student["city"] = "ភ្នំពេញ"
student.update({"grade": "A"})

# Iterate
for key, val in student.items():
    print(f"  {key}: {val}")

# Dict Comprehension
squares = {x: x**2 for x in range(6)}
print(squares)   # {0:0, 1:1, 2:4, 3:9, 4:16, 5:25}

# defaultdict & Counter
from collections import defaultdict, Counter

word_count = Counter("banana".split())
freq = Counter(["a","b","a","c","a","b"])
print(freq.most_common(2))  # [('a',3),('b',2)]

# ===== SET ===== Unique values
s1 = {1,2,3,4,5}
s2 = {4,5,6,7,8}

print(s1 & s2)   # Intersection: {4,5}
print(s1 | s2)   # Union: {1,2,3,4,5,6,7,8}
print(s1 - s2)   # Difference: {1,2,3}
print(s1 ^ s2)   # Symmetric diff: {1,2,3,6,7,8}

# Remove duplicates from list
dupes = [1,2,2,3,3,4]
unique = list(set(dupes))  # [1,2,3,4]
10

String Methods

str methods · split · join · strip · replace · find · format

Inter
strings.py
s = "  Hello Python World!  "

print(s.strip())              # ដកដកឃ្លា
print(s.upper())              # HELLO PYTHON WORLD!
print(s.lower())              # hello python world!
print(s.title())              # Hello Python World!
print(s.replace("Python", "🐍"))
print(s.find("Python"))       # 8 (index)
print(s.count("l"))            # 3
print(s.startswith("  H"))   # True
print(s.endswith("!  "))     # True
print("hello".capitalize())  # Hello
print("  py  ".center(10, "-"))  # ---  py  ---

# split & join
words = "ភ្នំពេញ,សៀមរាប,សីហនុ".split(",")
print(words)               # ['ភ្នំពេញ', 'សៀមរាប', 'សីហនុ']
print(" | ".join(words))    # ភ្នំពេញ | សៀមរាប | សីហនុ

# Check methods
print("abc123".isalnum())  # True
print("123".isdigit())     # True
print("abc".isalpha())     # True
11

List Comprehension & Generator Expressions

List · Dict · Set Comprehension · Nested · Conditional

Inter
comprehension.py
# List Comprehension — [expression for item in iterable if condition]

# Basic
squares = [x**2 for x in range(10)]
print(squares)   # [0,1,4,9,16,25,36,49,64,81]

# With condition
evens = [x for x in range(20) if x % 2 == 0]
print(evens)     # [0,2,4,...,18]

# Nested
matrix = [[i*j for j in range(1,4)] for i in range(1,4)]
print(matrix)    # [[1,2,3],[2,4,6],[3,6,9]]

# Flatten nested list
flat = [x for row in matrix for x in row]

# Ternary in comprehension
labels = ["Pass" if s >= 50 else "Fail"
          for s in [80,45,90,35,70]]
print(labels)   # ['Pass','Fail','Pass','Fail','Pass']

# Dict Comprehension
names = ["វណ្ណា","សុភា","ដារ៉ា"]
scr   = [95,87,92]
d = {n: s for n, s in zip(names, scr)}
print(d)         # {'វណ្ណា':95, 'សុភា':87, 'ដារ៉ា':92}

# Set Comprehension
unique = {x%5 for x in range(20)}  # {0,1,2,3,4}

# Generator Expression (Memory-efficient)
gen = (x**2 for x in range(1000000))  # ប្រើ Memory តិច!
print(next(gen))  # 0
12

File I/O

open · read · write · with · CSV · JSON · pathlib

Inter
file_io.py
import json, csv
from pathlib import Path

# ===== TEXT FILE =====
# Write
with open("data.txt", "w", encoding="utf-8") as f:
    f.write("វណ្ណា,20,3.8\n")
    f.write("សុភា,22,3.5\n")

# Read all lines
with open("data.txt", "r", encoding="utf-8") as f:
    lines = f.readlines()         # list of lines
    for line in lines:
        name, age, gpa = line.strip().split(",")
        print(f"{name} | {age} | {gpa}")

# ===== JSON =====
data = [{"name":"វណ្ណា","age":20},{"name":"សុភា","age":22}]

with open("students.json", "w", encoding="utf-8") as f:
    json.dump(data, f, ensure_ascii=False, indent=2)

with open("students.json") as f:
    loaded = json.load(f)

# ===== CSV =====
with open("scores.csv", "w", newline="") as f:
    writer = csv.writer(f)
    writer.writerow(["Name", "Score"])
    writer.writerows([["វណ្ណា",95],["សុភា",87]])

# ===== pathlib (Modern) =====
p = Path("data.txt")
print(p.exists(), p.suffix, p.stem)
text = p.read_text(encoding="utf-8")
13

Modules & Packages

import · from · __name__ · pip · Standard Library

Inter
modules.py
# Import Standard Library
import math
import random
import datetime
import os
from itertools import permutations, combinations

# math module
print(math.sqrt(144))          # 12.0
print(math.ceil(4.1))          # 5
print(math.floor(4.9))         # 4
print(math.factorial(5))       # 120
print(math.gcd(12, 8))         # 4

# random module
print(random.randint(1, 100))  # 1-100
print(random.choice(["a","b","c"]))
nums = list(range(10))
random.shuffle(nums)

# datetime
now = datetime.datetime.now()
print(now.strftime("%Y-%m-%d %H:%M:%S"))

# os module
print(os.getcwd())             # Current directory
files = os.listdir(".")        # List files

# Own module (utils.py)
# ---- utils.py ----
def greet(name):
    return f"Hello, {name}!"

if __name__ == "__main__":
    print("Run directly")
14

Exception Handling

try · except · else · finally · raise · Custom Exceptions

Inter
exceptions.py
# Basic try-except
try:
    x = 10 / 0
except ZeroDivisionError:
    print("❌ មិនអាចចែកនឹង 0!")

# Multiple exceptions
try:
    val = int(input("Enter number: "))
    result = 100 / val
except ValueError:
    print("❌ Error: មិនមែនជាចំនួន!")
except ZeroDivisionError:
    print("❌ Error: Division by zero!")
except Exception as e:
    print(f"❌ Error: {e}")
else:                           # No exception
    print(f"✅ Result: {result}")
finally:                        # Always runs
    print("🔁 Finally — ដំណើរការជានិច្ច")

# raise exception
def check_age(age):
    if age < 0:
        raise ValueError(f"អាយុ {age} មិនត្រឹមត្រូវ!")
    return age

# Custom Exception
class InsufficientFundsError(Exception):
    def __init__(self, amount):
        super().__init__(f"ប្រាក់ ${amount} មិនគ្រប់!")
        self.amount = amount

try:
    raise InsufficientFundsError(500)
except InsufficientFundsError as e:
    print(e)
🔴 កម្រឹតខ្ពស់ — Advanced
15

OOP — Classes & Objects

class · __init__ · self · @classmethod · @staticmethod · @property · __repr__

Advanced
oop_classes.py
class BankAccount:
    """Bank Account Class"""

    bank_name = "ABA Bank"     # Class variable

    def __init__(self, owner: str, balance: float = 0):
        self.owner   = owner
        self._balance = balance    # _ = private convention
        self._history = []

    @property
    def balance(self):            # Getter
        return self._balance

    def deposit(self, amount: float) -> None:
        if amount <= 0:
            raise ValueError("Amount must be positive")
        self._balance += amount
        self._history.append(f"+${amount}")
        return self  # Method chaining

    def withdraw(self, amount: float) -> None:
        if amount > self._balance:
            raise ValueError("ប្រាក់មិនគ្រប់!")
        self._balance -= amount
        self._history.append(f"-${amount}")

    @classmethod
    def from_dict(cls, data: dict):
        return cls(data["owner"], data["balance"])

    @staticmethod
    def validate_amount(amount):
        return amount > 0

    def __repr__(self):
        return f"BankAccount({self.owner!r}, ${self._balance:.2f})"

    def __str__(self):
        return f"[{self.owner}] Balance: ${self._balance:.2f}"

# Usage
acc = BankAccount("វណ្ណា", 500)
acc.deposit(300).deposit(200)    # Method chaining
acc.withdraw(100)
print(acc)          # [វណ្ណា] Balance: $900.00
print(repr(acc))     # BankAccount('វណ្ណា', $900.00)
print(acc.balance)   # 900.0 (@property)
16

Inheritance & Polymorphism

super() · MRO · Abstract Classes · @abstractmethod · dataclass

Advanced
inheritance.py
from abc import ABC, abstractmethod
from dataclasses import dataclass, field

# Abstract Base Class
class Shape(ABC):
    @abstractmethod
    def area(self) -> float: ...

    @abstractmethod
    def perimeter(self) -> float: ...

    def describe(self):
        print(f"{type(self).__name__} → Area:{self.area():.2f} Peri:{self.perimeter():.2f}")

import math

class Circle(Shape):
    def __init__(self, r): self.r = r
    def area(self):      return math.pi * self.r**2
    def perimeter(self): return 2 * math.pi * self.r

class Rectangle(Shape):
    def __init__(self, w, h): self.w, self.h = w, h
    def area(self):      return self.w * self.h
    def perimeter(self): return 2 * (self.w + self.h)

# Polymorphism
shapes = [Circle(5), Rectangle(4,6), Circle(3)]
for s in shapes:
    s.describe()

# @dataclass (Python 3.7+) — Auto __init__, __repr__
@dataclass
class Student:
    name:   str
    age:    int
    grades: list = field(default_factory=list)

    def average(self) -> float:
        return sum(self.grades) / len(self.grades) if self.grades else 0

s = Student("វណ្ណា", 20, [90,85,95])
print(s)              # Student(name='វណ្ណា', age=20, ...)
print(s.average())    # 90.0
17

Decorators

Function Decorators · Class Decorators · functools · @wraps · Stacking

Advanced
decorators.py
import time, functools

# ===== Decorator = Function ដែល Wraps Function ===== 
def timer(func):
    @functools.wraps(func)         # រក្សា metadata
    def wrapper(*args, **kwargs):
        start  = time.perf_counter()
        result = func(*args, **kwargs)
        end    = time.perf_counter()
        print(f"⏱ {func.__name__}: {(end-start)*1000:.2f}ms")
        return result
    return wrapper

def logger(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        print(f"📝 Calling {func.__name__}({args})")
        result = func(*args, **kwargs)
        print(f"✅ Returned: {result}")
        return result
    return wrapper

# Stacking decorators
@timer
@logger
def slow_add(a, b):
    time.sleep(0.01)
    return a + b

slow_add(3, 4)

# Parametrized Decorator
def repeat(n):
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            for _ in range(n):
                result = func(*args, **kwargs)
            return result
        return wrapper
    return decorator

@repeat(3)
def hello():
    print("Hello! 🐍")

hello()   # prints 3 times
18

Generators & Iterators

yield · Generator Functions · send() · __iter__ · __next__

Advanced
generators.py
# Generator Function — yield
def count_up(limit):
    n = 0
    while n < limit:
        yield n         # ផ្អាក ហើយ return n
        n += 1

gen = count_up(5)
print(next(gen))       # 0
print(list(gen))       # [1,2,3,4]

# Infinite Generator
def fibonacci():
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a + b

fib = fibonacci()
first10 = [next(fib) for _ in range(10)]
print(first10)   # [0,1,1,2,3,5,8,13,21,34]

# Custom Iterator Class
class Range:
    def __init__(self, start, stop, step=1):
        self.current = start
        self.stop    = stop
        self.step    = step

    def __iter__(self):
        return self

    def __next__(self):
        if self.current >= self.stop:
            raise StopIteration
        val = self.current
        self.current += self.step
        return val

for i in Range(0, 10, 2):
    print(i, end=" ")      # 0 2 4 6 8
19

Lambda & Functional Programming

lambda · map · filter · reduce · sorted · functools

Advanced
functional.py
from functools import reduce, partial, lru_cache

# Lambda — Anonymous function
square = lambda x: x**2
add    = lambda a, b: a + b
print(square(5))      # 25
print(add(3,4))       # 7

# map() — Apply function to all items
nums = [1,2,3,4,5]
sq  = list(map(lambda x: x**2, nums))
print(sq)    # [1,4,9,16,25]

# filter() — Keep matching items
even = list(filter(lambda x: x%2==0, nums))
print(even)  # [2,4]

# reduce() — Accumulate
total = reduce(lambda a,b: a+b, nums)
print(total) # 15

# sorted() with key
students = [{"name":"វណ្ណា","gpa":3.8},{"name":"សុភា","gpa":3.9}]
ranked = sorted(students, key=lambda s: s["gpa"], reverse=True)

# lru_cache — Memoization
@lru_cache(maxsize=None)
def fib(n):
    if n < 2: return n
    return fib(n-1) + fib(n-2)

print(fib(50))   # Fast! Cache saves results

# partial — Pre-fill arguments
def power(base, exp): return base**exp
square2 = partial(power, exp=2)
cube    = partial(power, exp=3)
print(square2(4))  # 16
print(cube(3))     # 27
20

Regular Expressions

re module · match · search · findall · sub · groups · patterns

Advanced
regex.py
import re

text = "ឈ្មោះ: វណ្ណា | Email: vanna@rupp.edu.kh | Tel: 012-345-678"

# re.search() — ស្វែងរក first match
m = re.search(r"[\w.+-]+@[\w-]+\.[\w.]+", text)
if m:
    print(f"Email: {m.group()}")  # vanna@rupp.edu.kh

# re.findall() — ស្វែងរក all matches
emails = re.findall(r"[\w.+-]+@[\w-]+\.[\w.]+", text)
phones = re.findall(r"\d{3}-\d{3}-\d{3}", text)
print(emails, phones)

# re.sub() — Replace
cleaned = re.sub(r"\d", "*", text)   # ជំនួស digits

# Groups
pattern = r"(\d{4})-(\d{2})-(\d{2})"
date_str = "2025-03-15"
m = re.match(pattern, date_str)
if m:
    year, month, day = m.groups()
    print(f"{year}/{month}/{day}")  # 2025/03/15

# Named Groups
pattern2 = r"(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})"
m2 = re.match(pattern2, date_str)
print(m2.group("year"))   # 2025

# Compiled pattern (reuse)
email_re = re.compile(r"[\w.+-]+@[\w-]+\.[\w.]+", re.IGNORECASE)
print(email_re.match("TEST@RUPP.EDU.KH"))  # Match!
21

Async / Await — Asynchronous Programming

asyncio · async def · await · gather · aiohttp · event loop

Advanced
async_demo.py
import asyncio, time

# Async function
async def fetch_data(name, delay):
    print(f"🔄 {name}: ចាប់ផ្ដើម...")
    await asyncio.sleep(delay)   # Non-blocking sleep
    print(f"✅ {name}: រួចរាល់!")
    return f"Data from {name}"

# Run multiple coroutines concurrently
async def main():
    start = time.time()

    # Sequential (slow)
    # await fetch_data("API-1", 2)
    # await fetch_data("API-2", 2)  # Total = 4s

    # Concurrent (fast) ✅
    results = await asyncio.gather(
        fetch_data("API-1", 2),
        fetch_data("API-2", 2),
        fetch_data("API-3", 1),
    )                              # Total ≈ 2s!

    print(f"⏱ {time.time()-start:.2f}s")
    print(results)

asyncio.run(main())

# Async Context Manager
async def download_files():
    tasks = []
    async with asyncio.TaskGroup() as tg:
        for i in range(5):
            tg.create_task(fetch_data(f"File-{i}", 0.5))
asyncio ពិសេសសម្រាប់ I/O-bound tasks — HTTP Requests, Database, File I/O។ សម្រាប់ CPU-bound tasks ប្រើ multiprocessing ជំនួស
22

Data Science Libraries

NumPy · Pandas · Matplotlib — Essential Python for Data

Advanced

Python ពិបាកចែករំលែកដោយគ្មាន Libraries ទាំង ៣ នេះ — ពួកវាជា Foundation នៃ Data Science!

data_science.py
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

# ===== NUMPY — Fast Array Operations =====
arr = np.array([1,2,3,4,5])
print(arr * 2)         # [2,4,6,8,10] Vectorized!
print(arr.mean())       # 3.0
print(arr.std())        # 1.414

matrix = np.zeros((3,3))
eye    = np.eye(3)            # Identity matrix
rand   = np.random.randn(100)  # 100 random normal

# ===== PANDAS — Data Analysis =====
df = pd.DataFrame({
    "ឈ្មោះ":  ["វណ្ណា", "សុភា", "ដារ៉ា", "ចន្ទ"],
    "ពិន្ទុ": [95, 87, 92, 78],
    "ថ្នាក់":  ["A", "B", "A", "C"]
})

print(df.head())          # Show first rows
print(df.describe())       # Statistics
print(df["ពិន្ទុ"].mean())   # 88.0

# Filter rows
top = df[df["ពិន្ទុ"] >= 90]   # ចំរាន >= 90
print(top)

# Group by
grouped = df.groupby("ថ្នាក់")["ពិន្ទុ"].mean()
print(grouped)

# Read/Write CSV
df.to_csv("students.csv", index=False)
df2 = pd.read_csv("students.csv")

# ===== MATPLOTLIB — Visualization =====
scores = df["ពិន្ទុ"].tolist()
names  = df["ឈ្មោះ"].tolist()

plt.figure(figsize=(8,5))
plt.bar(names, scores, color=["#84cc16","#2dd4bf","#60a5fa","#f87171"])
plt.title("ពិន្ទុសិស្ស", fontsize=16)
plt.xlabel("ឈ្មោះ")
plt.ylabel("ពិន្ទុ")
plt.ylim(0, 100)
plt.tight_layout()
plt.savefig("scores.png")
plt.show()
📦
ติดตั้ง Libraries: pip install numpy pandas matplotlib
NumPy — Array Mathematics | Pandas — Data Manipulation | Matplotlib — Visualization
Library ជ្រើស Conda: conda install numpy pandas matplotlib