ការណែនាំអំពី Python

ទិន្នន័យ/ការគណនា — Data → Calculate → Summarize → Save to file

Python 3.x VS Code 10 មេរៀន Beginner Level

ទិន្នន័យគំរូ: name, sell, cost, qty → revenue, total_cost, profit, profit_margin

1

Setup + Run Python + print() + tip: សរសេរតែ 3–5 បន្ទាត់ជាមុន

គោលបំណង

  • ដំឡើង Python 3.x និង VS Code លើម៉ាស៊ីនរបស់ខ្លួន
  • សរសេរកម្មវិធី Python ដំបូង ដោយប្រើ print()
  • យល់ពីគោលការណ៍: សរសេរតែ 3–5 បន្ទាត់ជាមុន រួចទើបបន្ថែម
  • បង្ហាញទិន្នន័យលក់ (name, sell, cost, qty) ជា text

គំនិតសំខាន់

Python ជា programming language ដែលងាយស្រួលរៀន។ រឿងដំបូង យើងរៀនប្រើ print() ដើម្បីបង្ហាញអក្សរ/លេខនៅលើអេក្រង់។ គោលការណ៍សំខាន់: សរសេរតែ 3–5 បន្ទាត់ជាមុន រួចដំណើរការ (Run) → មើលលទ្ធផល → រួចបន្ថែម។ កុំសរសេរមួយដុំធំរួចដំណើរការ ព្រោះបើខុស ពិបាករកកំហុស។

Demo Code

# មេរៀន 1: print() — បង្ហាញទិន្នន័យលក់
print("=== របាយការណ៍ទិន្នន័យលក់ ===")
print("ឈ្មោះទំនិញ: ទំនិញ A")
print("ថ្លៃលក់ (sell):", 5000)
print("ថ្លៃទិញ (cost):", 3000)
print("បរិមាណ (qty):", 10)

Output

=== របាយការណ៍ទិន្នន័យលក់ ===
ឈ្មោះទំនិញ: ទំនិញ A
ថ្លៃលក់ (sell): 5000
ថ្លៃទិញ (cost): 3000
បរិមាណ (qty): 10

លំហាត់ (Practice)

១) បង្ហាញទិន្នន័យ "ទំនិញ B" ដែល sell=8000, cost=5000, qty=5

ចម្លើយ
print("ឈ្មោះទំនិញ: ទំនិញ B")
print("ថ្លៃលក់ (sell):", 8000)
print("ថ្លៃទិញ (cost):", 5000)
print("បរិមាណ (qty):", 5)

២) សរសេរ print() ដែលបង្ហាញ "ចំណូល = ថ្លៃលក់ x បរិមាណ" ជាអក្សរ

ចម្លើយ
print("ចំណូល = ថ្លៃលក់ x បរិមាណ")
print("ចំណូល =", 5000, "x", 10, "=", 50000)

៣) ប្រើ print() បង្ហាញ 3 ទំនិញ (A, B, C) ក្នុង 3 បន្ទាត់ រួមជាមួយ sell

ចម្លើយ
print("ទំនិញ A — sell: 5000")
print("ទំនិញ B — sell: 8000")
print("ទំនិញ C — sell: 3000")

គន្លឹះ

  • សរសេរ 3 បន្ទាត់ → Run → មើលលទ្ធផល → រួចបន្ថែម។ កុំសរសេរ 20 បន្ទាត់ម្តងទេ។
  • រក្សាទុកឯកសារជា .py មុនដំណើរការ។
2

Variables + Object + Naming (ឈ្មោះអថេរ)

គោលបំណង

  • យល់ពី variable (អថេរ) ជាអ្វី និងហេតុអ្វីប្រើវា
  • ដាក់ឈ្មោះអថេរឲ្យបានច្បាស់ (snake_case)
  • រក្សាទុកទិន្នន័យលក់ក្នុងអថេរ
  • គណនាចំណូល (revenue) ពី sell និង qty

គំនិតសំខាន់

Variable គឺជា "ប្រអប់" សម្រាប់រក្សាទុកទិន្នន័យ។ ជំនួសឲ្យសរសេរលេខ 5000 រាល់កន្លែង យើងដាក់ sell = 5000 រួចប្រើ sell ជំនួស។ ការដាក់ឈ្មោះ: ប្រើ snake_case (អក្សរតូច + underscore) ដូចជា total_cost, profit_margin។ កុំដាក់ឈ្មោះ x, y ព្រោះអានមិនយល់។

Demo Code

# មេរៀន 2: Variables — រក្សាទុកទិន្នន័យក្នុងអថេរ
name = "ទំនិញ A"
sell = 5000
cost = 3000
qty = 10

# គណនាចំណូល
revenue = sell * qty
total_cost = cost * qty
profit = revenue - total_cost

print("ទំនិញ:", name)
print("ចំណូល (revenue):", revenue)
print("ចំណាយសរុប (total_cost):", total_cost)
print("ប្រាក់ចំណេញ (profit):", profit)

Output

ទំនិញ: ទំនិញ A
ចំណូល (revenue): 50000
ចំណាយសរុប (total_cost): 30000
ប្រាក់ចំណេញ (profit): 20000

លំហាត់ (Practice)

១) បង្កើតអថេរសម្រាប់ "ទំនិញ B" (sell=8000, cost=5000, qty=5) ហើយគណនា revenue និង profit

ចម្លើយ
name = "ទំនិញ B"
sell = 8000
cost = 5000
qty = 5
revenue = sell * qty     # 40000
profit = revenue - (cost * qty)  # 15000
print(name, "— profit:", profit)

២) ហេតុអ្វី tc មិនល្អ ជាង total_cost?

ចម្លើយ

ព្រោះ tc អានមិនយល់ថាជាអ្វី។ total_cost អានយល់ច្បាស់ថា "ចំណាយសរុប"។ ការដាក់ឈ្មោះល្អ ជួយឲ្យអ្នកផ្សេងយល់កូដរបស់យើង។

៣) គណនា profit_margin = (profit / revenue) * 100 សម្រាប់ទំនិញ A រួច print

ចម្លើយ
revenue = 50000
profit = 20000
profit_margin = (profit / revenue) * 100
print("Profit Margin:", profit_margin, "%")
# Output: Profit Margin: 40.0 %

គន្លឹះ

  • ដាក់ឈ្មោះអថេរជា snake_case: sell_price, total_cost, profit_margin
  • ផ្លាស់ប្ដូរតម្លៃមួយកន្លែង → លទ្ធផលផ្លាស់ប្ដូរទាំងអស់ ព្រោះយើងប្រើឈ្មោះអថេរ មិនប្រើលេខផ្ទាល់។
3

Data Types + type() + Type Conversion

គោលបំណង

  • ស្គាល់ប្រភេទទិន្នន័យ: str, int, float, bool
  • ប្រើ type() ដើម្បីពិនិត្យប្រភេទ
  • បម្លែងប្រភេទ: int(), float(), str()
  • ស្វែងយល់ហេតុអ្វី input() ផ្តល់ str → ត្រូវបម្លែងទៅ int/float

គំនិតសំខាន់

