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
| Language | Type System | Execution | Best For | Learning Curve |
|---|---|---|---|---|
| Python π | Dynamic | Interpreted | Data Science, AI, Web, Automation | ββ―β―β―β― Easy |
| R | Dynamic | Interpreted | Statistics, Data Analysis | βββ―β―β― Moderate |
| JavaScript | Dynamic | Interpreted/JIT | Web Development | βββ―β―β― Moderate |
| Java | Static | Compiled (bytecode) | Enterprise, Android | ββββ―β― Challenging |
| C++ | Static | Compiled | Systems, 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
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! π
Learn the full story behind Python's creation
The Python Organisation
πDevelopment Cycle
Python 3.13
CurrentReleased October 2024
β’ Free-threaded mode (no GIL) experimental
β’ JIT compiler experimental
β’ Enhanced error messages
π Annual Autumn Release
New major version every October
Version Support Timeline
π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
β Faster development β’ β Platform independent
Compiled
Code converted to machine code before running
β 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
Streaming & recommendations
Backend & ML
Scientific computing
Music algorithms
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
Interactive Lectures
Core concepts with biological examples
Hands-on Seminars
Apply concepts to real problems
Weekly Exercises
Practice with guided problems
Personal Projects
Apply to your own research
What We'll Build Together
π Your Learning Journey
Lab Calculations
- β’ Python basics & setup
- β’ Variables, lists, loops
- β’ Functions for lab math
- β’ Molarity calculators
DNA Analysis
- β’ String operations
- β’ Finding ORFs
- β’ Dictionaries & codons
- β’ FASTA file processing
Tabular Data
- β’ Pandas DataFrames
- β’ Linear regression
- β’ Gene dependency
- β’ Object-oriented code
Visualization
- β’ Matplotlib basics
- β’ Seaborn statistics
- β’ Publication figures
- β’ Interactive plots
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

π§ͺ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)
β The Question
How much solvent does Alex need to make a 10mM solution?
The formula:
Volume (mL) = mass (mg) / (MW (g/mol) Γ conc (mM))
π€― 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.
π 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:
- Step 1: Variables, data types, and basic calculations
- Step 2: Lists and for loops to handle multiple values
- Step 3: Functions to make code reusable
- 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.
π§ͺ 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
Click the Link
Open the Colab notebook in a new tab
Make a Copy
File β Save a copy in Drive to edit
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.
𧬠Working with Text (Strings)
Strings hold text data - perfect for gene names, sample IDs, and descriptions.
π― 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_ashould end up with the value 4.8 - β’ The variable
sample_bshould end up with the value 2.5 - β’ Can you figure out how to swap them?
π Practice More in Google Colab!
Explore variables and comments with more examples and exercises
π―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.
π§ Floats (float)
Numbers with decimal points - essential for measurements and concentrations.
𧬠Strings (str)
Text data - perfect for gene names, sample IDs, and DNA sequences.
β Booleans (bool)
True or False values - used for conditions and logical operations.
π Checking Data Types
Python can tell you what type of data you're working with using the type() function.
π Practice More in Google Colab!
Explore data types with more examples and exercises
π―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.
π’ Formatting Numbers
Control decimal places for precise scientific reporting.
π― 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
π Practice More in Google Colab!
Master f-strings with more examples and exercises
π―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!
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.
π§ List Operations
Add, remove, and modify values in your lists.
π― 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
π Practice More in Google Colab!
Master lists with more examples and exercises
π―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.21οΈβ£ Simple For Loops
Start with the basics - print each item in a list.
2οΈβ£ Building New Lists with Loops
Create new lists by processing data - start empty, then append!
3οΈβ£ Using range() and enumerate()
Access indices when you need to work with multiple lists or track position.
π― 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']
π Practice More in Google Colab!
Master for loops with more examples and exercises
4οΈβ£ Advanced: List Comprehensions
Python's shortcut for creating lists - same result, more compact! (Optional - for those who want to explore)
π―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!
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!
2οΈβ£ Functions that return a value
In most cases functions return the final result. This is then assigned to a new variable
3οΈβ£ Nested Functions and multiple return statements
Functions can be called with functions and return multiple values
π― 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
π―Key Concepts Learned
- βΈFunctions start with
def - βΈParameters go in parentheses
- βΈUse
returnto 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!
2οΈβ£ Keyword Arguments
Use parameter names to make function calls clearer - no need to remember order!
3οΈβ£ Functions Returning Multiple Values
Functions can return more than one value - separate them with commas!
π― 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)
π―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.
π 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:
- Step 1: Variables, data types, and basic calculations
- Step 2: Lists and for loops to handle multiple values
- Step 3: Functions to make code reusable
- 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(): - βΈ
returnresults 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
π§ͺ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:
π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
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
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
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
π§¬Python for Biology & Bioinformatics
π 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!