Lecture 1: Getting Started
with Python

From learning mindset to lab calculation automation

πŸ“šWhat We'll Cover Today

β†’

How to Learn Python

Effective strategies and mindset for coding success

β†’

Basic Introduction to Python

What Python is and why it's perfect for biology

β†’

Breaking Down Problems

Essential skill for tackling coding projects

β†’

Python Fundamentals

Variables, data types, lists, loops, and functions

πŸ§ͺOur First Project

βœ“

Lab Solution Calculator

Automate the calculation of volumes needed for making 10mM solutions from different reagents

βœ“

Real Problem Solving

Help 'Alex' process 100 bottles efficiently using Python instead of manual calculations

βœ“

Step-by-Step Approach

Learn to break down complex problems into manageable, programmable steps

Why Learning to Code?

πŸ€– The AI Revolution: A Double-Edged Sword

AI may be challenging news for professional software engineers, but it's incredibly empowering for everyone elseβ€”especially scientists.

πŸš€Boost Your Productivity

βœ“

Automate Repetitive Tasks

Stop doing manual calculations and data processingβ€”let code do it for you

βœ“

Work Smarter, Not Harder

A little coding knowledge can save hours of tedious work in the lab

βœ“

Scale Your Analysis

Process hundreds or thousands of samples with the same effort as one

πŸ“ŠDeepen Your Data Skills

βœ“

Advanced Data Analysis

Go beyond Excelβ€”perform sophisticated statistical analyses

βœ“

Custom Visualizations

Create publication-quality figures tailored to your data

βœ“

Reproducible Research

Make your analysis transparent and repeatable

🧠Use AI More Intelligently

βœ“

Understand AI Output

Know when AI-generated code is correct or nonsense

βœ“

Effective Collaboration

Work with AI tools as a knowledgeable partner, not a blind follower

βœ“

Debug and Adapt

Fix and customize AI-generated solutions for your specific needs

πŸ’ΌGain a Competitive Edge

βœ“

Unique Skill Combination

Coding skills + specialist biological expertise = rare and valuable

βœ“

Job Market Advantage

Stand out in academia, biotech, pharma, and beyond

βœ“

Future-Proof Your Career

Computational skills are increasingly essential in all scientific fields

Coding will be an essential side kick for your future career.
Let's get you ready for it.

How to Learn (and Teach) Python

The Truth About Learning to Code

You cannot learn Python from lectures. My aim is to show you what's possible and give you the tools to build projects useful for your studies. But you must do the work - actually write code, make mistakes, debug, and learn.

πŸ“š What We Provide

βœ“

Resources & Notebooks:

Ready-to-use examples

βœ“

Lab Sessions:

Hands-on practice time

βœ“

Slack Channel:

Community support

βœ“

Real Bio Problems:

Practical applications

πŸ’ͺ What You Must Do

β†’

Type Code Yourself:

No copy-paste learning

β†’

Embrace Errors:

They're how you learn

β†’

Build Projects:

Apply what you learn

β†’

Practice Daily:

Consistency is key

πŸ”‘ The Golden Rule

Practice writing code YOURSELF and work on YOUR OWN PROJECTS!

πŸ’ͺ

You don't get fit by watching fitness videos

🎸

You don't learn guitar by watching YouTube

πŸ’»

You don't learn coding by following a lecture

Your Potential Outcomes

Worst Case Scenario

Overview of Python applications for biology - still valuable knowledge!

Best Case Scenario

Start your coding journey, solve real problems, build useful projects!

AI & LLMs: A Double-Edged Sword

βœ…The Blessing

β€’

24/7 Teacher:

Get explanations anytime

β€’

Skilled Buddy:

Debug and optimize code together

β€’

Idea Explorer:

Discover alternative solutions

⚠️The Curse

β€’

Copy-Paste Trap:

No learning happens

β€’

Shallow Understanding:

Miss core concepts

β€’

Dependency:

Can't code without AI help

🎯The Right Approach

DO: Write β†’ Test β†’ Debug β†’ Ask AI β†’ Understand β†’ Improve

DON'T: Ask AI β†’ Copy β†’ Paste β†’ Submit

Where Python Fits In

LanguageType SystemExecutionBest ForLearning Curve
Python 🐍DynamicInterpretedData Science, AI, Web, Automationβ—‰β—―β—―β—―β—― Easy
RDynamicInterpretedStatistics, Data Analysisβ—‰β—‰β—―β—―β—― Moderate
JavaScriptDynamicInterpreted/JITWeb Developmentβ—‰β—‰β—―β—―β—― Moderate
JavaStaticCompiled (bytecode)Enterprise, Androidβ—‰β—‰β—‰β—―β—― Challenging
C++StaticCompiledSystems, Games, Performanceβ—‰β—‰β—‰β—‰β—― Difficult

