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

Python Variables: คู่มือการประกาศ ใช้งาน และ Best Practices

ตัวแปร (Variables) ใน Python เป็นชื่อที่อ้างอิงไปยัง Object ใน Memory ไม่ต้องประกาศ Type ไปล่วงหน้า (Dynamic Typing)

กฎการตั้งชื่อตัวแปร (Naming Rules)

  • ✅ เริ่มต้นด้วย ตัวอักษร (a-z, A-Z) หรือ Underscore (_)
  • ✅ ต่อด้วย ตัวอักษร, ตัวเลข (0-9), Underscore
  • ✅ Case-sensitive: name, Name, NAME ต่างกัน
  • ❌ ห้ามเริ่มต้นด้วยตัวเลข
  • ❌ ห้ามมี Space หรือ Special characters (!@#$%^&*)
  • ❌ ห้ามใช้ Python Keywords

Python Keywords (ห้ามใช้เป็นชื่อตัวแปร)

False  class  finally  is     return
None   continue for    lambda try
True   def    from   nonlocal while
and    del    global not    with
as     elif   if     or     yield
assert else   import pass
break  except in     raise

การกำหนดค่า (Assignment)

# Valid variable names
name = "John"
error_404 = 404
_status_200 = "OK"
mySurname = "Doe"
SURNAME = "Doe"
surname2 = "Doe"

# Invalid variable names (SyntaxError)
# 200_OK = 200      # เริ่มต้นด้วยตัวเลข
# error-500 = "..." # มี hyphen
# my var = "John"   # มี space
# $myname = "John"  # มี $

Multiple Assignment (กำหนดค่าหลายตัวพร้อมกัน)

ค่าต่างกัน

ok, redirect, server_error = 200, 300, 500
print(ok, redirect, server_error)  # 200 300 500

ค่าเดียวกันหลายตัวแปร

err_500 = err_501 = err_502 = "server_error"
print(err_500, err_501, err_502)  # server_error server_error server_error

Swap Values (แลกเปลี่ยนค่า)

a = 10
b = 20
a, b = b, a  # Pythonic swap!
print(a, b)  # 20 10

Variable Scope (ขอบเขตตัวแปร)

Global Variables

status_ok = 200  # Global variable

def status_code():
    print("Status code is", status_ok)  # เข้าถึง global ได้

status_code()  # Status code is 200

Local Variables

status = 200  # Global

def status_code():
    status = 401  # Local variable (แยกจาก global)
    print("Inside:", status)  # Inside: 401

status_code()
print("Outside:", status)  # Outside: 200 (global ไม่เปลี่ยน)

Global Keyword (แก้ไข Global ภายใน Function)

status = 200

def status_code():
    global status      # บอก Python ให้ใช้ global variable
    status = 401
    print("Inside:", status)  # Inside: 401

status_code()
print("Outside:", status)  # Outside: 401 (global เปลี่ยนแล้ว!)

Best Practices

แนวทางตัวอย่าง
ใช้ snake_case สำหรับตัวแปร/ฟังก์ชันuser_name, get_user()
ใช้ UPPER_CASE สำหรับ ConstantsMAX_RETRY = 3, API_URL = "..."
ตั้งชื่อให้มีความหมายuser_count แทน cnt
หลีกเลี่ยงตัวแปร Global มากเกินไปใช้ Parameter/Return แทน
ใช้ Type Hints (Python 3.5+)name: str = "John"

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