Control Flow
เงื่อนไข: if / elif / else
หัวข้อที่มีชื่อว่า “เงื่อนไข: if / elif / else”เงื่อนไขใน Python ใช้การเยื้องแทนวงเล็บปีกกา นิพจน์ใดก็ตามที่ประเมินได้เป็น truthy หรือ falsy สามารถใช้เป็นเงื่อนไขได้
score = 85
if score >= 90: grade = "A"elif score >= 80: grade = "B"elif score >= 70: grade = "C"else: grade = "F"
print(grade) # BPython ไม่มี switch statement — ใช้ if/elif chain หรือตั้งแต่ Python 3.10 ใช้ structural pattern matching (match/case)
ลูป for บน iterable
หัวข้อที่มีชื่อว่า “ลูป for บน iterable”ลูป for ของ Python วนซ้ำบน iterable ใดก็ได้ — list, string, range, file, dictionary, หรือออบเจกต์ที่ implement __iter__
fruits = ["apple", "banana", "cherry"]for fruit in fruits: print(fruit)
# วนซ้ำบนตัวอักษรในสตริงfor ch in "hello": print(ch)ใช้ enumerate() เมื่อต้องการทั้ง index และค่า:
for i, fruit in enumerate(fruits, start=1): print(f"{i}. {fruit}")range()
หัวข้อที่มีชื่อว่า “range()”range(stop), range(start, stop), และ range(start, stop, step) สร้างลำดับจำนวนเต็มโดยไม่สร้าง list ในหน่วยความจำ
for i in range(5): # 0, 1, 2, 3, 4 print(i)
for i in range(2, 10, 2): # 2, 4, 6, 8 print(i)ลูป while
หัวข้อที่มีชื่อว่า “ลูป while”while ทำซ้ำตราบเท่าที่เงื่อนไขเป็น truthy
count = 0while count < 3: print(count) count += 1break, continue, และ else บนลูป
หัวข้อที่มีชื่อว่า “break, continue, และ else บนลูป”breakออกจากลูปในสุดทันทีcontinueข้ามส่วนที่เหลือของการวนซ้ำปัจจุบันและไปยังครั้งถัดไป- clause
elseบนลูปทำงาน เฉพาะเมื่อลูปจบโดยไม่พบbreak
for n in [1, 3, 5, 7]: if n % 2 == 0: print("found even") breakelse: print("no even number found") # บรรทัดนี้ทำงานWalrus Operator :=
หัวข้อที่มีชื่อว่า “Walrus Operator :=”เปิดตัวใน Python 3.8, := กำหนดค่าและประเมินเป็นค่านั้นในนิพจน์เดียว
มีประโยชน์มากในเงื่อนไข while และ if เพื่อหลีกเลี่ยงการเขียนนิพจน์ซ้ำ
data = [4, 7, 2, 9, 1]if (largest := max(data)) > 5: print(f"Largest value {largest} exceeds 5")Demo ที่รันได้จริง
หัวข้อที่มีชื่อว่า “Demo ที่รันได้จริง”score = 85if score >= 90: grade = "A"elif score >= 80: grade = "B"elif score >= 70: grade = "C"else: grade = "F"print(f"Score {score} -> Grade {grade}")
total = 0for i in range(1, 6): total += iprint(f"Sum 1..5 = {total}")
numbers = [1, 3, 5, 7]for n in numbers: if n % 2 == 0: print(f"Found even: {n}") breakelse: print("No even numbers found")
count = 0while True: count += 1 if count % 2 == 0: continue if count > 7: break print(f"odd: {count}")
data = [4, 7, 2, 9, 1]if (largest := max(data)) > 5: print(f"Largest value {largest} exceeds 5")Loading Python runtime (first run only)…