ข้ามไปยังเนื้อหา

Control Flow

เงื่อนไขใน 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) # B

Python ไม่มี switch statement — ใช้ if/elif chain หรือตั้งแต่ Python 3.10 ใช้ structural pattern matching (match/case)

ลูป 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(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 ทำซ้ำตราบเท่าที่เงื่อนไขเป็น truthy

count = 0
while count < 3:
print(count)
count += 1
  • break ออกจากลูปในสุดทันที
  • continue ข้ามส่วนที่เหลือของการวนซ้ำปัจจุบันและไปยังครั้งถัดไป
  • clause else บนลูปทำงาน เฉพาะเมื่อลูปจบโดยไม่พบ break
for n in [1, 3, 5, 7]:
if n % 2 == 0:
print("found even")
break
else:
print("no even number found") # บรรทัดนี้ทำงาน

เปิดตัวใน Python 3.8, := กำหนดค่าและประเมินเป็นค่านั้นในนิพจน์เดียว มีประโยชน์มากในเงื่อนไข while และ if เพื่อหลีกเลี่ยงการเขียนนิพจน์ซ้ำ

data = [4, 7, 2, 9, 1]
if (largest := max(data)) > 5:
print(f"Largest value {largest} exceeds 5")
score = 85
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
else:
grade = "F"
print(f"Score {score} -> Grade {grade}")
total = 0
for i in range(1, 6):
total += i
print(f"Sum 1..5 = {total}")
numbers = [1, 3, 5, 7]
for n in numbers:
if n % 2 == 0:
print(f"Found even: {n}")
break
else:
print("No even numbers found")
count = 0
while 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")
clause `else` ของลูป `for` ทำงานเมื่อใด?
`range(2, 10, 3)` ให้ผลลัพธ์อะไร?
walrus operator `:=` ทำอะไร?
statement ใดจบการวนซ้ำปัจจุบันและไปยังครั้งถัดไปทันที?