Python មានប្រភេទទិន្នន័យច្រើន។ ពេលយើងធ្វើការជាមួយទិន្នន័យលក់: name ជា str, sell/cost/qty ជា int ឬ float។ ប្រសិនបើប្រភេទខុស Python នឹង error។ ឧទាហរណ៍ "5000" + 3000 នឹង error ព្រោះ str + int មិនបាន។ ត្រូវបម្លែងមុន: int("5000") + 3000

Demo Code

# មេរៀន 3: Data Types + type() + Conversion
name = "ទំនិញ A"
sell = 5000
cost = 3000.0
qty = 10
is_available = True

# ពិនិត្យប្រភេទ
print(type(name))       # <class 'str'>
print(type(sell))       # <class 'int'>
print(type(cost))       # <class 'float'>
print(type(is_available))  # <class 'bool'>

# បម្លែងប្រភេទ (Type Conversion)
sell_text = "5000"
sell_number = int(sell_text)
revenue = sell_number * qty
print("ចំណូល:", revenue)

# float ទៅ string សម្រាប់បង្ហាញ
profit_margin = 40.0
print("Margin: " + str(profit_margin) + "%")

Output

<class 'str'>
<class 'int'>
<class 'float'>
<class 'bool'>
ចំណូល: 50000
Margin: 40.0%

លំហាត់ (Practice)

១) អថេរ qty = "10" ជាប្រភេទអ្វី? បម្លែងទៅ int ហើយគុណនឹង sell=5000

ចម្លើយ
qty = "10"         # str
print(type(qty))   # <class 'str'>
qty = int(qty)     # បម្លែងទៅ int
revenue = 5000 * qty
print("ចំណូល:", revenue)  # 50000

២) ត្រូវមានអ្វីកើតឡើងបើសរសេរ "sell: " + 5000? កែដោយរបៀបណា?

ចម្លើយ
# Error: can only concatenate str to str
# កែ: បម្លែង 5000 ទៅ str
print("sell: " + str(5000))
# ឬប្រើ comma:
print("sell:", 5000)

៣) គណនា profit_margin ជា float រួចបង្ហាញក្នុងទម្រង់ 2 ខ្ទង់ "40.00%"

ចម្លើយ
profit = 20000
revenue = 50000
profit_margin = (profit / revenue) * 100
print(f"Profit Margin: {profit_margin:.2f}%")
# Output: Profit Margin: 40.00%

គន្លឹះ

  • ប្រើ f-string: f"Margin: {profit_margin:.2f}%" សម្រាប់ format ខ្ទង់ទសភាគ។
  • ពេលអាន CSV ឬ input() — ទិន្នន័យជា str ជានិច្ច → ត្រូវបម្លែង!
4

Operators (Arithmetic / Comparison / Logical)

គោលបំណង

  • ស្គាល់ Arithmetic Operators: + - * / // % **
  • ស្គាល់ Comparison Operators: == != > < >= <=
  • ស្គាល់ Logical Operators: and or not
  • គណនាពេញលេញ: revenue, total_cost, profit, profit_margin
  • ប្រើ comparison ដើម្បីផ្ទៀងផ្ទាត់ profit > 0 ឬអត់

គំនិតសំខាន់

Operators គឺជាសញ្ញាដែលធ្វើការគណនា ឬប្រៀបធៀប។ ក្នុងទិន្នន័យលក់ យើងប្រើ * គុណ sell * qty, - ដក revenue - total_cost, / ចែក profit/revenue។ Comparison ប្រើដើម្បីពិនិត្យ: sell > cost មែនទេ? profit >= 0 មែនទេ? Logical ប្រើបញ្ចូលគ្នា: sell > 0 and qty > 0

Demo Code

# មេរៀន 4: Operators — គណនា + ប្រៀបធៀប
name = "ទំនិញ A"
sell = 5000
cost = 3000
qty = 10

# Arithmetic
revenue = sell * qty          # 50000
total_cost = cost * qty       # 30000
profit = revenue - total_cost # 20000
profit_margin = (profit / revenue) * 100  # 40.0

print(f"ទំនិញ: {name}")
print(f"ចំណូល: {revenue}")
print(f"ប្រាក់ចំណេញ: {profit}")
print(f"Margin: {profit_margin:.2f}%")

# Comparison
is_profitable = profit > 0
print(f"មានចំណេញ? {is_profitable}")    # True

# Logical
is_valid = sell > 0 and cost > 0 and qty > 0
print(f"ទិន្នន័យត្រឹមត្រូវ? {is_valid}")  # True

# ពិនិត្យ sell >= cost
if sell >= cost:
    print("ថ្លៃលក់ >= ថ្លៃទិញ ✓")
else:
    print("ថ្លៃលក់ < ថ្លៃទិញ (ខាត!)")

Output

ទំនិញ: ទំនិញ A
ចំណូល: 50000
ប្រាក់ចំណេញ: 20000
Margin: 40.00%
មានចំណេញ? True
ទិន្នន័យត្រឹមត្រូវ? True
ថ្លៃលក់ >= ថ្លៃទិញ ✓

លំហាត់ (Practice)

១) គណនា revenue, total_cost, profit, margin សម្រាប់ "ទំនិញ D" (sell=12000, cost=9000, qty=3)

ចម្លើយ
sell, cost, qty = 12000, 9000, 3
revenue = sell * qty         # 36000
total_cost = cost * qty      # 27000
profit = revenue - total_cost  # 9000
margin = (profit / revenue) * 100  # 25.0
print(f"Margin: {margin:.2f}%")  # 25.00%

២) ប្រើ comparison ពិនិត្យថា margin > 30 មែនទេ? ជា bool

ចម្លើយ
margin = 25.0
high_margin = margin > 30
print("Margin > 30%?", high_margin)  # False

៣) ប្រើ logical: ពិនិត្យថា sell > 0 and qty > 0 and cost >= 0

ចម្លើយ
sell, cost, qty = 12000, 9000, 3
is_valid = sell > 0 and qty > 0 and cost >= 0
print("Valid?", is_valid)  # True

# ករណីមិន valid
sell2, cost2, qty2 = -100, 500, 2
is_valid2 = sell2 > 0 and qty2 > 0 and cost2 >= 0
print("Valid?", is_valid2)  # False

គន្លឹះ

  • / ចែកបានលទ្ធផល float; // ចែកបានលទ្ធផល int (គ្មានខ្ទង់ទសភាគ)។
  • ប្រើ f"...{value:.2f}..." ដើម្បីបង្ហាញ 2 ខ្ទង់ទសភាគ។
5

Input + Validation (ការទទួលទិន្នន័យពីអ្នកប្រើ)

គោលបំណង

  • ប្រើ input() ទទួលទិន្នន័យពីអ្នកប្រើប្រាស់
  • បម្លែង input ទៅ int/float
  • ផ្ទៀងផ្ទាត់ (validate): ពិនិត្យថាទិន្នន័យត្រឹមត្រូវមុនគណនា
  • ប្រើ while loop ដើម្បីសួរម្តងទៀតបើទិន្នន័យខុស
  • ដោះស្រាយ error ជាមួយ try/except

គំនិតសំខាន់

