if, for, while ใน Python: วิธีใช้ conditional statements, control flow, และ loop control ใน Python พร้อมตัวอย่าง

ในบทความนี้ เราจะมาดูวิธีใช้ code 3 ประเภท ที่จะช่วยให้ Python code สามารถตัดสินใจแทนเราได้:

  1. Conditional statements: if, elif, else
  2. Control flow statements: for, while
  3. Loop control statements: continue, break, pass

ก่อนไปดูวิธีใช้ทั้ง 3 ประเภท เราจะไปทำความรู้จักกับ comparison และ logical statement ซึ่งเราจะใช้ร่วมกับ code 3 ประเภทนี้กัน

ถ้าพร้อมแล้ว ไปเริ่มกันเลย


  1. 🧮 1. Comparison & Logical Operators
    1. #️⃣ (1) Comparison Operators
    2. ♟️ (2) Logical Operators
  2. 🚦 2. Conditional Statements
  3. 🌊 3. Control Flow Statements
    1. 📦 (1) for Loop
    2. 🔁 (2) while Loop
  4. 🚄 4. Loop Control Statements
  5. 💪 5. Summary
  6. 😺 GitHub
  7. 📃 References

🧮 1. Comparison & Logical Operators

#️⃣ (1) Comparison Operators

Comparison operators เป็นเครื่องหมายใช้เปรียบเทียบข้อมูล:

OperatorDescription
==เท่ากับ
!=ไม่เท่ากับ
>มากกว่า
>=มากกว่า/เท่ากับ
<น้อยกว่า
<=น้อยกว่า/เท่ากับ

โดย comparison operators จะให้ผลลัพธ์เป็น Boolean (True, False) กลับมา เช่น:

# True statement
10 > 5

ผลลัพธ์:

True

และ:

# False statement
10 < 5

ผลลัพธ์:

False

♟️ (2) Logical Operators

Logical operators เป็น keywords เชื่อมเงื่อนไข ช่วยให้เราประเมินหลายเงื่อนไขพร้อมกันได้:

OperatorDescription
andLogical AND
orLogical OR
notLogical NOT

โดยผลลัพธ์เป็นไปตาม truth table:

Condition 1OperatorCondition 2Result
TrueandTrueTrue
TrueandFalseFalse
FalseandFalseFalse
TrueorTrueTrue
TrueorFalseTrue
FalseorFalseFalse
notTrueFalse
notFalseTrue

ยกตัวอย่างเช่น:

# True and True
1 == 1 and 2 < 4

ผลลัพธ์:

True

🚦 2. Conditional Statements

Conditional statements ใช้กำหนดเงื่อนไขว่า code จะรันได้เมื่อไร และมีอยู่ 3 แบบ ได้แก่:

  • if: กำหนดเงื่อนไขแรก
  • elif: กำหนดเงื่อนไขเพิ่มเติม
  • else: รันเมื่อตรงกับเงื่อนไขอื่น ๆ ที่ไม่ใช่ if และ elif

ยกตัวอย่างเช่น เราต้องการ print ข้อความแจ้งเตือนตามสภาพอากาศ:

# Weather today
weather = "snowy"

เราสามารถทำได้แบบนี้:

# Print when sunny
if weather == "sunny":
    print("It's a sunny day. Don't forget your sunscreen!")

# Print when rainy
elif weather == "rainy":
    print("It's raining. Remember to bring an umbrella!")

# Print when other conditions
else:
    print("Likely chilly. Wear a jacket!")

ผลลัพธ์:

Likely chilly. Wear a jacket!

อธิบาย code:

  • if block: ประเมินว่า weather เป็น "sunny" ไหม ถ้าใช่ จะ print "It's a sunny day. Don't forget your sunscreen!"
  • elif block: weather เป็น "rainy" ไหม ถ้าใช่ จะ print "It's raining. Remember to bring an umbrella!"
  • else block: ถ้า weather เป็นค่าอื่น ๆ (เช่น "snowy") จะ print "Likely chilly. Wear a jacket!"

เพราะ weather มีค่าตรงกับ else block เราจึงได้ผลลัพธ์เป็น "Likely chilly. Wear a jacket!"


🌊 3. Control Flow Statements

Control flow statements ใช้ควบคุมลำดับการทำงานของ code และมีอยู่ 2 แบบ ได้แก่:

  1. for: รัน code ตามจำนวนข้อมูลที่มี
  2. while: รัน code จนกว่าเงื่อนไขจะไม่เป็นจริง

📦 (1) for Loop

ตัวอย่าง for loop เช่น print ชื่อแขกในงาน:

# Guest list
guests = ["James Bond", "John Wick", "Jack Reacher", "Jason Bourne", "Jack Ryan"]

# Print guest names
for name in guests:
    
    # Print name
    print(name)

ผลลัพธ์:

James Bond
John Wick
Jack Reacher
Jason Bourne
Jack Ryan

