10 mẹo Python giúp code ngắn gọn và chuyên nghiệp hơn

Viết code Pythonic

Dưới đây là 10 mẹo giúp code Python trở nên chuyên nghiệp hơn.

1. F-string formatting

name = "Python"
print(f"Xin chào {name}, phiên bản {3.12}")
print(f"Giá: {price:,.0f} VNĐ")

2. Unpacking thông minh

a, b = b, a  # Swap
first, *middle, last = [1, 2, 3, 4, 5]

3. Dictionary merge (3.9+)

config = default | custom

4. Walrus operator :=

if (n := len(data)) > 100:
    print(f"Dữ liệu lớn: {n} phần tử")

5. enumerate thay range(len())

for i, fruit in enumerate(fruits, start=1):
    print(i, fruit)

6. zip để duyệt song song

for name, score in zip(names, scores):
    print(f"{name}: {score} điểm")

7. any() và all()

print(all(a >= 18 for a in ages))
print(any(a >= 18 for a in ages))

8. Counter từ collections

from collections import Counter
count = Counter(words)
print(count.most_common(2))

9. pathlib thay os.path

from pathlib import Path
config = Path.home() / ".config" / "myapp" / "settings.json"

10. Type hints

def tinh_thue(thu_nhap: float, ty_le: float = 0.1) -> float:
    return thu_nhap * ty_le

Áp dụng những mẹo này sẽ giúp bạn viết Python ngắn gọn và chuyên nghiệp hơn. Happy coding! 🐍

Chia sẻ bài viết: