Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Python Conditional Statements: if, else, elif คู่มือครบวงจร

การตัดสินใจ (Decision Making) ใน Python ใช้ if, elif, else โครงสร้างควบคุมการทำงานของโปรแกรม

1. If Statement (พื้นฐาน)

# Syntax
if condition:
    statement

# Example
password = 'Hello'
if len(password) < 6:
    print('Password too weak - at least 6 characters')
# Output: Password too weak - at least 6 characters

⚠️ จดจำ: Python ใช้ Indentation (เว้นวรรค) แทน { } และมี Colon (:) ท้ายเงื่อนไข

Logical Operators (ตัวดำเนินการตรรกะ)

Operatorหมายความตัวอย่าง
==Equalsa == b
!=Not Equalsa != b
<Less thana < b
<=Less than or equala <= b
>Greater thana > b
>=Greater than or equala >= b
andLogical ANDa > 0 and a < 10
orLogical ORa < 0 or a > 10
notLogical NOTnot condition

2. If...Else Statement

password = 'Mission'  # 7 characters
if len(password) < 6:
    print('Password too weak')
else:
    print('Password accepted')
# Output: Password accepted

3. Multiple If...Else with Elif

elif = else if ใช้เมื่อมีเงื่อนไขมากกว่า 2 กรณี

# ตรวจสอบประเภทสามเหลี่ยม
a, b, c = 5, 5, 5

if a != b and b != c and a != c:
    print('Scalene triangle')      # ทุกด้านต่างกัน
elif a == b and b == c:
    print('Equilateral triangle')  # ทุกด้านเท่ากัน
else:
    print('Isosceles triangle')    # 2 ด้านเท่ากัน

# Output: Equilateral triangle
  • ใช้ elif ได้ไม่จำกัดจำนวน
  • มี else เพียง 1 ตัว (Catch-all)
  • เงื่อนไขถูกตรวจสอบจากบนลงล่าง หยุดเมื่อเจอเงื่อนไขที่ True แรก

4. Ternary Operator (Shorthand If...Else)

เขียน If-Else ในบรรทัดเดียว

# Syntax: value_if_true if condition else value_if_false

a, b = 100, 200
result = 'A' if a > b else 'B'
print(result)  # B

# ใช้กับการกำหนดค่า
status = "Adult" if age >= 18 else "Minor"
discount = 0.1 if is_member else 0.0

5. Nested If (If ใน If)

age = 25
has_license = True

if age >= 18:
    if has_license:
        print("Can drive")
    else:
        print("Need license")
else:
    print("Too young")

6. Match-Case (Python 3.10+ - Switch Statement)

status = 404

match status:
    case 200:
        print("OK")
    case 404:
        print("Not Found")
    case 500:
        print("Server Error")
    case _:  # Default (wildcard)
        print("Unknown status")

# Output: Not Found

Truthy และ Falsy Values

ใน Python ค่าต่อไปนี้ถือว่า Falsy (เป็น False ในเงื่อนไข):

  • False, None, 0, 0.0
  • Empty sequences: "", (), [], {}

ค่าอื่นๆ ทั้งหมดเป็น Truthy

name = ""
if name:           # False เพราะ empty string
    print("Has name")
else:
    print("No name")  # พิมพ์บรรทัดนี้

บทความเกี่ยวข้อง