4.2 Introduction to Python#

Python is the most widely used programming language in modern scientific research. It is used for:

  • Data analysis and visualization

  • Machine learning and AI

  • Bioinformatics and computational biology

  • Chemistry and materials science

  • Automation of repetitive tasks

  • Scientific simulations

Python is popular because it is easy to read, has a large ecosystem of scientific libraries, and works well with modern AI tools.

4.2.1 Installing Python#

The easiest way to get started is by installing:

  • Anaconda (recommended for scientific computing)

  • Miniconda (lighter alternative)

After installation, you can write Python code in:

  • Jupyter Notebook

  • JupyterLab

  • VS Code

  • Google Colab (runs in your browser, no installation needed)

Video: Installation walkthrough for Windows, for Mac.

4.2.2 Write Your First Python Program#

Python scripts are saved with .py extension. You can create a file named hello.py write print("Hello, world!") in it.

To run the code you only have to do python hello.py in your terminal. You will see the following output.

Video: running python scripts on Windows, on Mac

Additionally, you can test the code snippets by launching this notebook using the rocket (🚀) button at the top of the page. What’s the output you see when you run the following cell?

print("Hello, world!")

Integrated development environments (IDEs)#

While Python code can be written in a simple text editor, most programmers use an Integrated Development Environment (IDE). An IDE provides tools that make coding easier, including syntax highlighting, code completion, debugging, and project management.

For beginners, a popular choice is Visual Studio Code (VS Code), a free and lightweight editor that supports Python development through extensions. Other commonly used options include PyCharm, JupyterLab, and Google Colab. You are most likely using Google Colab in this tutorial series. But if you want to run scripts in your local computer it is highly recommended that you use an IDE.

Benefits of using an IDE include:

  • Highlighting syntax errors as you type

  • Auto-completing variable and function names

  • Running and debugging code with a single click

  • Managing larger projects and files

  • Integrating with version control systems such as Git

As your programs become more complex, an IDE can significantly improve productivity and help you identify errors more quickly.

Video: Getting started with VS code - Link

AI-assisted coding with cursor#

In recent years, AI-powered code editors have become popular tools for learning and programming. One example is Cursor, an editor built on top of VS Code that includes AI features for writing, explaining, and debugging code.

With Cursor, you can:

  • Ask questions about your code in natural language

  • Generate code from a description of a task

  • Get explanations of unfamiliar functions or error messages

  • Refactor or improve existing code

  • Work with larger codebases more efficiently

For scientists who are new to programming, Cursor can act like an on-demand tutor, helping you understand code and overcome common obstacles. However, it is important to review AI-generated code carefully and understand what it is doing rather than copying it blindly.

You can learn more on how to use Cursor by watching this video tutorial.

Tip: Use AI tools to accelerate learning, but always verify results and test code yourself.

Now let’s shift gears and take a much more detailed look into writing python codes.

4.2.3 Variables in Python#

Variables are used to store information that can be referenced and manipulated later in a program. You can think of a variable as a labeled container that holds a value, such as a number, a piece of text, or a collection of data.

Variables make programs more flexible because you can reuse values throughout your code without repeatedly typing them. To create a variable, use the = operator to assign a value to a name.

Let’s create a few variable names and assign values.

name = "Alice"
age = 30
temperature = 37.5

Now you can display stored values using print statements.

print(name)
print(age)

4.2.4 Basic Data Types#

Every value stored in Python has a data type. The data type determines what kind of information is stored and what operations can be performed on it.

Some of the most common data types include numbers, text (strings), and Boolean values (True/False). Understanding data types is important because they form the foundation of how Python stores and processes information.

Numbers#

Numbers are used to represent quantitative values. Python supports both integers (whole numbers) and floating-point numbers (numbers with decimal places). In the following example, x is an integer and y is a floating-point number.

x = 10
y = 3.5

Strings#

gene = "TP53"

Booleans#

is_significant = True

4.2.5 Basic Arithmetic#

Python can perform mathematical calculations just like a calculator. Arithmetic operations are useful in many scientific applications, including data analysis, statistical calculations, unit conversions, and numerical simulations.

The most common arithmetic operators are:

Operator

Description

Example

+

Addition

2 + 3

-

Subtraction

5 - 2

*

Multiplication

4 * 3

/

Division

10 / 2

**

Exponentiation

2 ** 3

%

Remainder (modulo)

10 % 3

a = 10
b = 3

print(a + b)
print(a - b)
print(a * b)
print(a / b)

4.2.6 Data Structures#

As programs become more complex, we often need to store and organize collections of data rather than individual values. Data structures are ways of organizing data so that it can be accessed, modified, and analyzed efficiently.

Python provides several built-in data structures, each designed for different use cases. Some of the most common are:

  • Lists: ordered collections of items

  • Dictionaries: collections of key-value pairs

  • Tuples: ordered collections that cannot be modified after creation

  • Sets: unordered collections of unique items

In scientific computing, data structures are used to store measurements, gene names, experimental results, sequences, and many other types of data. Choosing the appropriate data structure can make code easier to write and understand.

Lists#

Lists store multiple values. Python uses zero-based indexing, which means the first element has index 0, the second has index 1, the third has index 2, and so on. That’s why print(genes[0]) returns the first element in the following list.