input() ផ្តល់ str ជានិច្ច។ ត្រូវបម្លែងទៅ int ឬ float។ បើអ្នកប្រើវាយអក្សរជំនួសលេខ → error! ដូច្នេះយើង validate: (1) ពិនិត្យថាអាចបម្លែងបាន, (2) ពិនិត្យថាមិនមែនអវិជ្ជមាន, (3) name មិនទទេ។ ប្រើ try/except ដើម្បីចាប់ error។

Demo Code

# មេរៀន 5: Input + Validation
print("=== បញ្ចូលទិន្នន័យទំនិញ ===")

# ទទួល name — ពិនិត្យមិនទទេ
while True:
    name = input("ឈ្មោះទំនិញ: ").strip()
    if name != "":
        break
    print("កំហុស: ឈ្មោះមិនអាចទទេបានទេ!")

# ទទួលលេខ — ពិនិត្យថាជាលេខ និង >= 0
def get_positive_number(prompt):
    while True:
        try:
            value = float(input(prompt))
            if value < 0:
                print("កំហុស: តម្លៃមិនអាចអវិជ្ជមានបានទេ!")
                continue
            return value
        except ValueError:
            print("កំហុស: សូមបញ្ចូលលេខត្រឹមត្រូវ!")

sell = get_positive_number("ថ្លៃលក់ (sell): ")
cost = get_positive_number("ថ្លៃទិញ (cost): ")
qty = int(get_positive_number("បរិមាណ (qty): "))

# គណនា
revenue = sell * qty
total_cost = cost * qty
profit = revenue - total_cost
margin = (profit / revenue) * 100 if revenue > 0 else 0

print(f"\n--- លទ្ធផល ---")
print(f"ទំនិញ: {name}")
print(f"ចំណូល: {revenue:,.0f}")
print(f"ចំណេញ: {profit:,.0f}")
print(f"Margin: {margin:.2f}%")

Output (ឧទាហរណ៍)

=== បញ្ចូលទិន្នន័យទំនិញ ===
ឈ្មោះទំនិញ: ទំនិញ A
ថ្លៃលក់ (sell): 5000
ថ្លៃទិញ (cost): 3000
បរិមាណ (qty): 10

--- លទ្ធផល ---
ទំនិញ: ទំនិញ A
ចំណូល: 50,000
ចំណេញ: 20,000
Margin: 40.00%

លំហាត់ (Practice)

១) បន្ថែម validation: qty ត្រូវតែ > 0 (មិនមែន 0)

ចម្លើIf
def get_positive_qty(prompt):
    while True:
        try:
            value = int(input(prompt))
            if value <= 0:
                print("កំហុស: បរិមាណត្រូវតែ > 0!")
                continue
            return value
        except ValueError:
            print("កំហុស: សូមបញ្ចូលលេខគត់!")

២) បើ sell == cost → profit = 0។ print សារ "ដើមទុន = ថ្លៃលក់ — មិនមានចំណេញទេ"

ចម្លើយ
if sell == cost:
    print("ដើមទុន = ថ្លៃលក់ — មិនមានចំណេញទេ")
elif profit > 0:
    print(f"មានចំណេញ: {profit}")
else:
    print(f"ខាត: {profit}")

៣) ពិនិត្យថាអ្នកប្រើវាយ "abc" ជំនួសលេខ — try/except ចាប់ error

ចម្លើយ
try:
    sell = float(input("sell: "))
    print("sell =", sell)
except ValueError:
    print("កំហុស: សូមបញ្ចូលលេខ មិនមែនអក្សរ!")

គន្លឹះ

  • ប្រើ .strip() ដើម្បីដកដកឃ្លានៅខាងមុខ/ខាងក្រោយ input។
  • Validation ល្អ = កម្មវិធីមិន crash បើអ្នកប្រើវាយទិន្នន័យខុស។
6

List + for loop (ទិន្នន័យច្រើនជួរ)

គោលបំណង

  • បង្កើត list សម្រាប់ទុកទិន្នន័យច្រើន
  • ប្រើ for loop ដើរតាមធាតុនីមួយៗ
  • គណនាសរុប (total) ដោយប្រើ loop
  • ស្វែងរកតម្លៃធំជាងគេ
  • ប្រើ len(), append()

គំនិតសំខាន់

list គឺជា "បញ្ជី" ដែលផ្ទុកធាតុច្រើន។ ជំនួសឲ្យបង្កើតអថេរម្តង (sell1, sell2, sell3…) យើងដាក់ក្នុង list: sells = [5000, 8000, 3000]។ ប្រើ for loop ដើម្បីដំណើរការធាតុនីមួយៗ ដោយស្វ័យប្រវត្តិ។

Demo Code

# មេរៀន 6: List + for loop
names = ["ទំនិញ A", "ទំនិញ B", "ទំនិញ C", "ទំនិញ D", "ទំនិញ E"]
sells = [5000, 8000, 3000, 12000, 6000]
costs = [3000, 5000, 2500, 9000, 4500]
qtys  = [10, 5, 20, 3, 8]

# គណនាចំណេញនីមួយៗ
print(f"{'ទំនិញ':<12} {'Revenue':>10} {'Profit':>10} {'Margin':>8}")
print("-" * 44)

total_revenue = 0
total_profit = 0

for i in range(len(names)):
    revenue = sells[i] * qtys[i]
    tc = costs[i] * qtys[i]
    profit = revenue - tc
    margin = (profit / revenue) * 100 if revenue > 0 else 0

    total_revenue += revenue
    total_profit += profit

    print(f"{names[i]:<12} {revenue:>10,} {profit:>10,} {margin:>7.2f}%")

print("-" * 44)
print(f"{'សរុប':<12} {total_revenue:>10,} {total_profit:>10,}")

Output

ទំនិញ          Revenue     Profit   Margin
--------------------------------------------
ទំនិញ A         50,000     20,000   40.00%
ទំនិញ B         40,000     15,000   37.50%
ទំនិញ C         60,000     10,000   16.67%
ទំនិញ D         36,000      9,000   25.00%
ទំនិញ E         48,000     12,000   25.00%
--------------------------------------------
សរុប            234,000     66,000

លំហាត់ (Practice)

១) រកទំនិញដែលមាន profit ធំជាងគេ (ប្រើ loop)

ចម្លើយ
best_name = ""
best_profit = 0
for i in range(len(names)):
    revenue = sells[i] * qtys[i]
    profit = revenue - (costs[i] * qtys[i])
    if profit > best_profit:
        best_profit = profit
        best_name = names[i]
print(f"ចំណេញច្រើនបំផុត: {best_name} ({best_profit:,})")

២) គណនា average profit (ប្រាក់ចំណេញមធ្យម)

ចម្លើយ
avg_profit = total_profit / len(names)
print(f"ចំណេញមធ្យម: {avg_profit:,.2f}")
# 66000 / 5 = 13,200.00

៣) បន្ថែមទំនិញ F (sell=7000, cost=4000, qty=6) ដោយប្រើ append()

ចម្លើយ
names.append("ទំនិញ F")
sells.append(7000)
costs.append(4000)
qtys.append(6)
print("ចំនួនទំនិញ:", len(names))  # 6