Python is the 2nd best language for everything!

🐍

The Story of Python

1989

Guido starts Python as a hobby project during Christmas break

1991-2005: The Scripting Era

Python starts as a simple scripting language for automation and system administration

2006-2011: Scientific Foundation

NumPy (2006) and SciPy emerge, creating scientific computing foundation

β€’ Begins attracting academic researchers

2012-2015: The Breakthrough

Data science explosion begins with pandas (2008) gaining massive adoption

2016-2020: AI/ML Dominance

TensorFlow (2015) and deep learning libraries cement Python's leadership

2020-Present: Total Dominance

COVID-19 accelerates data science adoption, Python usage nearly doubles

β€’ 8.2M+ active users worldwide

Guido van Rossum

Guido van Rossum

BDFL, Benevolent Dictator for Life

"I was looking for a hobby programming project that would keep me occupied during the week around Christmas."

β€” Guido van Rossum on Python's origins

🎬 Named after

Monty Python's Flying Circus

Not the snake! 🐍

Watch Python Documentary

Learn the full story behind Python's creation

The Python Organisation

https://www.python.org/

πŸ”„Development Cycle

Python 3.13

Current

Released October 2024

β€’ Free-threaded mode (no GIL) experimental

β€’ JIT compiler experimental

β€’ Enhanced error messages

πŸ‚ Annual Autumn Release

New major version every October

Python 3.14October 2025
Python 3.15October 2026

Version Support Timeline

Full support:18 months
Security fixes:5 years total

🌍Global Impact

10M+

Active developers

500K+

PyPI packages

#1

on GitHub

30+

PyCons yearly

Python Software Foundation

Non-profit supporting Python development and community

$655K

in grants (2024)

61

countries supported

🐍Python is open source and community-driven - anyone can contribute!

Programming Paradigms

πŸ”„ Interpreted vs Compiled

Interpreted (like Python)

Code runs line-by-line, no compilation step

PythonJavaScriptRRuby

βœ“ Faster development β€’ βœ“ Platform independent

Compiled

Code converted to machine code before running

C/C++RustGoFortran

βœ“ Faster execution β€’ βœ— Platform specific

πŸ“ Dynamic vs Static Typing

Dynamic (like Python)

Variable types determined at runtime

x = 42        # x is an integer
x = "hello"   # now x is a string
x = [1, 2, 3] # now x is a list

βœ“ Flexible β€’ βœ“ Less code β€’ βœ“ Easier to learn

Static

Variable types must be declared

int x = 42;      // x is always an integer
string s = "hi"; // s is always a string

βœ“ Type safety β€’ βœ“ Better performance β€’ βœ— More verbose

πŸš€

Fast to Write

5-10x fewer lines than Java/C++

πŸ“š

Huge Ecosystem

Libraries for everything

🎯

Perfect for Science

Built for data & research

Who Uses Python?

The same tools you'll learn power the world's biggest companies

Netflix

Streaming & recommendations

Instagram

Backend & ML

NASA

Scientific computing

Spotify

Music algorithms

OpenAI

ChatGPT & AI

AI & Machine Learning

πŸ€–

Deep Learning

TensorFlow, PyTorch, Keras

πŸ“Š

Data Science

Pandas, NumPy, Scikit-learn

πŸ”

Computer Vision

OpenCV, image analysis, medical imaging

Biology & Science

🧬

Bioinformatics

BioPython, sequence analysis, BLAST

πŸ’Š

Drug Discovery

Molecular modeling, protein folding

πŸ”¬

Lab Automation

Instrument control, data pipelines

Course Structure

1

Interactive Lectures

Core concepts with biological examples

πŸ“š
2

Hands-on Seminars

Apply concepts to real problems

πŸ’»
3

Weekly Exercises

Practice with guided problems

✏️
4

Personal Projects

Apply to your own research

πŸš€

What We'll Build Together

πŸ“š Your Learning Journey

1️⃣

Lab Calculations

  • β€’ Python basics & setup
  • β€’ Variables, lists, loops
  • β€’ Functions for lab math
  • β€’ Molarity calculators
2️⃣

DNA Analysis

  • β€’ String operations
  • β€’ Finding ORFs
  • β€’ Dictionaries & codons
  • β€’ FASTA file processing
3️⃣

Tabular Data

  • β€’ Pandas DataFrames
  • β€’ Linear regression
  • β€’ Gene dependency
  • β€’ Object-oriented code
4️⃣

Visualization

  • β€’ Matplotlib basics
  • β€’ Seaborn statistics
  • β€’ Publication figures
  • β€’ Interactive plots