genes = ["TP53", "BRCA1", "EGFR"]

print(genes[0])

Dictionaries#

Dictionaries are data structures that store information as key-value pairs. Instead of accessing values by their position (as in a list), values in a dictionary are accessed using a unique key.

Dictionaries are useful when you want to associate one piece of information with another. For example, you might store gene expression values, sample metadata, or experimental measurements where each value has a meaningful label.

Unlike lists, dictionaries do not use numerical indexing. Instead, each value is accessed using its associated key, making dictionaries particularly useful for storing labeled scientific data.

In the following example, the keys are gene names (“TP53” and “BRCA1”), and the values are their corresponding expression levels. To retrieve a value, you provide its key inside square brackets.

expression = {
    "TP53": 12.5,
    "BRCA1": 8.3
}

print(expression["TP53"])

Conditional Statements#

Conditional statements allow your program to make decisions based on whether a condition is true or false. They are commonly used in scientific analysis to filter data, apply thresholds, or trigger different actions depending on the results.

In this example, the code checks whether the p-value is below the commonly used significance threshold of 0.05 and prints the appropriate message.

p_value = 0.03

if p_value < 0.05:
    print("Statistically significant")
else:
    print("Not significant")

4.2.7 Loops#

Loops allow you to repeat the same operation multiple times without rewriting code. This is especially useful when working with datasets, collections of genes, proteins, samples, or experimental measurements.

For Loop#

A for loop iterates over each item in a collection, such as a list. It is one of the most common ways to process scientific data in Python. This loop visits each gene in the list and prints its name.

genes = ["TP53", "BRCA1", "EGFR"]

for gene in genes:
    print(gene)

While Loop#

A while loop continues running as long as a condition remains true. These loops are useful when you do not know beforehand how many iterations will be needed.

The following loop prints the numbers 0 through 4 and stops once count reaches 5. The statement count += 1 increments the value of count during each iteration, ensuring that the loop eventually terminates.

count = 0

while count < 5:
    print(count)
    count += 1

4.2.8 Functions#

As programs grow larger, it becomes useful to group related code into reusable blocks called functions. Functions allow you to perform a specific task whenever needed without rewriting the same code multiple times.

Functions make code easier to read, maintain, and debug. They are especially useful in scientific programming, where the same calculations or analyses may need to be applied repeatedly to different datasets.

A function can accept inputs (called parameters), perform some computation, and optionally return a result.

# We define a function with `def` keyword and a name for the function.
# This function takes an input `x` and returns the square of `x`.
def square(x):
    y = x * x
    return y

result = square(4)
print(result)

4.2.9 Python Best Practices#

  • Use meaningful variable names.

  • Write small, reusable functions.

  • Add comments when needed.

  • Test code frequently.

  • Read error messages carefully.

  • Use version control (Git) for larger projects.

4.2.10 Importing Libraries#

Python’s power comes from its libraries. A library is a collection of pre-written code that provides additional functionality, allowing you to perform complex tasks without writing everything from scratch.

Scientists rarely use “plain” Python alone. Instead, they rely on specialized libraries for tasks such as data analysis, visualization, machine learning, and scientific computing. By importing a library, you gain access to tools developed and tested by large scientific and engineering communities.

Common scientific libraries:

Library

Purpose

NumPy

Numerical computing

Pandas

Data analysis

Matplotlib

Visualization

Seaborn

Statistical plots

SciPy

Scientific computing

Scikit-learn

Machine learning

import math

print(math.sqrt(16))

Before you import any packages, make sure they’re installed. If you’re using Google colab, you can use the following cell to install the packages.

! pip install numpy pandas matplotlib seaborn scipy scikit-learn

4.2.11 Working with Data#

One of the main reasons scientists use Python is its ability to work efficiently with data. Experimental results, survey responses, genomic datasets, and simulation outputs are often stored in tabular formats such as CSV (Comma-Separated Values) files.

Rather than manually inspecting spreadsheets, Python allows you to load, filter, analyze, and visualize data programmatically. This makes analyses more reproducible, scalable, and easier to share with others.

The Pandas library is one of the most popular tools for data analysis in Python. It provides a data structure called a DataFrame, which is similar to a spreadsheet or table where rows represent observations and columns represent variables. Read more on Pandas Dataframes here.

Here’s a simple example using Pandas:

import pandas as pd

data = {
    "gene": ["TP53", "BRCA1"],
    "expression": [12.5, 8.3]
}

df = pd.DataFrame(data)

print(df.head())

Plotting Data#

Visualizing data is an important part of scientific analysis. Graphs and charts can help reveal patterns, trends, outliers, and relationships that may not be obvious when looking at raw numbers alone.

Python provides several libraries for creating visualizations, with Matplotlib being one of the most widely used. It allows you to create a variety of plots, including line graphs, scatter plots, histograms, and bar charts.

The example below creates a simple line plot showing the relationship between two variables:

import matplotlib.pyplot as plt

x = [1, 2, 3, 4]
y = [2, 4, 6, 8]

plt.plot(x, y)
plt.xlabel("X")
plt.ylabel("Y")
plt.show()

4.2.12 Additional Resources#