គន្លឹះ

  • range(len(list)) ផ្តល់ index 0, 1, 2... សម្រាប់ access ធាតុ។
  • ក្នុងមេរៀន 7 យើងនឹងប្រើ dict ជំនួស list ច្រើន ដើម្បីអានកូដងាយជាង។
7

dict (fields: name/sell/cost/qty)

គោលបំណង

  • បង្កើត dict ដើម្បីផ្ទុកទិន្នន័យមួយទំនិញ
  • បង្កើត list of dict សម្រាប់ទំនិញច្រើន
  • Access ទិន្នន័យតាម key: item["sell"]
  • ប្រើ for loop ជាមួយ list of dict
  • រៀបចំទិន្នន័យជា structure ច្បាស់លាស់

គំនិតសំខាន់

dict (dictionary) ផ្ទុកទិន្នន័យជា key:value។ ជំនួសឲ្យមាន list ច្រើន (names, sells, costs, qtys) យើងដាក់ទិន្នន័យមួយទំនិញក្នុង dict មួយ: {"name": "A", "sell": 5000, "cost": 3000, "qty": 10}។ រួចដាក់ dict ច្រើនក្នុង list មួយ → list of dict។ អានកូដស្រួលជាង ហើយក៏ត្រៀមសម្រាប់ CSV ផងដែរ។

Demo Code

# មេរៀន 7: dict — ទិន្នន័យរចនាសម្ព័ន្ធ
items = [
    {"name": "ទំនិញ A", "sell": 5000,  "cost": 3000, "qty": 10},
    {"name": "ទំនិញ B", "sell": 8000,  "cost": 5000, "qty": 5},
    {"name": "ទំនិញ C", "sell": 3000,  "cost": 2500, "qty": 20},
    {"name": "ទំនិញ D", "sell": 12000, "cost": 9000, "qty": 3},
    {"name": "ទំនិញ E", "sell": 6000,  "cost": 4500, "qty": 8},
]

# គណនារួចបន្ថែម field ថ្មី
for item in items:
    item["revenue"]    = item["sell"] * item["qty"]
    item["total_cost"] = item["cost"] * item["qty"]
    item["profit"]     = item["revenue"] - item["total_cost"]
    if item["revenue"] > 0:
        item["margin"] = round((item["profit"] / item["revenue"]) * 100, 2)
    else:
        item["margin"] = 0.0

# បង្ហាញ
print(f"{'ទំនិញ':<12} {'Revenue':>10} {'Profit':>10} {'Margin':>8}")
print("-" * 44)
for item in items:
    print(f"{item['name']:<12} {item['revenue']:>10,} "
          f"{item['profit']:>10,} {item['margin']:>7.2f}%")

Output

ទំនិញ          Revenue     Profit   Margin
--------------------------------------------
ទំនិញ A         50,000     20,000   40.00%
ទំនិញ B         40,000     15,000   37.50%
ទំនិញ C         60,000     10,000   16.67%
ទំនិញ D         36,000      9,000   25.00%
ទំនិញ E         48,000     12,000   25.00%

លំហាត់ (Practice)

១) រកទំនិញដែលមាន margin ខ្ពស់ជាងគេ (ប្រើ loop ជាមួយ dict)

ចម្លើយ
best = items[0]
for item in items:
    if item["margin"] > best["margin"]:
        best = item
print(f"Margin ខ្ពស់បំផុត: {best['name']} ({best['margin']}%)")
# ទំនិញ A (40.00%)

២) គណនា total revenue និង total profit ពី list of dict

ចម្លើយ
total_rev = sum(item["revenue"] for item in items)
total_prof = sum(item["profit"] for item in items)
print(f"Total Revenue: {total_rev:,}")   # 234,000
print(f"Total Profit: {total_prof:,}")   # 66,000

៣) បន្ថែម "ទំនិញ F" ក្នុង list ដោយប្រើ append() ជាមួយ dict

ចម្លើយ
items.append({
    "name": "ទំនិញ F",
    "sell": 7000,
    "cost": 4000,
    "qty": 6
})
print("ចំនួនទំនិញ:", len(items))  # 6

គន្លឹះ

  • item["sell"] ផ្តល់តម្លៃ; បើ key មិនមាន → KeyError។
  • List of dict ជា pattern សំខាន់ សម្រាប់ manage ទិន្នន័យជា "តារាង"។
8

Functions (បំបែកកូដឲ្យស្អាត)

គោលបំណង

  • យល់ពី function: ហេតុអ្វីត្រូវបំបែកកូដ
  • បង្កើត function ជាមួយ def
  • ប្រើ return ដើម្បីផ្តល់លទ្ធផលត្រឡប់
  • សរសេរ compute_item(), compute_summary(), validate_item()
  • ហៅ function ច្រើនដង (reuse)

គំនិតសំខាន់

Function គឺជា "ដុំកូដ" ដែលមានឈ្មោះ សម្រាប់ធ្វើកិច្ចការមួយ។ ជំនួសឲ្យសរសេរកូដគណនាច្រើនដង យើងដាក់វាក្នុង function រួចហៅប្រើ។ ប្រយោជន៍: (1) កូដខ្លី, (2) ងាយកែ, (3) អាចប្រើម្តងទៀត។ Pattern: def function_name(parameters): ... return result

Demo Code

# មេរៀន 8: Functions — បំបែកកូដឲ្យស្អាត

def validate_item(item):
    """ផ្ទៀងផ្ទាត់ទិន្នន័យ — return list of errors"""
    errors = []
    if not item.get("name", "").strip():
        errors.append("ឈ្មោះមិនអាចទទេបានទេ")
    if item.get("sell", 0) < 0:
        errors.append("ថ្លៃលក់មិនអាចអវិជ្ជមានបានទេ")
    if item.get("cost", 0) < 0:
        errors.append("ថ្លៃទិញមិនអាចអវិជ្ជមានបានទេ")
    if item.get("qty", 0) <= 0:
        errors.append("បរិមាណត្រូវតែ > 0")
    return errors

def compute_item(item):
    """គណនា revenue, total_cost, profit, margin"""
    item["revenue"]    = item["sell"] * item["qty"]
    item["total_cost"] = item["cost"] * item["qty"]
    item["profit"]     = item["revenue"] - item["total_cost"]
    if item["revenue"] > 0:
        item["margin"] = round((item["profit"] / item["revenue"]) * 100, 2)
    else:
        item["margin"] = 0.0
    return item

def compute_summary(items):
    """គណនា summary: total + best profit item"""
    total_rev  = sum(it["revenue"] for it in items)
    total_cost = sum(it["total_cost"] for it in items)
    total_prof = sum(it["profit"] for it in items)
    best = max(items, key=lambda x: x["profit"])
    return {
        "total_revenue": total_rev,
        "total_cost":    total_cost,
        "total_profit":  total_prof,
        "best_item":     best["name"],
        "best_profit":   best["profit"],
    }

# --- ប្រើ functions ---
items = [
    {"name": "ទំនិញ A", "sell": 5000,  "cost": 3000, "qty": 10},
    {"name": "ទំនិញ B", "sell": 8000,  "cost": 5000, "qty": 5},
    {"name": "ទំនិញ C", "sell": 3000,  "cost": 2500, "qty": 20},
    {"name": "ទំនិញ D", "sell": 12000, "cost": 9000, "qty": 3},
    {"name": "ទំនិញ E", "sell": 6000,  "cost": 4500, "qty": 8},
]