5️⃣

Image Data & Statistics

  • β€’ NumPy arrays
  • β€’ Statistical analysis
  • β€’ P-value calculations
  • β€’ Scientific computing
✨

You'll Master

  • β€’ Real lab automation
  • β€’ Biological data analysis
  • β€’ Professional coding
  • β€’ Problem-solving skills

🎯 Choose Your Final Project

🧬

Cancer Gene Dependency Analysis

Analyze CRISPR screen data to identify essential genes in cancer cell lines

  • β€’ Process DepMap datasets
  • β€’ Statistical analysis of gene essentiality
  • β€’ Identify therapeutic targets
πŸ”¬

Microscopy Image Analysis

Build automated pipelines for cell counting and fluorescence quantification

  • β€’ Cell segmentation & tracking
  • β€’ Fluorescence intensity analysis
  • β€’ Batch processing of experiments
🧠

Neural Activity Data Analysis

Process and visualize calcium imaging or electrophysiology recordings

  • β€’ Spike detection algorithms
  • β€’ Time-series analysis
  • β€’ Network activity patterns
πŸ“š

Literature Analysis with LLMs

Use local AI models to mine scientific literature and extract insights

  • β€’ PubMed abstract mining
  • β€’ Knowledge graph creation
  • β€’ Automated literature reviews

By the end of this course, you'll have the skills to tackle real biological problems with code!

Ready to Start Coding?

πŸš€

Let's set up your Python environment and write your first program!

Today's Goal

Molecular Weight Calculator

By the end of this lecture, you'll have written a Python program
that calculates the correct volume of a solution to prepare a desired concentration.

The Problem

Lab bottles and reagents for solution preparation
~100 bottles!

πŸ§ͺAlex's Challenge

Alex has been asked to restock solutions in the lab. She has about 100 bottles of different reagents and needs to make 10mM stocks for each.

Step 1: Alex starts with MG132(proteasome inhibitor)

β€’ Molecular weight: 475.6 g/mol
β€’ Weight measured: 89.5 mg

❓ The Question

How much solvent does Alex need to make a 10mM solution?

The formula:

Volume (mL) = mass (mg) / (MW (g/mol) Γ— conc (mM))

Volume = 89.5 / (475.6 Γ— 10) = ?

🀯 That's a lot of calculations for 100 bottles!

The Solution: Code Planning

🎯Learning Outcomes

  • β–ΈCalculate solvent volumes programmatically
  • β–ΈUse functions to organize code
  • β–ΈImplement loops for repetitive tasks
  • β–ΈRead and write CSV files for data processing

1️⃣Step 1: Single Calculation

Write code to calculate the solvent volume for one reagent

# Calculate volume

mass = 5.2

mw = 342.3

conc = 0.1

volume = (mass/mw)/conc

βœ“ Basic arithmetic operations

2️⃣Step 2: Automate with Loops

Use for loops and functions to process multiple reagents

def calculate_volume(m, mw, c):

return (m/mw)/c

for reagent in reagents:

vol = calculate_volume(...)

βœ“ Functions & iteration

3️⃣Step 3: Data I/O

Read reagent data from CSV files and export results

import csv

data = read_csv('reagents.csv')

results = process_data(data)

write_csv('volumes.csv', results)

βœ“ File handling & data processing

⚑

The Power of Automation

Manual Calculation

5+ hours

2-3 minutes Γ— 100 reagents

Python Program

30 seconds

Write once, run for all

Breaking Down Problems

An Essential Programming Skill

Complex problems become manageable when divided into smaller, logical steps

πŸ”οΈThe Big Problem

"Process 100 reagents and generate a report with calculated volumes"

😰

Overwhelming!

🧩Broken Down

1. Solve for one reagent first

2. Create a reusable function

3. Apply to all reagents

4. Handle input/output

😊

Manageable!

🎯

Start Simple

Always begin with the simplest case. Get one thing working before adding complexity.

πŸ”„

Iterate & Improve

Build incrementally. Each step should work before moving to the next.

πŸ§ͺ

Test Each Step

Verify your solution works for edge cases before scaling up.

πŸ’‘This Skill Applies Everywhere

Lab Work: Protocol optimization

Data Analysis: Processing large datasets

Research: Experimental design

Automation: Workflow development

The Complete Solution: Lists, Loops & Functions

Everything We'll Learn Today

Here's the complete solution to our lab calculation problem. By the end of today's lecture, you'll understand every line of this code and be able to write similar solutions yourself!

πŸ“‹

Lists

Store multiple values

πŸ”„

For Loops

Process each value

πŸ“¦

Functions

Reusable calculations

πŸš€ The Complete Solution - Try It!

