Python โปรเจกต์: เครื่องคิดเลข CLI
โปรเจกต์แรกที่รวมสิ่งที่เรียนมาตั้งแต่ต้น: input/output, เงื่อนไข, ลูป, ฟังก์ชัน, การจัดการข้อผิดพลาด, dictionary และการเขียนเทสต์ เราจะสร้างเครื่องคิดเลขที่ทำงานในเทอร์มินัล
สิ่งที่โปรแกรมทำได้
- บวก ลบ คูณ หาร ยกกำลัง
- คำนวณต่อเนื่องโดยใช้ผลลัพธ์ก่อนหน้า
- จัดการกรณีหารด้วยศูนย์และ input ผิดรูปแบบ
- พิมพ์
helpดูวิธีใช้ พิมพ์quitออก
ขั้นที่ 1: ฟังก์ชันคำนวณหลัก
โค้ดขั้นที่ 1–3 ต่อกันเป็นไฟล์เดียวชื่อ calculator.py (แต่ละบล็อกเขียนต่อท้ายบล็อกก่อนหน้า) ส่วนเทสต์ในขั้นที่ 4 อยู่ในไฟล์แยก test_calculator.py
เริ่มจากตรรกะล้วน ๆ แยกจาก input/output จะได้เทสต์ง่าย
# calculator.py
def calculate(a, operator, b):
"""คำนวณ a operator b คืนผลลัพธ์"""
if operator == "+":
return a + b
if operator == "-":
return a - b
if operator == "*":
return a * b
if operator == "/":
if b == 0:
raise ZeroDivisionError("หารด้วยศูนย์ไม่ได้")
return a / b
if operator == "**":
return a ** b
raise ValueError(f"ไม่รู้จักตัวดำเนินการ '{operator}'")ขั้นที่ 2: แยกนิพจน์ที่ผู้ใช้พิมพ์
ผู้ใช้พิมพ์ 12 + 5 เราต้องแยกเป็น 12, +, 5
def parse_expression(text):
"""แปลง '12 + 5' เป็น (12.0, '+', 5.0)"""
parts = text.split()
if len(parts) != 3:
raise ValueError("รูปแบบ: ตัวเลข ตัวดำเนินการ ตัวเลข เช่น 12 + 5")
left, operator, right = parts
return float(left), operator, float(right)ขั้นที่ 3: ลูปหลักและเมนู
HELP_TEXT = """
คำสั่ง:
<ตัวเลข> <ตัวดำเนินการ> <ตัวเลข> เช่น 12 + 5
ตัวดำเนินการ: + - * / **
ใช้ ans แทนผลลัพธ์ก่อนหน้า เช่น ans * 2
help แสดงข้อความนี้
quit ออกจากโปรแกรม
"""
def main():
print("=== เครื่องคิดเลข ===")
print("พิมพ์ help เพื่อดูวิธีใช้")
answer = 0.0
while True:
text = input("\n> ").strip()
if text == "quit":
print("ลาก่อน")
break
if text == "help":
print(HELP_TEXT)
continue
if not text:
continue
# แทน ans ด้วยผลลัพธ์ก่อนหน้า
text = text.replace("ans", str(answer))
try:
a, operator, b = parse_expression(text)
answer = calculate(a, operator, b)
# แสดงเป็นจำนวนเต็มถ้าลงตัว
if answer == int(answer):
print(f"= {int(answer)}")
else:
print(f"= {answer}")
except ZeroDivisionError as e:
print(f"ผิดพลาด: {e}")
except ValueError as e:
print(f"ผิดพลาด: {e}")
if __name__ == "__main__":
main()ทดลองใช้
=== เครื่องคิดเลข ===
พิมพ์ help เพื่อดูวิธีใช้
> 12 + 5
= 17
> ans * 3
= 51
> 51 / 0
ผิดพลาด: หารด้วยศูนย์ไม่ได้
> 2 ** 10
= 1024
> สวัสดี
ผิดพลาด: รูปแบบ: ตัวเลข ตัวดำเนินการ ตัวเลข เช่น 12 + 5
> quit
ลาก่อนขั้นที่ 4: เขียนเทสต์
ต้องมี pytest ก่อน — พิมพ์ใน เทอร์มินัล (ไม่ใช่ Python shell): pip install pytest
# test_calculator.py
import pytest
from calculator import calculate, parse_expression
@pytest.mark.parametrize("a, op, b, expected", [
(2, "+", 3, 5),
(10, "-", 4, 6),
(6, "*", 7, 42),
(15, "/", 3, 5),
(2, "**", 8, 256),
])
def test_calculate(a, op, b, expected):
assert calculate(a, op, b) == expected
def test_divide_by_zero():
with pytest.raises(ZeroDivisionError):
calculate(10, "/", 0)
def test_unknown_operator():
with pytest.raises(ValueError):
calculate(1, "%", 2)
def test_parse_expression():
assert parse_expression("12 + 5") == (12.0, "+", 5.0)
def test_parse_bad_format():
with pytest.raises(ValueError):
parse_expression("12 +")pytest -vแนวคิดที่ได้ทบทวน
| แนวคิด | ใช้ตรงไหน |
|---|---|
| ฟังก์ชัน + return | calculate, parse_expression |
| เงื่อนไข | เลือกตัวดำเนินการ, จัดการคำสั่ง |
| ลูป while + break | เมนูหลัก |
| exception | หารศูนย์, input ผิด |
| string method | split(), strip(), replace() |
| แยกตรรกะออกจาก I/O | เพื่อเขียนเทสต์ |
ต่อยอด
- รองรับวงเล็บและลำดับการคำนวณ (ศึกษา
ast.literal_evalหรือเขียน parser เอง) - เก็บประวัติการคำนวณลงไฟล์
- เพิ่มฟังก์ชันทางวิทยาศาสตร์ (
sqrt,sin,log) ด้วย modulemath - ทำเป็นแพ็กเกจตามโครงสร้างในบทที่ 47
เช็คความเข้าใจก่อนข้ามบท
- แยกได้ว่าส่วนคำนวณ (
calculate) ไม่ควรผูกกับinput()หรือprint()เพื่อให้เทสต์ง่าย - อธิบายได้ว่า
parse_expressionรับผิดชอบอะไร และ error แบบใดควรถูกโยนออกมา - ลองเพิ่มตัวดำเนินการ
%พร้อม test กรณีหารเอาเศษ
สรุป
โปรเจกต์นี้แสดงรูปแบบที่ใช้ได้กับโปรแกรม CLI แทบทุกตัว: แยกตรรกะเป็นฟังก์ชันบริสุทธิ์ ครอบด้วยลูปเมนู while True + break จัดการ input ผิดด้วย try/except และเขียนเทสต์ให้ตรรกะหลัก
บทถัดไปเป็นเกมทายตัวเลข ฝึกเรื่องการสุ่มและสถานะของเกม