for item in items:
    errors = validate_item(item)
    if errors:
        print(f"កំហុស {item['name']}: {errors}")
    else:
        compute_item(item)

summary = compute_summary(items)
print(f"ចំណូលសរុប: {summary['total_revenue']:,}")
print(f"ចំណេញសរុប: {summary['total_profit']:,}")
print(f"ល្អបំផុត: {summary['best_item']} ({summary['best_profit']:,})")

Output

ចំណូលសរុប: 234,000
ចំណេញសរុប: 66,000
ល្អបំផុត: ទំនិញ A (20,000)

លំហាត់ (Practice)

១) ធ្វើ function print_report(items, summary) ដែលបង្ហាញតារាង + summary

ចម្លើយ
def print_report(items, summary):
    print(f"{'ទំនិញ':<12} {'Revenue':>10} {'Profit':>10} {'Margin':>8}")
    print("-" * 44)
    for it in items:
        print(f"{it['name']:<12} {it['revenue']:>10,} "
              f"{it['profit']:>10,} {it['margin']:>7.2f}%")
    print("-" * 44)
    print(f"សរុប Revenue: {summary['total_revenue']:,}")
    print(f"សរុប Profit:  {summary['total_profit']:,}")
    print(f"ល្អបំផុត: {summary['best_item']}")

២) បន្ថែម validation: sell មិនអាចជា string ("abc")

ចម្លើយ
def validate_item(item):
    errors = []
    if not isinstance(item.get("sell"), (int, float)):
        errors.append("sell ត្រូវតែជាលេខ")
    if not isinstance(item.get("cost"), (int, float)):
        errors.append("cost ត្រូវតែជាលេខ")
    if not isinstance(item.get("qty"), (int, float)):
        errors.append("qty ត្រូវតែជាលេខ")
    return errors

៣) ធ្វើ compute_average_margin(items) ដែល return margin មធ្យម

ចម្លើយ
def compute_average_margin(items):
    if not items:
        return 0.0
    total_margin = sum(it["margin"] for it in items)
    return round(total_margin / len(items), 2)

avg = compute_average_margin(items)
print(f"Margin មធ្យម: {avg}%")

គន្លឹះ

  • Function មួយ ធ្វើរឿងមួយ (Single Responsibility)។ កុំដាក់គណនា + print + save ក្នុង function មួយ។
  • ដាក់ docstring """...""" ក្រោម def ដើម្បីពន្យល់។
9

File CSV (រក្សាទុក/អានទិន្នន័យ)

គោលបំណង

  • យល់ពី CSV format (Comma-Separated Values)
  • ប្រើ csv.DictWriter ដើម្បីរក្សាទុក list of dict ទៅ CSV
  • ប្រើ csv.DictReader ដើម្បីអាន CSV ត្រឡប់មក
  • បម្លែង string ទៅ int/float ពេលអានពី CSV
  • ពិនិត្យឯកសារជាមួយ os.path.exists()

គំនិតសំខាន់

CSV ជាទម្រង់ឯកសារដែលផ្ទុកទិន្នន័យតារាង។ ជួរទី 1 ជា header (ឈ្មោះ column); ជួរបន្ទាប់ជាទិន្នន័យ។ Python មាន module csv សម្រាប់សរសេរ/អាន។ សំខាន់: ពេលអានពី CSV ទិន្នន័យទាំងអស់ជា string — ត្រូវបម្លែងលេខ!

Demo Code

# មេរៀន 9: CSV — រក្សាទុក និង អានទិន្នន័យ
import csv

items = [
    {"name": "ទំនិញ A", "sell": 5000,  "cost": 3000, "qty": 10},
    {"name": "ទំនិញ B", "sell": 8000,  "cost": 5000, "qty": 5},
    {"name": "ទំនិញ C", "sell": 3000,  "cost": 2500, "qty": 20},
    {"name": "ទំនិញ D", "sell": 12000, "cost": 9000, "qty": 3},
    {"name": "ទំនិញ E", "sell": 6000,  "cost": 4500, "qty": 8},
]

# === រក្សាទុកទៅ CSV ===
def export_csv(items, filename):
    fieldnames = ["name", "sell", "cost", "qty"]
    with open(filename, "w", newline="", encoding="utf-8") as f:
        writer = csv.DictWriter(f, fieldnames=fieldnames)
        writer.writeheader()
        for item in items:
            writer.writerow({
                "name": item["name"],
                "sell": item["sell"],
                "cost": item["cost"],
                "qty":  item["qty"],
            })
    print(f"រក្សាទុករួចរាល់: {filename} ({len(items)} ជួរ)")

# === អានពី CSV ===
def import_csv(filename):
    imported = []
    with open(filename, "r", encoding="utf-8") as f:
        reader = csv.DictReader(f)
        for row in reader:
            imported.append({
                "name": row["name"],
                "sell": float(row["sell"]),
                "cost": float(row["cost"]),
                "qty":  int(row["qty"]),
            })
    print(f"អានរួចរាល់: {filename} ({len(imported)} ជួរ)")
    return imported

# --- ប្រើ ---
export_csv(items, "report.csv")
loaded = import_csv("report.csv")

# បង្ហាញទិន្នន័យដែលអានបាន
for item in loaded:
    print(f"  {item['name']}: sell={item['sell']}, cost={item['cost']}, qty={item['qty']}")

Output

រក្សាទុករួចរាល់: report.csv (5 ជួរ)
អានរួចរាល់: report.csv (5 ជួរ)
  ទំនិញ A: sell=5000.0, cost=3000.0, qty=10
  ទំនិញ B: sell=8000.0, cost=5000.0, qty=5
  ទំនិញ C: sell=3000.0, cost=2500.0, qty=20
  ទំនិញ D: sell=12000.0, cost=9000.0, qty=3
  ទំនិញ E: sell=6000.0, cost=4500.0, qty=8

CSV ឯកសារ (report.csv)

name,sell,cost,qty
ទំនិញ A,5000,3000,10
ទំនិញ B,8000,5000,5
ទំនិញ C,3000,2500,20
ទំនិញ D,12000,9000,3
ទំនិញ E,6000,4500,8

លំហាត់ (Practice)

១) Export ជាមួយ computed fields: name, sell, cost, qty, revenue, profit, margin

ចម្លើយ
def export_full_csv(items, filename):
    fieldnames = ["name","sell","cost","qty","revenue","total_cost","profit","margin"]
    with open(filename, "w", newline="", encoding="utf-8") as f:
        writer = csv.DictWriter(f, fieldnames=fieldnames)
        writer.writeheader()
        for item in items:
            writer.writerow(item)

២) ប្រើ os.path.exists() ពិនិត្យថាឯកសារមានមុន import

ចម្លើយ
import os
filename = "report.csv"
if os.path.exists(filename):
    loaded = import_csv(filename)
else:
    print(f"កំហុស: រកមិនឃើញឯកសារ {filename}")

