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

การกำหนดค่าตัวแปร (Variable Assignment) ใน Python

Python มีหลายวิธีในการกำหนดค่าตัวแปร

1. Direct Assignment (การกำหนดโดยตรง)

x = 5
x = 9  # ค่าใหม่ทับค่าเก่า
print(x)  # 9

2. Multiple Assignment (หลายตัวแปรพร้อมกัน)

a, b, c = 1, 2, 3
x = y = z = 0  # ทั้งสามตัว = 0

3. Conditional Assignment (Ternary Operator)

x = 12
y = 13 if x > 8 else 0
print("Value of y is:", y)  # 13

4. Unpacking Assignment

# จาก List/Tuple
coordinates = [10, 20]
x, y = coordinates

# Swap variables
a, b = 5, 10
a, b = b, a  # a=10, b=5

5. Walrus Operator (Python 3.8+)

# Assignment expression
if (n := len([1, 2, 3])) > 2:
    print(f"Length is {n}")  # Length is 3

ข้อควรระวัง

  • ตัวแปรใน Python เป็น Reference ไม่ใช่กล่องเก็บค่า
  • x = [1,2,3]; y = x → y และ x ชี้ไปออบเจ็กต์เดียวกัน
  • ใช้ copy() หรือ [:] ถ้าต้องการสำเนาจริง