Calculate buffer volumes for multiple reagents with different molecular weights.

Loading interactive Python...

πŸ” Breaking It Down

1. The Data (Lists)

mol_weights = [342.3, 156.8, 456.58]  # Store multiple values

β†’ We'll learn this in Step 2

2. The Function (Reusable Code)

def mw_calculator(mass, concentration, mw):
    return 1000 * (mass / concentration) / mw

β†’ We'll learn this in Step 3

3. The Loop (Process Everything)

for index, mw in enumerate(mol_weights):
    volume = mw_calculator(...)

β†’ We'll learn this in Step 2

🎯 Try It Yourself!

Modify the code above to experiment:

  • β–ΈAdd more molecular weights to the list: [342.3, 156.8, 456.58, 234.5, 678.9]
  • β–ΈChange the concentration to 5 mM and see how volumes change
  • β–ΈTry different masses: 2 mg, 10 mg, etc.
  • β–ΈAdd reagent names: reagent_names = ["MG132", "Cycloheximide", "Rapamycin"]

➑️Ready to Learn How This Works?

Don't worry if this looks complex right now! We'll break it down step by step:

  1. Step 1: Variables, data types, and basic calculations
  2. Step 2: Lists and for loops to handle multiple values
  3. Step 3: Functions to make code reusable
  4. Step 4: Reading data from files (bonus!)

Step 1: Calculating the Dilution Volume

Single Reagent Calculation

Let's solve our problem for one reagent first. We'll calculate how much solvent to add to achieve the desired concentration.

Loading interactive Python...

πŸ§ͺ Try Different Values!

Challenge 1: What volume do you need if you weigh 8.5 mg?

Challenge 2: How does doubling the concentration affect the volume?

Challenge 3: Try calculating for caffeine (mol_weight = 194.19)!

🎯Key Novel Concepts

  • β–ΈUse Google Colab notebooks for Python programming
  • β–ΈRun and modify code cells interactively
  • β–ΈDefine variables and perform calculations
  • β–ΈFormat output using f-strings

Google Colab: Your Python Laboratory

Rather than writing code here, you can also use Google Colab notebooks to work with Python. Colab provides a more complete environment for learning and experimenting.

πŸš€ Why Use Google Colab?

βœ“

No Installation Required

Python runs in your browser - no setup needed

βœ“

Save Your Work

Notebooks automatically save to Google Drive

βœ“

Rich Output

See graphs, tables, and formatted results

βœ“

More Space

Work with longer code and complex projects

βœ“

Libraries Included

NumPy, Pandas, Matplotlib already installed

βœ“

Share & Collaborate

Easy sharing with classmates and instructors

πŸ“‹ Quick Start Guide

1

Click the Link

Open the Colab notebook in a new tab

2

Make a Copy

File β†’ Save a copy in Drive to edit

3

Run & Experiment

Click β–Ά to run code cells, modify as needed

🧬 Try experimenting in Colab

Practice DNA sequence analysis with our interactive notebook. Work through examples, try challenges, and experiment with your own sequences.

πŸ’‘ Pro Tips for Colab Success

  • β–ΈUse Shift+Enter to run a cell quickly
  • β–ΈAdd text cells to document your thinking
  • β–ΈPrint variables to see what's happening
  • β–ΈRestart runtime if things get stuck
  • β–ΈUse # comments to explain your code
  • β–ΈExperiment freely - you can't break anything!

πŸ€” When to Use Each Tool

Interactive Slides

  • βœ“ Quick examples during lecture
  • βœ“ Testing small code snippets
  • βœ“ Following along in class
  • βœ“ No login required

Google Colab

  • βœ“ Homework and assignments
  • βœ“ Longer coding sessions
  • βœ“ Saving your work
  • βœ“ Advanced features & libraries

πŸ’» For Power Users

Want to take your Python development to the next level? Learn how to set up a professional local development environment with VS Code for more powerful coding capabilities.

Step 1: Variables & Assignment

What are Variables?

Variables are like labeled containers that store data. In biology, think of them like test tubes with labels - each one holds a specific value you can use later.

Basic syntax:

# Creating variables
sample_count = 24          # Store a number
gene_name = "BRCA1"        # Store text
temperature = 37.5         # Store a decimal

# Using variables
print(sample_count)        # Output: 24
print(gene_name)           # Output: BRCA1

πŸ”’ Working with Numbers

Let's start with numbers - perfect for lab measurements, concentrations, and calculations.

Loading interactive Python...

🧬 Working with Text (Strings)

Strings hold text data - perfect for gene names, sample IDs, and descriptions.

Loading interactive Python...

🎯 Challenge: Variable Swapping

Here's a classic programming problem: How do you swap the values of two variables? You have two sample concentrations and need to exchange their values.

