การตัดสินใจ (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 | หมายความ | ตัวอย่าง |
|---|---|---|
== | Equals | a == b |
!= | Not Equals | a != b |
< | Less than | a < b |
<= | Less than or equal | a <= b |
> | Greater than | a > b |
>= | Greater than or equal | a >= b |
and | Logical AND | a > 0 and a < 10 |
or | Logical OR | a < 0 or a > 10 |
not | Logical NOT | not 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") # พิมพ์บรรทัดนี้