៣) Import CSV រួច compute ហើយ print report សម្រាប់ទិន្នន័យដែលអានបាន

ចម្លើយ
loaded = import_csv("report.csv")
for item in loaded:
    compute_item(item)  # ប្រើ function ពីមេរៀន 8
summary = compute_summary(loaded)
print_report(loaded, summary)

គន្លឹះ

  • ប្រើ encoding="utf-8" នៅពេល open() ដើម្បី support អក្សរខ្មែរ!
  • CSV អាន → string ជានិច្ច! ត្រូវ float(row["sell"])int(row["qty"])
10

Mini Project — Data Profit Analyzer

គោលបំណង

  • បញ្ចូលចំណេះដឹងទាំង 9 មេរៀនចូលគ្នា ក្នុង project មួយ
  • សរសេរកម្មវិធីដែលមាន menu (ផ្ទាំងជម្រើស)
  • ប្រើ functions, validation, CSV export/import
  • បង្កើត report ដែលអាចអានបានច្បាស់
  • ត្រៀមខ្លួនសម្រាប់ Assignment

គំនិតសំខាន់

Mini Project នេះបញ្ចូលអ្វីដែលរៀន: list of dict + functions (validate, compute, export, import, report) + CSV + menu។ Flow: ជ្រើសរើស Option A (ប្រើ sample data → គណនា → export) ឬ Option B (import CSV → គណនា → report)។ នេះជា project គំរូ មុនធ្វើ Assignment។

Demo Code (សង្ខេប)

# មេរៀន 10: Mini Project — Data Profit Analyzer
import csv, os

# --- Functions (ពីមេរៀន 8 + 9) ---
def validate_item(item):
    errors = []
    if not item.get("name", "").strip():
        errors.append("ឈ្មោះទទេ")
    if item.get("sell", 0) < 0:
        errors.append("sell អវិជ្ជមាន")
    if item.get("cost", 0) < 0:
        errors.append("cost អវិជ្ជមាន")
    if item.get("qty", 0) <= 0:
        errors.append("qty ត្រូវតែ > 0")
    return errors

def compute_item(item):
    item["revenue"]    = item["sell"] * item["qty"]
    item["total_cost"] = item["cost"] * item["qty"]
    item["profit"]     = item["revenue"] - item["total_cost"]
    item["margin"]     = round((item["profit"] / item["revenue"]) * 100, 2) if item["revenue"] > 0 else 0.0
    return item

def compute_summary(items):
    total_rev  = sum(it["revenue"] for it in items)
    total_cost = sum(it["total_cost"] for it in items)
    total_prof = sum(it["profit"] for it in items)
    best = max(items, key=lambda x: x["profit"])
    return {"total_revenue": total_rev, "total_cost": total_cost,
            "total_profit": total_prof, "best_item": best["name"],
            "best_profit": best["profit"]}

def export_csv(items, filename):
    fields = ["name","sell","cost","qty","revenue","total_cost","profit","margin"]
    with open(filename, "w", newline="", encoding="utf-8") as f:
        writer = csv.DictWriter(f, fieldnames=fields)
        writer.writeheader()
        for item in items:
            writer.writerow(item)
    print(f"✓ Export រួចរាល់: {filename}")

def import_csv(filename):
    data = []
    with open(filename, "r", encoding="utf-8") as f:
        for row in csv.DictReader(f):
            data.append({"name": row["name"], "sell": float(row["sell"]),
                         "cost": float(row["cost"]), "qty": int(row["qty"])})
    print(f"✓ Import រួចរាល់: {filename} ({len(data)} items)")
    return data

def print_report(items, summary):
    print(f"\n{'='*54}")
    print(f"  របាយការណ៍ប្រាក់ចំណេញ (Profit Report)")
    print(f"{'='*54}")
    print(f"{'ទំនិញ':<12} {'Revenue':>10} {'Cost':>10} {'Profit':>10} {'Margin':>8}")
    print(f"{'-'*54}")
    for it in items:
        print(f"{it['name']:<12} {it['revenue']:>10,} {it['total_cost']:>10,} "
              f"{it['profit']:>10,} {it['margin']:>7.2f}%")
    print(f"{'-'*54}")
    print(f"{'សរុប':<12} {summary['total_revenue']:>10,} "
          f"{summary['total_cost']:>10,} {summary['total_profit']:>10,}")
    print(f"\nចំណេញច្រើនបំផុត: {summary['best_item']} ({summary['best_profit']:,})")
    print(f"{'='*54}")

# --- Sample Data ---
sample_items = [
    {"name": "ទំនិញ A", "sell": 5000,  "cost": 3000, "qty": 10},
    {"name": "ទំនិញ B", "sell": 8000,  "cost": 5000, "qty": 5},
    {"name": "ទំនិញ C", "sell": 3000,  "cost": 2500, "qty": 20},
    {"name": "ទំនិញ D", "sell": 12000, "cost": 9000, "qty": 3},
    {"name": "ទំនិញ E", "sell": 6000,  "cost": 4500, "qty": 8},
]

# --- Main Menu ---
print("=== Data Profit Analyzer ===")
print("A) ប្រើ Sample Data → គណនា → Export CSV")
print("B) Import CSV → គណនា → Report")
choice = input("ជ្រើសរើស (A/B): ").strip().upper()

if choice == "A":
    for item in sample_items:
        errors = validate_item(item)
        if errors:
            print(f"កំហុស {item['name']}: {errors}")
        else:
            compute_item(item)
    summary = compute_summary(sample_items)
    print_report(sample_items, summary)
    export_csv(sample_items, "report.csv")

elif choice == "B":
    fname = "report.csv"
    if not os.path.exists(fname):
        print(f"កំហុស: រកមិនឃើញ {fname}")
    else:
        loaded = import_csv(fname)
        for item in loaded:
            compute_item(item)
        summary = compute_summary(loaded)
        print_report(loaded, summary)
else:
    print("ជម្រើសមិនត្រឹមត្រូវ!")

Output (Option A)

=== Data Profit Analyzer ===
A) ប្រើ Sample Data → គណនា → Export CSV
B) Import CSV → គណនា → Report
ជ្រើសរើស (A/B): A

======================================================
  របាយការណ៍ប្រាក់ចំណេញ (Profit Report)
======================================================
ទំនិញ          Revenue       Cost     Profit   Margin
------------------------------------------------------
ទំនិញ A         50,000     30,000     20,000   40.00%
ទំនិញ B         40,000     25,000     15,000   37.50%
ទំនិញ C         60,000     50,000     10,000   16.67%
ទំនិញ D         36,000     27,000      9,000   25.00%
ទំនិញ E         48,000     36,000     12,000   25.00%
------------------------------------------------------
សរុប            234,000    168,000     66,000

ចំណេញច្រើនបំផុត: ទំនិញ A (20,000)
======================================================
✓ Export រួចរាល់: report.csv

លំហាត់ (Practice)

១) បន្ថែម Option C: បញ្ចូលទិន្នន័យដោយដៃ (input) → compute → export