Your Task:

  • β€’ The variable sample_a should end up with the value 4.8
  • β€’ The variable sample_b should end up with the value 2.5
  • β€’ Can you figure out how to swap them?
Loading interactive Python...

πŸ“š Practice More in Google Colab!

Explore variables and comments with more examples and exercises

Open in Colab

🎯Key Concepts Learned

  • β–ΈVariables store data with descriptive names
  • β–ΈPrint statements display variable values
  • β–ΈNumbers and strings behave differently
  • β–ΈVariables can be swapped (challenge!)
  • β–ΈVariables can be reused and updated
  • β–ΈString methods transform text data

Step 1: Data Types

Python's Core Data Types

Python has four fundamental data types that you'll use constantly in biological analysis. Each type has specific properties and uses in lab calculations.

The four core types:

# Integer (int) - whole numbers
sample_count = 24
pcr_cycles = 35

# Float (float) - decimal numbers  
ph_level = 7.4
concentration = 2.5

# String (str) - text data
gene_name = "BRCA1"
sequence = "ATGCGATCG"

# Boolean (bool) - True/False
is_complete = True
contaminated = False

πŸ”’ Integers (int)

Whole numbers - perfect for counting samples, cycles, or time points.

Loading interactive Python...

πŸ’§ Floats (float)

Numbers with decimal points - essential for measurements and concentrations.

Loading interactive Python...

🧬 Strings (str)

Text data - perfect for gene names, sample IDs, and DNA sequences.

Loading interactive Python...

βœ… Booleans (bool)

True or False values - used for conditions and logical operations.

Loading interactive Python...

πŸ” Checking Data Types

Python can tell you what type of data you're working with using the type() function.

Loading interactive Python...

πŸ“š Practice More in Google Colab!

Explore data types with more examples and exercises

Open in Colab

🎯Key Concepts Learned

  • β–Έint: Whole numbers for counting
  • β–Έfloat: Decimal numbers for measurements
  • β–Έstr: Text data in quotes
  • β–Έbool: True or False values
  • β–ΈUse type() to check data types
  • β–ΈChoose the right type for your data

Step 1: Printing & F-Strings

Communicating Results with F-Strings

F-strings are Python's most powerful way to create formatted output. They let you embed variables directly into text, making your results clear and professional.

F-string syntax:

# Basic f-string usage
gene = "BRCA1"
expression = 8.5
sample = "HS_001"

print(f"Gene: {gene}")
print(f"Sample {sample}: {gene} expression = {expression}")

# Output:
# Gene: BRCA1
# Sample HS_001: BRCA1 expression = 8.5

πŸ“ Basic F-String Usage

Start with f"" and put variables in {} brackets.

Loading interactive Python...

πŸ”’ Formatting Numbers

Control decimal places for precise scientific reporting.

Loading interactive Python...

🎯 Practice: Create a Lab Report

Use f-strings to create a simple lab report with the given variables.

Your Task:

Create output that looks like:

Sample: E. coli
OD600: 0.65
Growth phase: exponential
Loading interactive Python...

πŸ“š Practice More in Google Colab!

Master f-strings with more examples and exercises

Open in Colab

🎯Key Concepts Learned

  • β–ΈF-strings start with f""
  • β–ΈVariables go in {} brackets
  • β–ΈFormat decimals with :.2f
  • β–ΈPercentages with :.1%

Step 2: Analyzing Many Values at Once

The Problem with Step 1

We can only process one value at a time

What if we have 10 samples? 100 samples? 1000 genes?
Do we copy-paste our code for each one?

The Solution: Lists & Loops

πŸ“‹

Lists store multiple values

Keep all your data organized in one place

πŸ”„

Loops process each value

Automatically repeat operations for every item

[ ] = List of valuesΒ Β Β for = Process each one

The solution in action - try it!

Loading interactive Python...

One loop handles 5, 50, or 5000 samples!

Step 2: Lists - Storing Multiple Values

What are Lists?

Lists are containers that hold multiple values in order. Think of them like a test tube rack - each position holds one sample, and you can access them by their position number.

Basic list syntax:

# Creating lists
samples = [2.5, 3.8, 1.2, 4.5]        # List of numbers
genes = ["BRCA1", "TP53", "MYC"]      # List of strings
mixed = [24, "E. coli", 37.5, True]   # Mixed types

# Accessing values (indexing starts at 0!)
print(samples[0])     # Output: 2.5 (first item)
print(genes[2])       # Output: MYC (third item)
print(len(samples))   # Output: 4 (number of items)

πŸ“‹ Creating and Using Lists

Store your experimental data in lists for batch processing.

Loading interactive Python...