อธิบาย code:

  • guest = ...: สร้าง list เก็บรายชื่อแขก
  • for ...: นำชื่อแขกใน list มา print จนกว่าจะครบทุกคน

🔁 (2) while Loop

ตัวอย่าง while loop เช่น นับเลข 1 ถึง 10:

# Starting number
number = 1

# Count to 10
while number <= 10:
    
    # Print number
    print(number)
    
    # Add 1 to number
    number += 1

ผลลัพธ์:

1
2
3
4
5
6
7
8
9
10

อธิบาย code:

  • number = 1: กำหนดเลขเริ่มต้น
  • while ...: print number และปรับ number ให้สูงขึ้น 1 ค่า ทำอย่างนี้วนไปจนกว่า number จะมากกว่า 10 (number <= 10 ไม่เป็นจริง)

🚄 4. Loop Control Statements

Loop control statements ใช้ควบคุมการทำงานของ control flow และมีอยู่ 3 แบบ ได้แก่:

  1. continue: skip ไป item ถัดไป
  2. break: หยุดการทำงานของ control flow
  3. pass: placeholder สำหรับใส่ code ในอนาคต

ยกตัวอย่างเช่น เรามีรายการของที่ต้องซื้อ และแต่ละอย่างมี action ไม่เหมือนกัน:

# A shopping list program
shopping_list = ["milk", "bread", "chips", "apple", "toothpaste", "chocolate"]

# Loop through the list
for item in shopping_list:

    # Skip item if chip
    if item == "chips":
        print("Chips are unhealthy. Skipping ...")
        continue
    
    # Stop the loop if toothpaste
    if item == "toothpaste":
        print("Found toothpaste, done shopping early!")
        break
    
    # Do nothing if milk
    if item == "milk" or item == "bread":
        pass
    
    # Print item
    print("Putting", item, "into the cart.")

ผลลัพธ์:

Putting milk into the cart.
Putting bread into the cart.
Chips are unhealthy. Skipping ...
Putting apple into the cart.
Found toothpaste, done shopping early!

อธิบาย code:

  • shopping_list = ...: สร้าง list เก็บรายการซื้อของ
  • if item == "chips" block: ประเมินว่า item ใช่ "chip" ไหม ถ้าใช่ ให้ print "Chips are unhealthy. Skipping ..." และข้ามไป item ถัดไป (continue)
  • if item == "toothpaste" block: ประเมินว่า item ใช่ "toothpaste" ไหม ถ้าใช่ ให้ print "Found toothpaste, done shopping early!" และจบ loop ทันที (break)
  • if item == "milk" … block: ประเมินว่า item ใช่ "milk" หรือ "bread" ไหม ถ้าใช่ ไม่ต้องทำอะไร (pass)
  • print ...: print ว่า กำลังเอา item ใส่ตระกร้า

สังเกตว่า:

  • มีแค่ milk, bread, apple ที่ “กำลังใส่ตระกร้า” เพราะ milk และ bread อยู่ใน pass block และ apple ไม่ได้อยู่ใน block ไหนเลย
  • Chip ถูกข้ามไป เพราะอยู่ใน continue block
  • Toothpaste อยู่ใน break block และมาก่อน chocolate ทำให้เราไม่เห็น chocolate เพราะ toothpaste

💪 5. Summary

ในบทความนี้ เราได้ไปดูวิธีการเขียน code ใน Python เพื่อให้ code ตัดสินใจได้:

Comparison operators:

OperatorDescription
==เท่ากับ
!=ไม่เท่ากับ
>มากกว่า
>=มากกว่า/เท่ากับ
<น้อยกว่า
<=น้อยกว่า/เท่ากับ

Logical operators:

OperatorDescription
andLogical AND
orLogical OR
notLogical NOT

Conditional statements:

StatementDescription
ifกำหนดเงื่อนไขแรก
elifกำหนดเงื่อนไขเพิ่มเติม
elseทำ action เมื่อเข้าเงื่อนไขอื่น ๆ

Control flow statements:

StatementDescription
forวนจนครบทุก item
whileวนจนกว่าเงื่อนไขจะเป็น False

Loop control statements:

StatementDescription
continueSkip
breakStop
passDo nothing

😺 GitHub

ดูตัวอย่าง code ทั้งหมดได้ที่ GitHub


📃 References

Comments

One response to “if, for, while ใน Python: วิธีใช้ conditional statements, control flow, และ loop control ใน Python พร้อมตัวอย่าง”

  1. Python for AI: รวบรวม 8 บทความการทำงานกับ AI ด้วย Python – Shi no Shigoto Avatar

    […] Control flow: สอนใช้ statement เช่น if, for, while เพื่อควบคุมการทำงานของ Python […]

    Like

Leave a reply to Python for AI: รวบรวม 8 บทความการทำงานกับ AI ด้วย Python – Shi no Shigoto Cancel reply