ចម្លើយ
# ក្នុង menu បន្ថែម:
elif choice == "C":
    manual_items = []
    n = int(input("ចំនួនទំនិញ: "))
    for i in range(n):
        name = input(f"ឈ្មោះទំនិញ {i+1}: ")
        sell = float(input("sell: "))
        cost = float(input("cost: "))
        qty = int(input("qty: "))
        manual_items.append({"name": name, "sell": sell, "cost": cost, "qty": qty})
    for item in manual_items:
        compute_item(item)
    summary = compute_summary(manual_items)
    print_report(manual_items, summary)

២) បន្ថែមការបង្ហាញ average margin ក្នុង report

ចម្លើយ
# ក្នុង compute_summary បន្ថែម:
avg_margin = round(sum(it["margin"] for it in items) / len(items), 2)
# ក្នុង print_report បន្ថែម:
print(f"Margin មធ្យម: {summary['avg_margin']:.2f}%")

៣) ធ្វើ while loop ឲ្យ menu ដំណើរការម្តងទៀតរហូតអ្នកប្រើជ្រើស "Q" (Quit)

ចម្លើយ
while True:
    print("\n=== Data Profit Analyzer ===")
    print("A) Sample Data  B) Import CSV  Q) Quit")
    choice = input("ជ្រើសរើស: ").strip().upper()
    if choice == "Q":
        print("លាហើយ!")
        break
    elif choice == "A":
        # ... (code Option A)
        pass
    elif choice == "B":
        # ... (code Option B)
        pass

គន្លឹះ

  • គ្រប់ function ត្រូវមានពីមុន (validate, compute, export, import, report) — ហៅប្រើតែប៉ុណ្ណោះ។
  • ធ្វើម្តងមួយ feature រួចធ្វើតេស្ត មុនបន្ថែម feature ថ្មី!

Assignment: Data Profit Analyzer (Python)

ការងារផ្ទាល់ខ្លួន — វគ្គសិក្សា Python ទិន្នន័យ/ការគណនា

គោលបំណងនៃការរៀន (Learning Objectives)

ការងារនេះទាក់ទងនឹង មេរៀន 6–10។ បន្ទាប់ពីបញ្ចប់ អ្នកនឹង:

  • ប្រើ list of dict ផ្ទុកទិន្នន័យទំនិញច្រើន
  • សរសេរ functions សម្រាប់គណនា (compute), ផ្ទៀងផ្ទាត់ (validate), និងរបាយការណ៍ (report)
  • គណនា revenue, total_cost, profit, profit_margin សម្រាប់ទំនិញនីមួយៗ
  • Export/Import ទិន្នន័យជា CSV
  • បង្កើត summary report ដែលរួមបញ្ចូល totals + best profit item

តម្រូវការ និង ការកំណត់ (Requirements & Constraints)

  • ប្រើ list of dict — ទំនិញនីមួយៗមាន keys: name, sell, cost, qty
  • ប្រើ functions សម្រាប់គណនា (កុំដាក់កូដទាំងអស់ក្នុង main)
  • ផ្ទៀងផ្ទាត់ Input: sell/cost មិនអវិជ្ជមាន, qty > 0, name មិនទទេ
  • sell == cost គឺអាចទទួលយកបាន ប៉ុន្តែ profit នឹង = 0
  • រក្សាទុកលទ្ធផលទៅ CSV (report.csv)
  • អានទិន្នន័យពី CSV រួចបង្កើត report ឡើងវិញ
  • ប្រើ Python standard library តែប៉ុណ្ណោះ (csv, os) — គ្មាន pandas
  • Profit margin បង្ហាញជា % ជាមួយ 2 ខ្ទង់ទសភាគ

កិច្ចការ (Tasks)

1

បង្កើតឈុតទិន្នន័យ (Dataset) — យ៉ាងតិច 5 ទំនិញ

ប្រើ list of dict ដែល key = name, sell, cost, qty។ អាចប្រើ sample ខាងក្រោម ឬបង្កើតថ្មី។

2

គណនាសម្រាប់ទំនិញនីមួយៗ: revenue, total_cost, profit, margin

revenue = sell × qty, total_cost = cost × qty, profit = revenue − total_cost, margin = (profit/revenue)×100

3

បង្ហាញ Summary: total revenue, total cost, total profit + ទំនិញមានចំណេញច្រើនបំផុត

ប្រើ formatted output (f-string) ដែលអានបានច្បាស់លាស់។

4

Export ទៅ CSV (report.csv)

ប្រើ csv.DictWriter រួមជាមួយ header row។

5

Import ពី CSV រួចបង្កើត report ឡើងវិញ

អានដោយ csv.DictReader → បម្លែង str→number → compute → report។

ទិន្នន័យគំរូ (Sample Dataset)

name sell cost qty revenue total_cost profit margin
ទំនិញ A5,0003,0001050,00030,00020,00040.00%
ទំនិញ B8,0005,000540,00025,00015,00037.50%
ទំនិញ C3,0002,5002060,00050,00010,00016.67%
ទំនិញ D12,0009,000336,00027,0009,00025.00%
ទំនិញ E6,0004,500848,00036,00012,00025.00%
សរុប 234,000 168,000 66,000

ចំណេញច្រើនបំផុត: ទំនិញ A (profit = 20,000)

អ្វីដែលត្រូវផ្ញើមក (Deliverables)

  • ឯកសារ Python: profit_analyzer.py
  • ឯកសារ CSV: report.csv (exported ពីកម្មវិធី)
  • Screenshot នៃ output (ជាជម្រើស)

Rubric — ការវាយតម្លៃ (100 ពិន្ទុ)

លក្ខណវិនិច្ឆ័យ (Criteria) ការពិពណ៌នា (Description) ពិន្ទុ កំហុសទូទៅ (Common Mistakes)
រចនាសម្ព័ន្ធទិន្នន័យ
(Data Structure)
  • ប្រើ list of dict ត្រឹមត្រូវ
  • Keys ត្រឹមត្រូវ: name, sell, cost, qty
  • យ៉ាងតិច 5 ទំនិញ
  • Data types ត្រឹមត្រូវ (str, int/float)
15
  • ប្រើ list ច្រើន ជំនួស list of dict
  • ភ្លេច key ឬ key ខុសឈ្មោះ
  • ទិន្នន័យតិចជាង 5
ការគណនា
(Calculations)
  • revenue = sell × qty ✓
  • total_cost = cost × qty ✓
  • profit = revenue − total_cost ✓
  • margin = (profit/revenue)×100 ✓
  • Summary totals ត្រឹមត្រូវ
  • Best profit item ត្រឹមត្រូវ
25
  • រូមន្តគណនាខុស
  • ចែកនឹង 0 (division by zero)
  • Margin មិនគុណ 100
  • Summary total ខុស
ការផ្ទៀងផ្ទាត់
(Validation & Error Handling)
  • ពិនិត្យ name មិនទទេ
  • ពិនិត្យ sell/cost >= 0
  • ពិនិត្យ qty > 0
  • ដោះស្រាយ revenue = 0 (ចែកនឹង 0)
  • ប្រើ try/except កន្លែងចាំបាច់
20
  • គ្មាន validation ទាំងអស់
  • ប្រើ validation ប៉ុន្តែមិនពេញលេញ
  • Program crash ពេលданных ខុស