πŸ”§ List Operations

Add, remove, and modify values in your lists.

Loading interactive Python...

🎯 Practice: Manage Sample Data

Create and manipulate a list of pH measurements.

Your Tasks:

  • β€’ Create a list with pH values: 7.2, 7.4, 6.8
  • β€’ Add pH 7.5 to the end
  • β€’ Print the second pH value (should be 7.4)
  • β€’ Print the total number of measurements
Loading interactive Python...

πŸ“š Practice More in Google Colab!

Master lists with more examples and exercises

Open in Colab

🎯Key Concepts Learned

  • β–ΈLists store multiple values in order
  • β–ΈAccess items with square brackets [ ]
  • β–ΈIndexing starts at 0, not 1
  • β–ΈUse append() to add items
  • β–Έlen() gives the number of items
  • β–ΈNegative indices count from the end

Step 2: For Loops - Processing Each Item

What are For Loops?

For loops automatically repeat code for each item in a list. Instead of writing the same code multiple times, you write it once and Python applies it to every value.

For loop syntax:

# Basic for loop structure
samples = [2.5, 3.8, 1.2]

for concentration in samples:
    # This code runs for each value
    print(concentration)
    
# Output:
# 2.5
# 3.8
# 1.2

1️⃣ Simple For Loops

Start with the basics - print each item in a list.

Loading interactive Python...

2️⃣ Building New Lists with Loops

Create new lists by processing data - start empty, then append!

Loading interactive Python...

3️⃣ Using range() and enumerate()

Access indices when you need to work with multiple lists or track position.

Loading interactive Python...

🎯 Practice: Process pH Readings

Create a new list showing whether each pH is acidic, neutral, or basic.

Your Task:

  • β€’ Create an empty list called descriptions
  • β€’ For each pH value, create a description string
  • β€’ Append each description to the list
  • β€’ Print the final list

Expected output:

['pH 6.5', 'pH 7.0', 'pH 7.4', 'pH 8.2']
Loading interactive Python...

πŸ“š Practice More in Google Colab!

Master for loops with more examples and exercises

Open in Colab

4️⃣ Advanced: List Comprehensions

Python's shortcut for creating lists - same result, more compact! (Optional - for those who want to explore)

Loading interactive Python...

🎯Key Concepts Learned

  • β–ΈFor loops process each item in a list
  • β–ΈBuild new lists with append()
  • β–Έrange(len()) for index access
  • β–Έenumerate() for index + value
  • β–ΈIndentation defines loop body
  • β–ΈList comprehensions are optional shortcuts

Step 3: Creating Reusable Functions

The Problem with Steps 1 & 2

Our code works, but what if we need the same calculation for different experiments?

Currently we'd have to copy and paste the entire code block!
There must be a better way to reuse our calculations...

The Solution: Functions

πŸ“¦

Package calculations into functions

Write once, use anywhere

πŸ”§

Customize with parameters

Same function, different inputs

def = Define a function

The solution in action - try it!

Loading interactive Python...

One function, lots of calculations!

Step 3: Functions - Packaging Your Code

What are Functions?

Functions are reusable blocks of code that perform specific tasks. Think of them like lab protocols - write the procedure once, then follow it whenever you need that result.

Basic function syntax:

def function_name(parameters):
    """Optional description"""
    # Your code here
    return result

# Call the function
result = function_name(arguments)

1️⃣ Simple Functions

The most basic functions just take variables (numbers, strings) and print the result. Nothing is returned!

Loading interactive Python...

2️⃣ Functions that return a value

In most cases functions return the final result. This is then assigned to a new variable

Loading interactive Python...

3️⃣ Nested Functions and multiple return statements

Functions can be called with functions and return multiple values

Loading interactive Python...

🎯 Practice: Create a Concentration Calculator

Write a function that calculates final concentration after dilution.

Your Task:

  • β€’ Function name: calculate_final_concentration
  • β€’ Parameters: initial_conc, volume_added, total_volume
  • β€’ Return: final concentration
  • β€’ Formula: (initial_conc Γ— volume_added) Γ· total_volume

Test it with: 10 mg/mL, 50 Β΅L added, 200 Β΅L total

Loading interactive Python...

🎯Key Concepts Learned

  • β–ΈFunctions start with def
  • β–ΈParameters go in parentheses
  • β–ΈUse return to send back results
  • β–ΈFunctions make code reusable
  • β–ΈSome functions print instead of return
  • β–ΈWrite once, use many times

πŸ““Practice in Google Colab

Ready to practice functions? Open this interactive notebook to work through more examples and exercises.

πŸš€Open Functions Notebookβ†’

Step 3: Function Parameters & Arguments

Making Functions Flexible

