Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Cách chạy code Python trên Google Colaboratory (Colab)

Google Colaboratory (Colab) là môi trường Jupyter Notebook miễn phí, chạy trên đám mây Google, không cần cài đặt, hỗ trợ GPU/TPU miễn phí. Rất phù hợp cho Machine Learning, Data Science, học tập.

1. Mở Colab

  1. Truy cập: colab.research.google.com
  2. Đăng nhập Google Account (nếu chưa).
  3. Chọn New Notebook (Python 3) ở góc dưới phải.

Cách chạy code Python trên Google Colaboratory (Colab)

2. Giao diện Notebook

Tương tự Jupyter: ô Code (code cell) và ô Text (Markdown cell).

  • Code cell: Viết và chạy Python.
  • Text cell: Viết markdown, giải thích, tiêu đề.
  • Thêm cell: + Code / + Text hoặc phím tắt.

Cách chạy code Python trên Google Colaboratory (Colab)

3. Viết và chạy code Python

# Ví dụ: Import thư viện, vẽ biểu đồ
import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 10, 100)
y = np.sin(x)

plt.figure(figsize=(8, 4))
plt.plot(x, y)
plt.title("Sine Wave on Colab")
plt.show()

Cách chạy code Python trên Google Colaboratory (Colab)

4. Chạy code

  • Nhấn nút Play (▶) bên trái cell.
  • Phím tắt: Ctrl+Enter (chạy cell), Shift+Enter (chạy + tạo cell mới), Alt+Enter (chạy + chèn cell dưới).
  • Kết quả hiển thị ngay dưới cell.

Cách chạy code Python trên Google Colaboratory (Colab)

Tính năng nổi bật

Tính năngMô tả
GPU/TPU miễn phíRuntime → Change runtime type → GPU/TPU
Mount Google Drivefrom google.colab import drive; drive.mount('/content/drive')
Cài package!pip install package_name (dấu ! chạy shell)
Upload fileIcon folder bên trái → upload, hoặc from google.colab import files; files.upload()
Chia sẻShare link (view/edit/comment) như Google Docs
ExportFile → Download .ipynb / .py / .html / .pdf

Kết luận

Colab là công cụ đắc lực cho Data Science/ML: zero-setup, free GPU, dễ chia sẻ, tích hợp Google Drive. Lý tưởng cho học tập, prototype, demo.