CSV Export/Import
(ឯកសារ CSV)
  • Export ជា CSV ត្រឹមត្រូវ (header + data)
  • Import ពី CSV ជោគជ័យ
  • បម្លែង string→number ពេល import
  • ប្រើ encoding="utf-8"
  • ពិនិត្យ file exists មុន import
20
  • ភ្លេច newline="" ក្នុង open()
  • មិនបម្លែង str→int/float ពេល import
  • គ្មាន header row
  • File path ខុស ឬ hardcoded
រចនាសម្ព័ន្ធកូដ
(Code Structure)
  • ប្រើ functions (មិនមែន flat code)
  • ឈ្មោះអថេរ/function ច្បាស់លាស់
  • មាន comments ពន្យល់
  • កូដអាចអានបានស្រួល (readability)
  • មិនមាន code duplication ច្រើន
15
  • គ្មាន function ទាំងអស់
  • ឈ្មោះអថេរ x, y, z
  • គ្មាន comment
  • Copy-paste កូដដដែលៗ
Output/Report
(លទ្ធផល)
  • Report អានបានច្បាស់ (formatted)
  • Margin បង្ហាញ % ជា 2 ខ្ទង់
  • Summary ពេញលេញ
5
  • Output មិនមាន format
  • Margin មិនបង្ហាញជា %
សរុប (Total) 100

A (90–100)

ឆ្នើម

B (75–89)

ល្អ

C (60–74)

មធ្យម

D (<60)

ត្រូវកែលម្អ

Answer Key — ចម្លើយ (profit_analyzer.py)

កូដពេញលេញ — សម្រាប់គ្រូ

"""
Data Profit Analyzer — Answer Key
វគ្គសិក្សា Python: ទិន្នន័យ → គណនា → សង្ខេប → រក្សាទុក
"""
import csv
import os

# ===== SAMPLE DATA =====
SAMPLE_ITEMS = [
    {"name": "ទំនិញ A", "sell": 5000,  "cost": 3000, "qty": 10},
    {"name": "ទំនិញ B", "sell": 8000,  "cost": 5000, "qty": 5},
    {"name": "ទំនិញ C", "sell": 3000,  "cost": 2500, "qty": 20},
    {"name": "ទំនិញ D", "sell": 12000, "cost": 9000, "qty": 3},
    {"name": "ទំនិញ E", "sell": 6000,  "cost": 4500, "qty": 8},
]

# ===== VALIDATION =====
def validate_item(item):
    errors = []
    if not item.get("name", "").strip():
        errors.append("ឈ្មោះមិនអាចទទេបានទេ")
    if not isinstance(item.get("sell"), (int, float)) or item["sell"] < 0:
        errors.append("ថ្លៃលក់ (sell) ត្រូវតែ >= 0")
    if not isinstance(item.get("cost"), (int, float)) or item["cost"] < 0:
        errors.append("ថ្លៃទិញ (cost) ត្រូវតែ >= 0")
    if not isinstance(item.get("qty"), (int, float)) or item["qty"] <= 0:
        errors.append("បរិមាណ (qty) ត្រូវតែ > 0")
    return errors

# ===== COMPUTE =====
def compute_item(item):
    item["revenue"]    = item["sell"] * item["qty"]
    item["total_cost"] = item["cost"] * item["qty"]
    item["profit"]     = item["revenue"] - item["total_cost"]
    if item["revenue"] > 0:
        item["margin"] = round((item["profit"] / item["revenue"]) * 100, 2)
    else:
        item["margin"] = 0.0
    return item

def compute_summary(items):
    total_rev  = sum(it["revenue"]    for it in items)
    total_cost = sum(it["total_cost"] for it in items)
    total_prof = sum(it["profit"]     for it in items)
    best = max(items, key=lambda x: x["profit"])
    return {
        "total_revenue": total_rev,
        "total_cost":    total_cost,
        "total_profit":  total_prof,
        "best_item":     best["name"],
        "best_profit":   best["profit"],
    }

# ===== CSV =====
def export_csv(items, filename):
    fields = ["name","sell","cost","qty","revenue","total_cost","profit","margin"]
    with open(filename, "w", newline="", encoding="utf-8") as f:
        writer = csv.DictWriter(f, fieldnames=fields)
        writer.writeheader()
        for item in items:
            writer.writerow(item)
    print(f"✓ Export: {filename} ({len(items)} ជួរ)")

def import_csv(filename):
    data = []
    with open(filename, "r", encoding="utf-8") as f:
        for row in csv.DictReader(f):
            data.append({
                "name": row["name"],
                "sell": float(row["sell"]),
                "cost": float(row["cost"]),
                "qty":  int(row["qty"]),
            })
    print(f"✓ Import: {filename} ({len(data)} ជួរ)")
    return data

# ===== REPORT =====
def print_report(items, summary):
    print(f"\n{'='*60}")
    print(f"  របាយការណ៍ប្រាក់ចំណេញ (Profit Report)")
    print(f"{'='*60}")
    print(f"{'ទំនិញ':<12} {'Revenue':>10} {'Cost':>10} {'Profit':>10} {'Margin':>8}")
    print(f"{'-'*60}")
    for it in items:
        print(f"{it['name']:<12} {it['revenue']:>10,} {it['total_cost']:>10,} "
              f"{it['profit']:>10,} {it['margin']:>7.2f}%")
    print(f"{'-'*60}")
    print(f"{'សរុប':<12} {summary['total_revenue']:>10,} "
          f"{summary['total_cost']:>10,} {summary['total_profit']:>10,}")
    print(f"\nចំណេញច្រើនបំផុត: {summary['best_item']} "
          f"(profit = {summary['best_profit']:,})")
    print(f"{'='*60}")

# ===== MAIN =====
def main():
    print("=" * 40)
    print("  Data Profit Analyzer")
    print("=" * 40)
    print("A) ប្រើ Sample Data → គណនា → Export CSV")
    print("B) Import CSV → គណនា → Report")
    choice = input("\nជ្រើសរើស (A/B): ").strip().upper()

    if choice == "A":
        items = [dict(it) for it in SAMPLE_ITEMS]  # copy
        for item in items:
            errors = validate_item(item)
            if errors:
                print(f"⚠ {item.get('name','?')}: {', '.join(errors)}")
                return
            compute_item(item)
        summary = compute_summary(items)
        print_report(items, summary)
        export_csv(items, "report.csv")

    elif choice == "B":
        fname = "report.csv"
        if not os.path.exists(fname):
            print(f"កំហុស: រកមិនឃើញ {fname}")
            return
        items = import_csv(fname)
        for item in items:
            errors = validate_item(item)
            if errors:
                print(f"⚠ {item.get('name','?')}: {', '.join(errors)}")
                return
            compute_item(item)
        summary = compute_summary(items)
        print_report(items, summary)
    else:
        print("ជម្រើសមិនត្រឹមត្រូវ!")

if __name__ == "__main__":
    main()

sample_sales.csv

name,sell,cost,qty
ទំនិញ A,5000,3000,10
ទំនិញ B,8000,5000,5
ទំនិញ C,3000,2500,20
ទំនិញ D,12000,9000,3
ទំនិញ E,6000,4500,8