Parameters make functions adaptable - like adjusting a protocol for different reagents or conditions. You can set default values and use keywords for clarity.

Parameter types:

def function_name(required_param, optional_param=default_value):
    # Function body
    return result

# Call with positional arguments
function_name(value1, value2)

# Call with keyword arguments  
function_name(required_param=value1, optional_param=value2)

1️⃣ Default Parameters

Set common values as defaults - parameters with = signs are optional!

Loading interactive Python...

2️⃣ Keyword Arguments

Use parameter names to make function calls clearer - no need to remember order!

Loading interactive Python...

3️⃣ Functions Returning Multiple Values

Functions can return more than one value - separate them with commas!

Loading interactive Python...

🎯 Practice: Default Parameters

Write a function with default values for dilutions.

Your Task:

  • β€’ Function: make_solution(stock_conc, target_conc=1.0)
  • β€’ Calculate dilution factor: stock_conc Γ· target_conc
  • β€’ Test with 10 mg/mL stock (use default target)
Loading interactive Python...

🎯Key Concepts Learned

  • β–ΈDefault parameters: param=value
  • β–ΈKeyword arguments for clarity
  • β–ΈMultiple return values with commas
  • β–ΈUnpack: a, b = function()
  • β–ΈPositional args come before keyword
  • β–ΈFunctions become more flexible

πŸ““Practice in Google Colab

Ready to practice function parameters? Open this interactive notebook to work through more examples and exercises.

πŸš€Open Functions Notebookβ†’

The Complete Solution: Lists, Loops & Functions

Everything We'll Learn Today

Here's the complete solution to our lab calculation problem. By the end of today's lecture, you'll understand every line of this code and be able to write similar solutions yourself!

πŸ“‹

Lists

Store multiple values

πŸ”„

For Loops

Process each value

πŸ“¦

Functions

Reusable calculations

πŸš€ The Complete Solution - Try It!

Calculate buffer volumes for multiple reagents with different molecular weights.

Loading interactive Python...

πŸ” Breaking It Down

1. The Data (Lists)

mol_weights = [342.3, 156.8, 456.58]  # Store multiple values

β†’ We'll learn this in Step 2

2. The Function (Reusable Code)

def mw_calculator(mass, concentration, mw):
    return 1000 * (mass / concentration) / mw

β†’ We'll learn this in Step 3

3. The Loop (Process Everything)

for index, mw in enumerate(mol_weights):
    volume = mw_calculator(...)

β†’ We'll learn this in Step 2

🎯 Try It Yourself!

Modify the code above to experiment:

  • β–ΈAdd more molecular weights to the list: [342.3, 156.8, 456.58, 234.5, 678.9]
  • β–ΈChange the concentration to 5 mM and see how volumes change
  • β–ΈTry different masses: 2 mg, 10 mg, etc.
  • β–ΈAdd reagent names: reagent_names = ["MG132", "Cycloheximide", "Rapamycin"]

➑️Ready to Learn How This Works?

Don't worry if this looks complex right now! We'll break it down step by step:

  1. Step 1: Variables, data types, and basic calculations
  2. Step 2: Lists and for loops to handle multiple values
  3. Step 3: Functions to make code reusable
  4. Step 4: Reading data from files (bonus!)

Lecture 1 Summary: What You've Learned Today

1️⃣Variables & Data Types

Assignment

  • β–ΈStore values: mass = 5.5
  • β–ΈMeaningful variable names

Data Types

  • β–ΈNumbers, strings, booleans
  • β–ΈType matters for operations

F-Strings

  • β–ΈFormatted output
  • β–Έf"Value: {var}"

2️⃣Lists & For Loops

Lists

  • β–ΈStore multiple values: [1, 2, 3]
  • β–ΈAccess with index: list[0]

For Loops

  • β–ΈProcess each item automatically
  • β–Έfor item in list:

Enumerate

  • β–ΈTrack position and value
  • β–Έenumerate(list)

3️⃣Functions - Reusable Code

Function Basics

  • β–Έdef function_name():
  • β–Έreturn results back

Parameters

  • β–ΈDefault values: param=1.0
  • β–ΈKeyword arguments for clarity

Flexibility

  • β–ΈMultiple return values
  • β–ΈReuse code efficiently

🧬Real Lab Applications

βš—οΈ

Molarity Calculations

Automated concentration calculations for lab solutions

πŸ“Š

Batch Processing

Process multiple samples at once with loops

πŸ”„

Reusable Protocols

Functions as digital lab protocols

πŸ’‘Problem-Solving Skills You've Gained

  • βœ“Break down complex problems into smaller steps
  • βœ“Think algorithmically about lab procedures
  • βœ“Automate repetitive calculations to reduce errors
  • βœ“Write clean, reusable code with functions
  • βœ“Handle multiple data points efficiently
  • βœ“Debug and test your solutions

