Google Colab is a browser-based notebook environment for running Python code without installing Python on your local computer.
A Colab notebook can contain Python code, text, tables, charts and output in the same .ipynb file. Notebooks can also be stored in Google Drive and shared with other users.
Colab is useful for Python learning, Pandas and NumPy exercises, data analysis, machine learning experiments, API projects, charts, database work and other notebook-based applications.
Show Table of ContentsGoogle Colab, short for Google Colaboratory, provides a notebook environment that runs Python code in a cloud-based runtime.
Instead of creating a local Python environment first, a beginner can open a notebook in a browser, add a code cell and start running Python.
A notebook can contain:
Popular Python libraries such as Pandas and NumPy are commonly available in the Colab environment and can be imported directly.
.ipynb file.
A Colab notebook can be created from Google Drive.
New > More > Google Colaboratory
If Google Colaboratory is not listed, use:
New > More > Connect more apps
Search for Google Colaboratory and connect it to Drive.
Existing notebooks can also be opened or uploaded through Colab.
Create a code cell and enter:
print('Hello from Google Colab')
Output
Hello from Google Colab
Variables, loops, functions and other Python code work in the same way as in a normal Python environment.
name='Alex'
print(
f'Welcome {name}'
)
Use this shell command inside a code cell:
!python --version
The displayed Python version depends on the current Colab runtime.
Many libraries are already installed.
To view installed packages:
%pip list
To inspect one package:
%pip show pandas
To install a package:
%pip install package_name
For example:
%pip install pytrends
try:
import reportlab
found=True
except ImportError:
found=False
print(found)
The try and except statement allows the program to handle a missing package without immediately stopping.
Files stored directly in the Colab runtime are temporary.
For example, a downloaded file may appear under:
/content/
These runtime files can disappear when the runtime is reset, disconnected or replaced.
from google.colab import files
uploaded=files.upload()
The returned uploaded object contains the uploaded file data.
from google.colab import files
files.download(
'fish-market.jpg'
)
from google.colab import files
with open(
'data1.txt',
'w'
) as file:
file.write(
'This text was created in Google Colab.'
)
files.download(
'data1.txt'
)
Files that must remain available after the current runtime ends can be stored in Google Drive.
Mount Drive using:
from google.colab import drive
drive.mount(
'/content/drive'
)
Colab will request permission to access the selected Google Drive account.
After authorization, Drive files are normally available below:
/content/drive/MyDrive/
The Files panel can be used to browse folders and copy the path of a required file.
After mounting Drive, Pandas can read CSV and Excel files directly.
import pandas as pd
path='/content/drive/MyDrive/Colab Notebooks/downloads/my_file.xlsx'
my_data=pd.read_excel(
path
)
print(
my_data.head()
)
See the detailed Pandas read_excel() tutorial.
import pandas as pd
path='/content/drive/MyDrive/Colab Notebooks/downloads/student.csv'
my_data=pd.read_csv(
path
)
print(
my_data.head()
)
See the Pandas read_csv() tutorial.
A file available through a direct URL can be downloaded to the current Colab runtime with wget.
!wget https://www.plus2net.com/python/download/my_db.db
Other examples:
!wget https://www.plus2net.com/python/download/student.xlsx
!wget https://www.plus2net.com/python/download/student.csv
These downloaded files belong to the current runtime unless you copy them to persistent storage such as Google Drive.
Colab supports normal Python together with shell commands and notebook magic commands.
| Command | Purpose |
|---|---|
%pip install package |
Install a Python package in the notebook environment |
%pip list |
List installed Python packages |
%pip show package |
Display information about a package |
!python --version |
Display the Python version |
!pwd |
Display the current working directory |
!ls |
List files and directories |
%cd path |
Change the notebook working directory |
!mkdir folder |
Create a directory |
!cp source destination |
Copy a file |
!mv old new |
Move or rename a file |
!rm filename |
Remove a file |
!wget URL |
Download a file from a URL |
!curl URL |
Retrieve content using curl |
!nvidia-smi |
Display NVIDIA GPU information when a compatible GPU runtime is active |
%%time |
Measure the execution time of a cell |
%%capture |
Capture or suppress cell output |
!python script.py |
Run a Python script file |
! for shell commands, % for line magic commands and %% for cell magic commands.
The ipywidgets library can add sliders, buttons, dropdown lists, checkboxes, text inputs, file uploads, progress bars and other interactive controls to notebook interfaces.
For example:
import ipywidgets as widgets
from IPython.display import display
slider=widgets.IntSlider(
value=50,
min=0,
max=100,
description='Value:'
)
display(slider)
The dedicated tutorial covers interact(), observe(), on_click(), layout containers, file uploads and linked widgets.
Once the basic Colab workflow is understood, the same notebook environment can be used for larger Python projects.
This project uses Python Requests to retrieve the latest available mutual fund NAV through MFAPI. It then expands the same workflow to multiple schemes, historical NAV charts, portfolio valuation, Excel input and scheduled automation.
Mutual Fund NAV Tracking with Python and MFAPIBuild notebook forms with text boxes, dropdowns, buttons and other interactive controls.
Data Entry Form with Colab and ipywidgetsColab can connect to SQLite database files and use them together with Pandas.
SQLite Database Using Google ColabPython libraries can generate PDF files from notebook data and database content.
Generate PDF Files in Google ColabSecrets and API calls can be combined to create AI-based Python notebook projects.
Using Gemini API in Google ColabSupported Colab environments can include AI-assisted features for working with code and data.
Depending on the available interface and account features, these tools can assist with tasks such as:
Because Colab features can change over time, the exact buttons and interface available in a notebook may differ.
The Plus2net example notebook demonstrates using an AI data-analysis workflow with the student database exercise.
Open the Data Analysis NotebookSQLite is a file-based database, so a database file can be stored in Google Drive or uploaded to the current Colab runtime.
Python can then connect to the SQLite database, run queries and transfer data between SQLite, Pandas, Excel and other formats.
Use SQLite Database from Google Drive with ColabPython libraries can create PDF documents in a Colab notebook using text, tables, images and dynamic data.
The PDF can then be downloaded to the local computer or saved to Google Drive.
Generate PDF Files in Google ColabAPI keys, passwords and other credentials should not be written directly into notebook code that may be shared.
Google Colab provides a Secrets area where sensitive values can be stored separately from the Python cells.
Add a secret name, such as:
OPENAI_API_KEY
and store its value in the Secrets panel.
from google.colab import userdata
api_key=userdata.get(
'OPENAI_API_KEY'
)
import os
from google.colab import userdata
os.environ['OPENAI_API_KEY']=userdata.get(
'OPENAI_API_KEY'
)
Notebook access to a stored secret should only be enabled for notebooks that need it.
.ipynb file.!python --version to check the active Python version.%pip install to install additional Python packages.files.upload() and files.download() for local file transfer.wget can download files directly into the runtime.Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.