πŸš€What's Coming Next

Lecture 2

Working with DNA: String Operations, Dictionaries and Conditionals
🧬
String Operations

Manipulate DNA sequences, find patterns, slice strings

πŸ“š
Dictionaries

Store genetic code, codon tables, key-value pairs

πŸ”€
Conditionals

Make decisions in code with if/else statements

πŸŽ‰ Congratulations!

You've taken your first steps into the world of programming for biology

Keep practicing with the Google Colab notebooks, and remember: every expert was once a beginner!

Next Steps: Keep Learning & Practicing

πŸ““Practice Makes Perfect

The best way to learn programming is by doing! We've prepared interactive notebooks for you to practice everything you learned today.

🎯 Today's Exercises

  • β–ΈPractice variables and calculations
  • β–ΈWork with lists and loops
  • β–ΈBuild your own functions
  • β–ΈSolve real lab problems

πŸ’‘ Tips for Success

  • β–ΈType out code yourself (don't copy-paste)
  • β–ΈExperiment and break things!
  • β–ΈRead error messages carefully
  • β–ΈTry the challenge exercises
πŸš€Access Lecture 1 Practice Notebooksβ†’

πŸ§ͺSpecial Project: Lab Calculator Toolkit

Put everything together with our comprehensive Lab Calculator Toolkit! This notebook combines all the concepts you've learned into practical tools you'll actually use in the lab:

β€’ DNA/RNA dilution calculator
β€’ Molarity & MW calculator
β€’ PCR master mix calculator
β€’ Growth rate calculator
πŸ““Open Lab Calculator Toolkit

πŸ“Coming Soon: Working with Real Data Files

πŸ“ŠWhy File I/O Matters

Real biological data doesn't live in code - it's in files! Soon you'll learn to:

  • βœ“Read experimental data from CSV files
  • βœ“Process thousands of data points at once
  • βœ“Save analysis results for reports
  • βœ“Automate data pipeline workflows

🐼Lecture 4: Pandas & Data Analysis

We'll dive deep into file handling with the powerful Pandas library:

import pandas as pd # Read experimental data data = pd.read_csv('results.csv') # Analyze & transform processed = data.groupby('sample') # Save results processed.to_csv('analysis.csv')

For now, focus on mastering the basics - we'll build up to this!

πŸ“Before Next Lecture

βœ…

Complete Exercises

Work through all practice notebooks for Lecture 1

πŸ”„

Review & Experiment

Try modifying the code examples to see what happens

πŸ€”

Bring Questions

Note down any concepts that need clarification

🌟 You've taken your first steps into computational biology!

Remember: Every expert programmer started exactly where you are now. Keep practicing, stay curious, and don't be afraid to make mistakes!

Further Resources: Keep Growing Your Skills

Ready to dive deeper? Here are some excellent resources to continue your Python journey beyond this course.

πŸ“Š

DataCamp: Python for Data Science

Interactive online courses perfect for scientists. Learn Python with hands-on exercises focused on data analysis and visualization.

🎯 Perfect for:

  • β€’ Interactive learning with immediate feedback
  • β€’ Data science focus relevant to biology
  • β€’ Structured curriculum with certificates
Visit DataCamp→
πŸŽ™οΈ

Talk Python Podcast

Learn Python through engaging conversations with experts. Great for commutes or lab downtime!

🎯 Perfect for:

  • β€’ Learning about real-world applications
  • β€’ Staying updated with Python trends
  • β€’ Passive learning during other activities
Listen to Podcast→
πŸ“š

Real Python Tutorials

In-depth tutorials and articles on every Python topic imaginable. Excellent for deepening your understanding.

🎯 Perfect for:

  • β€’ Detailed explanations of concepts
  • β€’ Best practices and clean code
  • β€’ Advanced topics when you're ready
Explore Tutorials→
πŸ“–

Python Crash Course (Book)

The bestselling Python book - perfect for scientists who prefer traditional learning with hands-on projects.

🎯 Perfect for:

  • β€’ Comprehensive reference material
  • β€’ Step-by-step project building
  • β€’ Offline learning and practice
View on O'Reilly→

🧬Python for Biology & Bioinformatics

Biopython

The official Python library for biological computation

biopython.org β†’

Rosalind

Learn bioinformatics through problem solving

rosalind.info β†’

Python for Biologists

Free online book specifically for biologists

pythonforbiologists.com β†’

🌟 Remember: Learning to code is a journey, not a destination

These resources will be here whenever you're ready to explore them. Focus on this course first, then branch out at your own pace!