0% found this document useful (0 votes)
9 views143 pages

Python Crash Course

This document is an introduction to programming using Python, specifically tailored for bioinformatics students. It covers the importance of Python, its advantages, and its ecosystem, along with practical aspects such as environment setup and programming fundamentals. The document also emphasizes Python's relevance in scientific computing and provides guidance on best practices for coding and collaboration.

Uploaded by

aissadicko082
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views143 pages

Python Crash Course

This document is an introduction to programming using Python, specifically tailored for bioinformatics students. It covers the importance of Python, its advantages, and its ecosystem, along with practical aspects such as environment setup and programming fundamentals. The document also emphasizes Python's relevance in scientific computing and provides guidance on best practices for coding and collaboration.

Uploaded by

aissadicko082
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Generated on Friday 12th December, 2025 at 21:02

Introduction to Programming
Applied Python for Bioinformatics

Abdoulaye SAMAKE∗
Department of Mathematics and Computer Science
Faculty of Sciences and Techniques (FST)
University of Sciences, Techniques and Technologies of Bamako (USTTB)

Master of Bioinformatics


E-mail: [Link]@[Link]
BP: E 3206, Bamako, Mali

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 1 / 143


Outline

1 Introduction and Motivation

2 Setting up the Python Environment

3 Python Fundamentals
Variables and Simple Data Types
Lists and if Statements
Dictionaries and User Input
Functions and Modules

4 Practical Aspects of Python Programming


Introduction & Environment Setup
Python Path & Module Discovery
Virtual Environments Management
Module Import Strategies & Best Practices
Summary & Best Practices

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 2 / 143


Introduction and Motivation

Outline

1 Introduction and Motivation


2 Setting up the Python Environment
3 Python Fundamentals
Variables and Simple Data Types
Lists and if Statements
Dictionaries and User Input
Functions and Modules
4 Practical Aspects of Python Programming
Introduction & Environment Setup
Python Path & Module Discovery
Virtual Environments Management
Module Import Strategies & Best Practices
Summary & Best Practices

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 3 / 143


Introduction and Motivation

Why Python?

The Python Crash Course Philosophy


“Python is a language that lets you work quickly and integrate systems more
effectively.”
— Eric Matthes, Python Crash Course

Key Advantages for Scientists


❒ Gentle Learning Curve: Perfect for beginners with no programming background
❒ Readability: Code reads almost like English (Pythonic philosophy)
❒ Immediate Feedback: Interactive mode lets you experiment and learn quickly
❒ Batteries Included: Rich standard library for common tasks
❒ Cross-Platform: Runs on Windows, macOS, Linux seamlessly

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 4 / 143


Introduction and Motivation

A Brief History of Python

Timeline
❒ 1989: Conceived by Guido van Rossum
❒ 1991: First public release (Python 0.9.0)
❒ 2000: Python 2.0 released
❒ 2008: Python 3.0 released
❒ 2020: Python 2 end-of-life
❒ Today: Python 3.x dominant

Design Philosophy
❒ Simple is better than complex
❒ Explicit is better than implicit
❒ Readability counts
❒ There should be one obvious way to do it

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 5 / 143


Introduction and Motivation

Python’s Dominance in 2025

Industry Recognition
❒ TIOBE Index #1: Most popular programming language
❒ PYPL Index #1: Most searched tutorials
❒ Stack Overflow: 2nd most loved language
❒ GitHub: Top 3 most used language

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 6 / 143


Introduction and Motivation

Python’s Dominance in 2025

Why This Matters for You


❒ High employability across sectors
❒ Extensive learning resources
❒ Active community support
❒ Continuous innovation

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 7 / 143


Introduction and Motivation

Language Comparison for Scientific Computing

Choosing the Right Tool for Scientific Workflows


Language Speed Learning Curve Sci. Libraries Use Case
C/C++ ++++ Steep ++ High-performance computing
Java +++ Moderate ++ Enterprise systems
R + Gentle ++++ Statistical analysis
MATLAB ++ Gentle +++ Engineering math
Julia ++++ Moderate +++ Scientific computing
Python +++ Gentle ++++ General-purpose science

Python’s Sweet Spot


❒ Optimal balance of performance and productivity
❒ Glue language that integrates with C/Fortran for speed
❒ One language for data analysis, visualization, and modeling

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 8 / 143


Introduction and Motivation

Python Across Scientific Domains

Mathematics & Statistics Chemistry & Materials


❒ SymPy: Symbolic mathematics ❒ RDKit: Cheminformatics ASE:
❒ NumPy: Numerical computing Atomistic simulations
❒ SciPy: Scientific algorithms ❒ Pymatgen: Materials analysis
❒ StatsModels: Statistical testing ❒ OpenBabel: Chemical file formats

Physics & Engineering Bioinformatics & Biology


❒ Matplotlib: Publication-quality plots ❒ Biopython: Sequence analysis
❒ Astropy: Astronomy toolbox ❒ Scikit-bio: Bioinformatics
❒ OpenCV: Computer vision ❒ Scanpy: Single-cell analysis
❒ FEniCS: PDE solving ❒ PyRanges: Genomics

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 9 / 143


Introduction and Motivation

The Python Scientific Ecosystem—Part 1


A Layered Stack for Scientific Computing
VISUALIZATION

Seaborn Matplotlib Plotly


Stats Viz Plotting Interactive

NumPy SciPy Pandas


Numerical Scientific Data

FOUNDATION

Python
Core Language

CORE

Biopython Scikit-learn RDKit


Bioinfo ML Chem

DOMAIN

Simple Relationship Types


Core Dependencies Package Relationships
Python to essential packages Inter-package dependencies and usage
Abdoulaye Samaké (USTTB/FST) Introduction to Programming 10 / 143
Introduction and Motivation

First Steps: Python Crash Course Style

The Interactive Approach - Learning by Doing


1 # Example 1: Immediate feedback in Python interpreter
2 >>> print("Hello, Bioinformatics World!")
3 Hello, Bioinformatics World!
4
5 # Example 2: Variables and simple math (as in calculator)
6 >>> dna_length = 1000
7 >>> gc_count = 450
8 >>> gc_content = gc_count / dna_length
9 >>> print(f"GC content: {gc_content:.1%}")
10 GC content: 45.0%
11
12 # Example 3: Working with biological sequences
13 >>> sequence = "ATCGATCG"
14 >>> print(f"Sequence length: {len(sequence)}")
15 Sequence length: 8
16 >>> print(f"Reverse complement: {sequence[::-1]}")
17 Reverse complement: GCTAGCTA
18

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 11 / 143


Introduction and Motivation

Python in Modern Research Workflows

Data Analysis Pipeline


1. Data acquisition and cleaning Research Advantages
2. Exploratory data analysis ❒ Reproducibility: Scripts document
3. Statistical modeling exact analysis
4. Visualization and reporting ❒ Automation: Process 1000s of files
automatically
5. Reproducible publication
❒ Integration: Combine tools from
different domains
Key Tools
❒ Collaboration: Share code with
❒ Jupyter: Interactive notebooks research community
❒ Pandas: Data manipulation ❒ Publication-ready: Create figures for
❒ Scikit-learn: Machine learning papers
❒ Matplotlib: Visualization

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 12 / 143


Introduction and Motivation

The Zen of Python: Principles for Better Code

Core Principles (PEP 20)

❒ Special cases aren’t special enough to


❒ Beautiful is better than ugly. break the rules.
❒ Explicit is better than implicit. ❒ Although practicality beats purity.
❒ Simple is better than complex. ❒ Errors should never pass silently.
❒ Complex is better than complicated. ❒ Unless explicitly silenced.
❒ Readability counts. ❒ There should be one–and preferably
only one–obvious way to do it.

Application to Scientific Programming


❒ Write code that your future self can understand
❒ Choose clear variable names (gc_content vs x)
❒ Break complex problems into simple functions
❒ Document your code for reproducibility

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 13 / 143


Introduction and Motivation

Interactive Exploration vs. Scripted Analysis

Scripted Mode (.py files)


Interactive Mode (Jupyter/REPL)
Essential for:
Perfect for:
❒ Reproducible research
❒ Learning and experimentation
❒ Large projects
❒ Data exploration
❒ Automated pipelines
❒ Quick calculations
❒ Production code
❒ Prototyping ideas
❒ Version control
❒ Debugging code
Best Practices:
Tools:
❒ Modular code organization
❒ Jupyter Notebook/Lab
❒ Documentation strings
❒ IPython interpreter
❒ Unit testing
❒ Spyder IDE
❒ Version control with Git

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 14 / 143


Introduction and Motivation

Practical Scientific Examples

Mathematics: Solving Equations


1 # Solve quadratic equation: ax^2 + bx + c = 0
2 import math
3
4 def solve_quadratic(a, b, c):
5 """Solve quadratic equation and return real roots."""
6 discriminant = b**2 - 4*a*c
7 if discriminant >= 0:
8 root1 = (-b + [Link](discriminant)) / (2*a)
9 root2 = (-b - [Link](discriminant)) / (2*a)
10 return root1, root2
11 else:
12 return None # No real roots
13
14 # Example usage
15 roots = solve_quadratic(1, -3, 2)
16 print(f"Roots of x^2 - 3x + 2 = 0: {roots}")

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 15 / 143


Introduction and Motivation

Bioinformatics Example: DNA Analysis

Complete DNA Sequence Analysis Function


1 def analyze_dna_sequence(sequence):
2 """
3 Comprehensive DNA sequence analysis.
4
5 Parameters:
6 sequence (str): DNA sequence (A, T, C, G)
7
8 Returns:
9 dict: Analysis results
10 """
11 sequence = [Link]()
12
13 # Basic statistics
14 length = len(sequence)
15 gc_count = [Link]('G') + [Link]('C')
16 gc_content = gc_count / length
17
18 # Nucleotide frequencies
19 nucleotide_freq = {
20 'A': [Link]('A') / length,
21 'T': [Link]('T') / length,
22 'C': [Link]('C') / length,
23 'G': [Link]('G') / length
24 }
25
26 return {
27 'length': length,
28 'gc_content': gc_content,
29 'nucleotide_frequencies': nucleotide_freq
} Samaké (USTTB/FST)
30 Abdoulaye Introduction to Programming 16 / 143
Introduction and Motivation

Python: Balanced Perspective


Strengths Considerations
+ Gentle learning curve - Perfect for - Execution speed - Slower than
scientists compiled languages
+ Rich ecosystem - Libraries for every - Memory usage - Can be high for large
domain datasets
+ Excellent documentation - Easy to - Global Interpreter Lock - Limits
find help parallel execution
+ Cross-platform - Works everywhere - Mobile development - Not ideal for
+ Free and open source - No license mobile apps
costs - Runtime errors - Some errors only
+ Great community - Active support appear at runtime
+ Integration capabilities - Glue - Packaging - Can be complex for
language distribution
Mitigation Strategies
❒ Use NumPy/SciPy for performance-critical parts
❒ Call C/Fortran code for bottlenecks
❒ Use multiprocessing for parallel tasks
❒ Write tests to catch errors early

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 17 / 143


Introduction and Motivation

Summary: Why Python for Your Master’s Studies?

Career and Research Benefits


❒ Marketable Skill: Highly sought in industry and academia
❒ Research Efficiency: Automate repetitive analysis tasks
❒ Reproducible Science: Scripts provide exact methodology
❒ Collaboration: Share code with international colleagues
❒ Publication Support: Create professional visualizations
❒ Future-Proof: Continuously evolving ecosystem

Learning Path Ahead


1. Python fundamentals (variables, loops, functions)
2. Data structures (lists, dictionaries, arrays)
3. Scientific libraries (NumPy, Pandas, Matplotlib)
4. Domain-specific tools (Biopython, Scikit-learn)
5. Advanced topics (optimization, parallel computing)

Next Session
Setting up your Python environment and writing your first programs
Abdoulaye Samaké (USTTB/FST) Introduction to Programming 18 / 143
Setting up the Python Environment

Outline

1 Introduction and Motivation


2 Setting up the Python Environment
3 Python Fundamentals
Variables and Simple Data Types
Lists and if Statements
Dictionaries and User Input
Functions and Modules
4 Practical Aspects of Python Programming
Introduction & Environment Setup
Python Path & Module Discovery
Virtual Environments Management
Module Import Strategies & Best Practices
Summary & Best Practices

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 19 / 143


Setting up the Python Environment

The Importance of a Proper Development Environment

Why Environment Setup Matters


❒ Reproducibility: Ensures consistent results across different machines
❒ Dependency Management: Isolates project-specific packages
❒ Conflict Prevention: Avoids version clashes between projects
❒ Collaboration: Makes sharing code with colleagues seamless
❒ Debugging: Reduces environment-related issues

Common Pitfalls to Avoid


❒ Installing packages system-wide (can break system tools)
❒ Mixing Python versions in the same environment
❒ Not documenting package versions
❒ Using different environments across projects

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 20 / 143


Setting up the Python Environment

Python Distribution Options

Option 1: [Link] (Standard)


❒ Direct from [Link]
❒ Most basic installation
❒ Requires manual package management
❒ Good for learning fundamentals
❒ Recommended for: Beginners understanding the ecosystem

Option 2: Anaconda/Miniconda (Scientific)


❒ Pre-packaged scientific Python
❒ Includes data science libraries
❒ Built-in environment management
❒ Optimized for scientific computing
❒ Recommended for: Researchers and data scientists

Our Recommendation for This Course


Miniconda - Lightweight, flexible, and perfect for scientific computing
Abdoulaye Samaké (USTTB/FST) Introduction to Programming 21 / 143
Setting up the Python Environment

Installing Miniconda

Step-by-Step Installation
1. Download: Visit [Link]/[Link]
2. Choose: Python 3.9+ (64-bit) for your OS
3. Install: Follow platform-specific instructions
4. Verify: Open terminal and run conda –version
5. Update: Run conda update conda

Windows macOS/Linux
❒ Download .exe installer ❒ Download .sh installer
❒ Run as administrator ❒ Run: bash Miniconda3-latest*.sh
❒ Add to PATH (recommended) ❒ Restart terminal
❒ Use Anaconda Prompt ❒ Use regular terminal

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 22 / 143


Setting up the Python Environment

Understanding Conda Environments

What are Virtual Environments?


❒ Isolated spaces with specific Python versions and packages
❒ Each environment has its own:
➩ Python interpreter
➩ Installed packages
➩ Package versions
➩ Environment variables
❒ Prevents conflicts between projects

Real-World Analogy
❒ Think of environments as separate workshops
❒ Each workshop has specific tools for specific tasks
❒ You don’t mix woodworking tools with electronics tools

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 23 / 143


Setting up the Python Environment

Essential Conda Commands


Environment Management
1 # Create a new environment with Python 3.11
2 conda create --name bioinformatics python=3.11
3
4 # Activate the environment
5 conda activate bioinformatics
6
7 # Deactivate current environment
8 conda deactivate
9
10 # List all environments
11 conda env list
12
13 # Remove an environment
14 conda env remove --name bioinformatics
15

Package Management
1 # Install packages
2 conda install numpy pandas matplotlib
3 conda install -c conda-forge biopython
4
5 # List installed packages
6 conda list
7
8 # Remove packages
9 conda remove package_name
10
Abdoulaye Samaké (USTTB/FST) Introduction to Programming 24 / 143
Setting up the Python Environment

Setting Up Our Bioinformatics Environment

Complete Environment Setup


1 # Create environment for the course
2 conda create --name bioinfo_course python=3.11
3
4 # Activate environment
5 conda activate bioinfo_course
6
7 # Install core scientific packages
8 conda install numpy scipy pandas matplotlib seaborn jupyter
9
10 # Install bioinformatics packages
11 conda install -c conda-forge biopython
12 conda install -c conda-forge scikit-learn
13 conda install -c conda-forge plotly
14
15 # Install development tools
16 conda install black flake8 jupyterlab
17

Pro Tip
Always create a new environment for each research project to maintain clean
dependencies

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 25 / 143


Setting up the Python Environment

Environment Configuration Files

[Link] - Reproducible Environments


1 name: bioinfo_course
2 channels:
3 - conda-forge
4 - defaults
5 dependencies:
6 - python=3.11
7 - numpy
8 - scipy
9 - pandas
10 - matplotlib
11 - jupyter
12 - biopython
13 - scikit-learn
14 - pip
15 - pip:
16 - some-pypi-only-package
17

Using the Environment File


1 # Create environment from file
2 conda env create -f [Link]
3
4 # Export current environment
5 conda env export > [Link]
6
Abdoulaye Samaké (USTTB/FST) Introduction to Programming 26 / 143
Setting up the Python Environment

Choosing Your Code Editor/IDE

VS Code
❒ Free, lightweight, PyCharm Jupyter Lab
extensible ❒ Professional IDE ❒ Web-based interface
❒ Excellent Python ❒ Powerful debugging ❒ Perfect for exploration
support ❒ Scientific mode ❒ Combines code and
❒ Great for beginners available documentation
and experts ❒ More ❒ Excellent for data
❒ Integrated terminal resource-intensive analysis
and Git ❒ Free community ❒ Less suited for large
❒ Recommended for this edition projects
course

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 27 / 143


Setting up the Python Environment

Configuring VS Code for Scientific Python

Essential VS Code Extensions


❒ Python (Microsoft) - Core Python support
❒ Pylance - Enhanced language features
❒ Jupyter - Notebook support
❒ Python Docstring Generator - Documentation
❒ GitLens - Git integration
❒ Remote - SSH - Remote development

Key VS Code Settings


1 {
2 "[Link]": "~/miniconda3/envs/bioinfo_course/bin/python",
3 "[Link]": true,
4 "[Link]": "black",
5 "[Link]": true,
6 "[Link]": "basic"
7 }
8

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 28 / 143


Setting up the Python Environment

Working with Jupyter Notebooks

Starting Jupyter Lab


1 # Activate your environment first
2 conda activate bioinfo_course
3
4 # Launch Jupyter Lab
5 jupyter lab
6
7 # Or launch classic Jupyter
8 jupyter notebook
9

Jupyter Advantages Jupyter Limitations


❒ Interactive code execution ❒ Not ideal for large projects
❒ Combine code, text, and visualizations ❒ Version control challenges
❒ Perfect for data exploration ❒ Can become disorganized
❒ Great for teaching and collaboration ❒ Execution order matters
❒ Export to various formats ❒ Harder to debug complex code

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 29 / 143


Setting up the Python Environment

Package Management Best Practices

Dependency Management Strategy


❒ Use environment files for reproducibility
❒ Pin important versions for critical packages
❒ Regularly update packages for security and features
❒ Test updates in a separate environment first
❒ Document version requirements in your code

Version Pinning Examples


1 dependencies:
2 - python=3.11
3 - numpy=1.24.* # Allow patch updates
4 - pandas=1.5.3 # Exact version
5 - biopython>=1.80 # Minimum version
6

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 30 / 143


Setting up the Python Environment

Troubleshooting Common Setup Issues

Common Problems
❒ Conda not found: PATH issue Solutions
❒ Permission errors: Install location ❒ Restart terminal after installation
❒ Environment not activating: Shell ❒ Use conda init for shell setup
configuration ❒ Check conda info for configuration
❒ Package conflicts: Incompatible ❒ Create fresh environments for conflicts
versions ❒ Use mamba for faster resolution
❒ Memory issues: Large packages

Useful Diagnostic Commands


1 conda info # System information
2 conda config --show # Configuration
3 which python # Check Python location
4 conda list # Installed packages
5

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 31 / 143


Setting up the Python Environment

Alternative Package Management Tools

pip + venv
Mamba
❒ Python’s built-in solution
❒ Faster alternative to conda
❒ Good for pure Python packages
❒ Same commands as conda
❒ Limited scientific package support
❒ Better dependency resolution
❒ Use when: Working with web
❒ Use when: Conda is too slow
development
❒ Install: conda install -c
❒ Not recommended for scientific
conda-forge mamba
computing

When to Use Each Tool


❒ Conda/Mamba: Scientific computing, data science
❒ pip: Pure Python packages, web frameworks
❒ Both: Use conda first, then pip if package not available

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 32 / 143


Setting up the Python Environment

Verifying Your Python Environment

Comprehensive Verification Script


1 def verify_environment():
2 """Verify all required packages are installed and working."""
3 import sys
4 print(f"Python version: {[Link]}")
5 print(f"Python executable: {[Link]}")
6
7 # Test core scientific packages
8 packages = ['numpy', 'scipy', 'pandas', 'matplotlib',
9 'biopython', 'sklearn', 'jupyter']
10
11 for package in packages:
12 try:
13 __import__(package)
14 print(f" {package:12} - OK")
15 except ImportError:
16 print(f" {package:12} - MISSING")
17
18 # Test basic functionality
19 import numpy as np
20 import pandas as pd
21 print(f"\nNumPy array test: {[Link]([1, 2, 3])}")
22 print("Environment verification complete!")
23
24 if __name__ == "__main__":
25 verify_environment()
26

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 33 / 143


Setting up the Python Environment

Organizing Your Bioinformatics Projects

Recommended Project Structure


1 bioinformatics_project/
2 |-- [Link] # Conda environment
3 |-- [Link] # pip requirements (if needed)
4 |-- [Link] # Project documentation
5 |-- data/ # Raw data (never modify)
6 | |-- raw/
7 | `-- processed/
8 |-- notebooks/ # Jupyter notebooks
9 | |-- 01_data_exploration.ipynb
10 | `-- 02_analysis.ipynb
11 |-- src/ # Source code
12 | |-- __init__.py
13 | |-- data_processing.py
14 | `-- [Link]
15 |-- tests/ # Unit tests
16 |-- results/ # Output files and figures
17 `-- docs/ # Documentation

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 34 / 143


Setting up the Python Environment

Summary: Your Development Environment

What We’ve Accomplished


❒ Installed Miniconda for Python management
❒ Created isolated environments for different projects
❒ Installed essential scientific packages
❒ Set up VS Code for efficient development
❒ Learned Jupyter for interactive analysis
❒ Established best practices for reproducibility

Your Development Workflow


1. conda activate bioinfo_course
2. code . (or open your IDE)
3. Develop and test your code
4. conda deactivate when done

Next Session
Python Fundamentals: Variables, Data Types, and Basic Operations
We’ll start writing actual bioinformatics code!
Abdoulaye Samaké (USTTB/FST) Introduction to Programming 35 / 143
Setting up the Python Environment

Quick Reference Card

Essential Commands
Command Purpose
conda –version Check conda installation
conda create -n env_name python=3.11 Create new environment
conda activate env_name Activate environment
conda deactivate Deactivate environment
conda install package_name Install package
conda list List installed packages
conda env export > [Link] Export environment
conda env create -f [Link] Create from file
jupyter lab Start Jupyter Lab

Getting Help
❒ conda –help - Command help
❒ conda install –help - Package installation help
❒ Conda documentation: [Link]
❒ Stack Overflow - Community support

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 36 / 143


Python Fundamentals

Outline

1 Introduction and Motivation


2 Setting up the Python Environment
3 Python Fundamentals
Variables and Simple Data Types
Lists and if Statements
Dictionaries and User Input
Functions and Modules
4 Practical Aspects of Python Programming
Introduction & Environment Setup
Python Path & Module Discovery
Virtual Environments Management
Module Import Strategies & Best Practices
Summary & Best Practices

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 37 / 143


Python Fundamentals Variables and Simple Data Types

Getting Started with Python

Python Crash Course Approach


“In this chapter you’ll learn to work with variables, which are used to store infor-
mation, and how to use text and numerical data in your programs.”
—Python Crash Course

What We’ll Learn


❒ Using variables to store data
❒ Working with strings and text data
❒ Using numbers in your programs
❒ Naming conventions and best practices

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 38 / 143


Python Fundamentals Variables and Simple Data Types

Variables and Simple Data Types


Storing Information in Variables
1 # Store a DNA sequence in a variable
2 dna_sequence = "ATCGATCG"
3 print(dna_sequence)
4
5 # Store a gene name
6 gene_name = "TP53"
7 print(gene_name)
8
9 # Variables can be changed
10 gene_name = "BRCA1"
11 print(gene_name)
12
13 # Using variables in messages
14 message = f"Analyzing gene {gene_name}"
15 print(message)
16

Variable Naming Rules


❒ Can contain letters, numbers, and underscores
❒ Cannot start with a number
❒ No spaces (use underscores like gene_name)
❒ Avoid Python keywords like print, for, if
❒ Be descriptive but concise
Abdoulaye Samaké (USTTB/FST) Introduction to Programming 39 / 143
Python Fundamentals Variables and Simple Data Types

Working with Strings


Changing Case in Strings
1 # Standardizing DNA sequences
2 sequence = "atcGATcg"
3 print([Link]()) # ATCGATCG
4 print([Link]()) # atcgatcg
5
6 # Formatting gene names
7 gene = "brca1"
8 print([Link]()) # Brca1
9
10 # Personal message example
11 researcher = "ada lovelace"
12 message = f"Hello, {[Link]()}!"
13 print(message) # Hello, Ada Lovelace!
14

Combining Strings (Concatenation)


1 # Building biological identifiers
2 genus = "Homo"
3 species = "sapiens"
4 full_species = genus + " " + species
5 print(full_species) # Homo sapiens
6
7 # Creating analysis messages
8 gene = "TP53"
9 result = "expressed"
10 analysis = gene + " is " + result
11 print(analysis) # TP53 is expressed
12 Abdoulaye Samaké (USTTB/FST) Introduction to Programming 40 / 143
Python Fundamentals Variables and Simple Data Types

Whitespace and F-Strings—Part 1

Adding Whitespace
1 # Tabs and newlines in output
2 print("DNA Bases:\n\tAdenine\n\tThymine\n\tCytosine\n\tGuanine")
3 # DNA Bases:
4 # Adenine
5 # Thymine
6 # Cytosine
7 # Guanine
8
9 # Stripping whitespace from sequences
10 sequence_data = " ATCG \n"
11 clean_sequence = sequence_data.strip()
12 print(f"'{clean_sequence}'") # 'ATCG'
13

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 41 / 143


Python Fundamentals Variables and Simple Data Types

Whitespace and F-Strings—Part 2

F-Strings for Clean Formatting


1 # Formatting biological data
2 gene = "TP53"
3 expression_level = 245.67
4 p_value = 0.0032
5
6 report = f"""
7 Analysis Report for {gene}
8 Expression Level: {expression_level}
9 Significance: {p_value}
10 """
11 print(report)
12
13 # Simple calculations in f-strings
14 gc_count = 450
15 total_bases = 1000
16 print(f"GC Content: {gc_count/total_bases:.1%}") # GC Content: 45.0%
17

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 42 / 143


Python Fundamentals Variables and Simple Data Types

Working with Numbers

Integers and Floats


1 # Basic arithmetic operations
2 print(3 + 2) # 5
3 print(3 - 2) # 1
4 print(3 * 2) # 6
5 print(3 / 2) # 1.5
6
7 # Exponents for scientific calculations
8 print(2 ** 3) # 8
9 print(10 ** 6) # 1000000
10
11 # Order of operations
12 print(2 + 3 * 4) # 14
13 print((2 + 3) * 4) # 20
14
15 # Biological calculations
16 cells_count = 1000000
17 dilution_factor = 10
18 final_count = cells_count / dilution_factor
19 print(f"Final cell count: {final_count}") # Final cell count: 100000.0
20

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 43 / 143


Python Fundamentals Variables and Simple Data Types

Floats and Multiple Assignment

Working with Floating-Point Numbers


1 # Float operations
2 print(0.1 + 0.1) # 0.2
3 print(0.2 + 0.1) # 0.30000000000000004
4 print(4 / 2) # 2.0
5
6 # Concentration calculations
7 stock_concentration = 50.0 # mM
8 dilution_factor = 5
9 working_concentration = stock_concentration / dilution_factor
10 print(f"Working concentration: {working_concentration} mM") # 10.0 mM
11
12 # Making large numbers readable
13 human_genome_size = 3_000_000_000 # 3 billion base pairs
14 print(human_genome_size) # 3000000000
15
16 # Multiple assignment
17 gene, chromosome, position = "TP53", 17, 7668402
18 print(f"{gene} on chromosome {chromosome} at position {position}")
19

Constants
1 MAX_SEQUENCE_LENGTH = 10000 # Constants in all caps
2 AVOGADRO_NUMBER = 6.022e23
3

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 44 / 143


Python Fundamentals Variables and Simple Data Types

Extra: Useful Math Operations

For the Curious - Advanced Operators


1 # Floor division - whole number result
2 print(7 // 2) # 3 (not 3.5)
3
4 # Modulo - remainder after division
5 print(7 % 2) # 1 (remainder)
6
7 # Useful in bioinformatics:
8 total_bases = 100
9 codon_length = 3
10 complete_codons = total_bases // codon_length # 33
11 remaining_bases = total_bases % codon_length # 1

Course Philosophy
We’ll explore these more in later chapters when we need them for specific tasks!

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 45 / 143


Python Fundamentals Variables and Simple Data Types

Introducing Lists

What is a List?
1 # A list stores multiple items in a single variable
2 genes = ['TP53', 'BRCA1', 'EGFR', 'MYC']
3 print(genes) # ['TP53', 'BRCA1', 'EGFR', 'MYC']
4
5 # Accessing elements
6 print(genes[0]) # TP53
7 print(genes[0].upper()) # TP53
8
9 # Using individual items
10 message = f"The first gene is {genes[0]}"
11 print(message) # The first gene is TP53
12
13 # Lists of numbers
14 expression_levels = [245.6, 128.3, 89.7, 456.2]
15 print(expression_levels[1]) # 128.3
16
17 # Mixed data types
18 gene_data = ['TP53', 17, 245.6, True]
19 print(gene_data) # ['TP53', 17, 245.6, True]
20

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 46 / 143


Python Fundamentals Variables and Simple Data Types

List Index Positions

Understanding List Positions


1 genes = ['TP53', 'BRCA1', 'EGFR', 'MYC']
2
3 # Positive indexes (start from beginning)
4 print(genes[0]) # TP53 (1st item)
5 print(genes[1]) # BRCA1 (2nd item)
6 print(genes[2]) # EGFR (3rd item)
7 print(genes[3]) # MYC (4th item)
8
9 # Negative indexes (start from end)
10 print(genes[-1]) # MYC (last item)
11 print(genes[-2]) # EGFR (2nd from last)
12 print(genes[-3]) # BRCA1 (3rd from last)
13 print(genes[-4]) # TP53 (4th from last)
14
15 # Using list items in messages
16 print(f"The tumor suppressor gene is {genes[0]}")
17 print(f"The oncogene is {genes[-1]}")
18

Bioinformatics Application
Use lists to store sequences, gene names, expression values, or any collection of related
biological data.

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 47 / 143


Python Fundamentals Variables and Simple Data Types

Modifying Lists

Changing List Elements


1 genes = ['TP53', 'BRCA1', 'EGFR']
2 print(genes) # ['TP53', 'BRCA1', 'EGFR']
3
4 # Changing elements
5 genes[0] = 'TP53_MUTATED'
6 print(genes) # ['TP53_MUTATED', 'BRCA1', 'EGFR']
7
8 # Adding elements to the end
9 [Link]('MYC')
10 print(genes) # ['TP53_MUTATED', 'BRCA1', 'EGFR', 'MYC']
11
12 # Inserting elements at specific positions
13 [Link](1, 'RB1')
14 print(genes) # ['TP53_MUTATED', 'RB1', 'BRCA1', 'EGFR', 'MYC']
15
16 # Removing elements by position
17 del genes[0]
18 print(genes) # ['RB1', 'BRCA1', 'EGFR', 'MYC']
19

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 48 / 143


Python Fundamentals Variables and Simple Data Types

Removing Items from Lists

Using pop() and remove()


1 genes = ['TP53', 'BRCA1', 'EGFR', 'MYC']
2 print(genes) # ['TP53', 'BRCA1', 'EGFR', 'MYC']
3
4 # pop() removes last item and returns it
5 removed_gene = [Link]()
6 print(genes) # ['TP53', 'BRCA1', 'EGFR']
7 print(removed_gene) # MYC
8
9 # pop() from specific position
10 first_gene = [Link](0)
11 print(f"First gene analyzed: {first_gene}") # First gene analyzed: TP53
12 print(genes) # ['BRCA1', 'EGFR']
13
14 # remove() by value
15 [Link]('BRCA1')
16 print(genes) # ['EGFR']
17
18 # Working with expression data
19 expression_values = [245.6, 128.3, 89.7, 456.2]
20 highest_expression = expression_values.pop()
21 print(f"Highest expression: {highest_expression}") # Highest expression: 456.2
22

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 49 / 143


Python Fundamentals Variables and Simple Data Types

Organizing Lists

Sorting Lists
1 genes = ['EGFR', 'TP53', 'MYC', 'BRCA1']
2
3 # sort() permanently sorts the list
4 [Link]()
5 print(genes) # ['BRCA1', 'EGFR', 'MYC', 'TP53'] (alphabetical)
6
7 # sort() in reverse order
8 [Link](reverse=True)
9 print(genes) # ['TP53', 'MYC', 'EGFR', 'BRCA1']
10
11 # sorted() for temporary sorting
12 genes = ['EGFR', 'TP53', 'MYC', 'BRCA1']
13 print("Original:", genes) # ['EGFR', 'TP53', 'MYC', 'BRCA1']
14 print("Sorted:", sorted(genes)) # ['BRCA1', 'EGFR', 'MYC', 'TP53']
15 print("Original:", genes) # ['EGFR', 'TP53', 'MYC', 'BRCA1']
16
17 # Reverse order
18 [Link]()
19 print(genes) # ['BRCA1', 'MYC', 'TP53', 'EGFR']
20
21 # List length
22 print(f"Number of genes: {len(genes)}") # Number of genes: 4
23

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 50 / 143


Python Fundamentals Variables and Simple Data Types

Practical Bioinformatics Examples

Applying Concepts to Biological Data


1 # DNA sequence analysis
2 sequence = "atcgatcg"
3 clean_sequence = [Link]()
4 gc_count = clean_sequence.count('G') + clean_sequence.count('C')
5 gc_content = gc_count / len(clean_sequence)
6 print(f"Sequence: {clean_sequence}")
7 print(f"GC content: {gc_content:.1%}")
8
9 # Working with gene lists
10 cancer_genes = ['TP53', 'BRCA1', 'EGFR', 'KRAS', 'MYC']
11 print(f"First gene to analyze: {cancer_genes[0]}")
12 print(f"Number of cancer genes: {len(cancer_genes)}")
13
14 # Expression data analysis
15 expression_data = [245.6, 128.3, 89.7, 456.2]
16 average_expression = sum(expression_data) / len(expression_data)
17 print(f"Average expression: {average_expression:.1f}")
18
19 # Building analysis reports
20 gene = "TP53"
21 expression = 245.6
22 report = f"""
23 Gene Expression Report
24 Gene: {gene}
25 Expression Level: {expression}
26 Status: {'Expressed' if expression > 100 else 'Low'}
27 """
28 print(report)
29
Abdoulaye Samaké (USTTB/FST) Introduction to Programming 51 / 143
Python Fundamentals Variables and Simple Data Types

Avoiding Common Errors

Handling List Errors Gracefully


1 # Index Error example
2 genes = ['TP53', 'BRCA1', 'EGFR']
3 # print(genes[3]) # This causes an IndexError!
4
5 # Safe way to access list elements
6 if len(genes) > 3:
7 print(genes[3])
8 else:
9 print(f"The list only has {len(genes)} elements")
10
11 # Working with empty lists
12 empty_list = []
13 if empty_list:
14 print(empty_list[0])
15 else:
16 print("The list is empty")
17
18 # Practical bioinformatics example
19 sequences = ['ATCG', 'GGAT', 'CCCT']
20 if sequences:
21 print(f"First sequence: {sequences[0]}")
22 print(f"Last sequence: {sequences[-1]}")
23 else:
24 print("No sequences to analyze")
25

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 52 / 143


Python Fundamentals Variables and Simple Data Types

Practice Exercises

Try These Exercises


1 # Exercise 1: Personal Message
2 researcher = "your name"
3 message = f"Hello {[Link]()}, ready to analyze some DNA?"
4 print(message)
5
6 # Exercise 2: List of Genes
7 genes = ['TP53', 'BRCA1', 'EGFR']
8 print(f"The first gene is {genes[0]}")
9 print(f"The second gene is {genes[1]}")
10 print(f"The third gene is {genes[2]}")
11
12 # Exercise 3: Guest List for Seminar
13 scientists = ['Darwin', 'Curie', 'Einstein']
14 message = f"Dear Dr. {scientists[0]}, you're invited to our bioinformatics seminar."
15 print(message)
16
17 # Exercise 4: Changing Lists
18 scientists[0] = 'Franklin'
19 print(f"Updated list: {scientists}")
20
21 # Exercise 5: DNA Sequence Analysis
22 sequence = "atcGATcg"
23 print(f"Standardized: {[Link]()}")
24 print(f"Length: {len(sequence)} bases")
25

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 53 / 143


Python Fundamentals Variables and Simple Data Types

Summary: Variables and Simple Data Types

What We’ve Learned


❒ Variables: Store and manage data with meaningful names
❒ Strings: Work with text data using methods like upper(), strip(), title()
❒ Numbers: Perform calculations with integers and floats
❒ Lists: Store collections of related data
❒ List Operations: Access, modify, add, remove, and sort elements
❒ F-Strings: Format output cleanly and professionally
Key Bioinformatics Applications
❒ Store DNA sequences and gene names in variables
❒ Use lists for collections of genes or samples
❒ Format analysis reports with f-strings
❒ Perform basic calculations on biological data
❒ Standardize data using string methods
Next: Working with Lists and if Statements
We’ll learn more advanced list operations and how to make decisions in our code
Abdoulaye Samaké (USTTB/FST) Introduction to Programming 54 / 143
Python Fundamentals Variables and Simple Data Types

Quick Reference

Essential Python Commands


Command Purpose
variable = value Store data in a variable
[Link]() Convert to uppercase
[Link]() Convert to lowercase
[Link]() Remove whitespace
f"{var}" Insert variables in strings
list[index] Access list element
[Link](item) Add item to end
[Link](pos, item) Insert item at position
del list[index] Remove item by position
[Link]() Remove and return last item
[Link](value) Remove item by value
[Link]() Sort list permanently
sorted(list) Return sorted copy
len(list) Get number of items
3 + 2, 3 - 2, 3 * 2, 3 / 2 Basic arithmetic

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 55 / 143


Python Fundamentals Lists and if Statements

Organizing and Making Decisions with Data

Python Crash Course Approach


“In this chapter you’ll learn how to loop through an entire list and how to use if
statements to make decisions about your data.”
—Python Crash Course

What We will Learn


❒ Looping through entire lists
❒ Working with numerical lists
❒ Making simple decisions with if statements
❒ Using if statements with lists
❒ Styling your if statements

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 56 / 143


Python Fundamentals Lists and if Statements

Looping Through an Entire List

Using for Loops


1 # Basic for loop structure
2 genes = ['TP53', 'BRCA1', 'EGFR', 'MYC']
3 for gene in genes:
4 print(gene)
5
6 # Output:
7 # TP53
8 # BRCA1
9 # EGFR
10 # MYC
11
12 # Doing more with each item
13 for gene in genes:
14 print(f"Analyzing gene: {gene}")
15 print(f"Finished analyzing {gene}\n")
16
17 # Bioinformatics example: DNA sequences
18 sequences = ['ATCG', 'GGAT', 'CCCT', 'TAAA']
19 for sequence in sequences:
20 gc_content = ([Link]('G') + [Link]('C')) / len(sequence)
21 print(f"Sequence {sequence}: GC content = {gc_content:.1%}")
22

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 57 / 143


Python Fundamentals Lists and if Statements

Doing More Work Within for Loops

Performing Multiple Operations


1 # Comprehensive sequence analysis
2 sequences = ['ATCGATCG', 'GGATCC', 'CCCTAA', 'TAAAGGG']
3
4 for sequence in sequences:
5 print(f"\nAnalyzing: {sequence}")
6 length = len(sequence)
7 a_count = [Link]('A')
8 gc_count = [Link]('G') + [Link]('C')
9 gc_content = gc_count / length
10
11 print(f" Length: {length} bases")
12 print(f" Adenine count: {a_count}")
13 print(f" GC content: {gc_content:.1%}")
14
15 # Building new lists during iteration
16 genes = ['tp53', 'brca1', 'egfr', 'myc']
17 capitalized_genes = []
18
19 for gene in genes:
20 capitalized_genes.append([Link]())
21
22 print(capitalized_genes) # ['TP53', 'BRCA1', 'EGFR', 'MYC']
23

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 58 / 143


Python Fundamentals Lists and if Statements

Making Numerical Lists

Using the range() Function


1 # Basic range() function
2 for value in range(1, 5):
3 print(value)
4 # Output: 1 2 3 4
5
6 # Creating lists of numbers
7 numbers = list(range(1, 6))
8 print(numbers) # [1, 2, 3, 4, 5]
9
10 # Even numbers
11 even_numbers = list(range(2, 11, 2))
12 print(even_numbers) # [2, 4, 6, 8, 10]
13
14 # Bioinformatics application: sample IDs
15 sample_ids = list(range(1, 101)) # IDs for 100 samples
16 print(f"First 5 samples: {sample_ids[:5]}") # [1, 2, 3, 4, 5]
17
18 # Replicate numbers
19 replicates = list(range(1, 4)) # 3 replicates
20 print(f"Replicates: {replicates}") # [1, 2, 3]
21

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 59 / 143


Python Fundamentals Lists and if Statements

Simple Statistics with Numerical Lists

Basic Statistical Operations


1 # Expression data analysis
2 expression_values = [245, 128, 89, 456, 322, 178]
3
4 print(f"Minimum expression: {min(expression_values)}") # 89
5 print(f"Maximum expression: {max(expression_values)}") # 456
6 print(f"Total expression: {sum(expression_values)}") # 1418
7 print(f"Average expression: {sum(expression_values)/len(expression_values):.1f}") # 236.3
8
9 # Creating and analyzing numerical lists
10 squares = []
11 for value in range(1, 11):
12 [Link](value ** 2)
13
14 print(squares) # [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
15 print(f"Sum of squares: {sum(squares)}") # 385
16
17 # List comprehensions (more concise)
18 squares = [value**2 for value in range(1, 11)]
19 print(squares) # [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
20

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 60 / 143


Python Fundamentals Lists and if Statements

Working with Part of a List

Slicing Lists
1 genes = ['TP53', 'BRCA1', 'EGFR', 'MYC', 'KRAS', 'PTEN']
2
3 # Slicing a list
4 print(genes[0:3]) # ['TP53', 'BRCA1', 'EGFR'] (positions 0-2)
5 print(genes[1:4]) # ['BRCA1', 'EGFR', 'MYC'] (positions 1-3)
6 print(genes[:4]) # ['TP53', 'BRCA1', 'EGFR', 'MYC'] (start to 3)
7 print(genes[2:]) # ['EGFR', 'MYC', 'KRAS', 'PTEN'] (position 2 to end)
8 print(genes[-3:]) # ['MYC', 'KRAS', 'PTEN'] (last three)
9
10 # Looping through a slice
11 print("First three genes to analyze:")
12 for gene in genes[:3]:
13 print(f"- {gene}")
14
15 # Copying a list
16 genes_backup = genes[:] # Creates a separate copy
17 genes_backup.append('AKT1')
18 print(f"Original: {genes}") # Unchanged
19 print(f"Backup: {genes_backup}") # Has AKT1
20

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 61 / 143


Python Fundamentals Lists and if Statements

Introduction to if Statements

Simple Conditional Tests


1 # Basic if statement
2 expression = 245
3 if expression > 200:
4 print("This gene is highly expressed!")
5
6 # Conditional tests
7 gene = 'TP53'
8 if gene == 'TP53':
9 print("This is a tumor suppressor gene")
10
11 if [Link]() == 'tp53':
12 print("Case-insensitive comparison works!")
13
14 # Numerical comparisons
15 p_value = 0.03
16 if p_value < 0.05:
17 print("Result is statistically significant")
18
19 # Checking for inequality
20 mutated = True
21 if mutated != False:
22 print("This gene has mutations")
23

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 62 / 143


Python Fundamentals Lists and if Statements

if-else Statements

Making Decisions with Two Outcomes


1 # Basic if-else structure
2 expression = 150
3 if expression > 200:
4 print("Gene is highly expressed")
5 else:
6 print("Gene has normal expression")
7
8 # Bioinformatics examples
9 gc_content = 0.45
10 if gc_content > 0.5:
11 print("High GC content")
12 else:
13 print("Normal GC content")
14
15 # Age classification in clinical data
16 age = 65
17 if age >= 65:
18 print("Patient is elderly")
19 else:
20 print("Patient is not elderly")
21
22 # Statistical significance
23 p_value = 0.08
24 if p_value < 0.05:
25 print("Significant result - publish!")
26 else:
27 print("Not significant - need more data")
28

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 63 / 143


Python Fundamentals Lists and if Statements

The if-elif-else Chain—Part 1

Testing Multiple Conditions


1 # Multiple conditions with elif
2 expression = 320
3 if expression > 400:
4 print("Very high expression")
5 elif expression > 200:
6 print("High expression") # This will execute
7 elif expression > 100:
8 print("Moderate expression")
9 else:
10 print("Low expression")
11
12 # Gene function classification
13 gene_function = 'tumor_suppressor'
14 if gene_function == 'oncogene':
15 print("Promotes cancer growth")
16 elif gene_function == 'tumor_suppressor':
17 print("Prevents cancer growth") # This executes
18 elif gene_function == 'dna_repair':
19 print("Repairs DNA damage")
20 else:
21 print("Unknown function")
22

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 64 / 143


Python Fundamentals Lists and if Statements

The if-elif-else Chain—Part 2

Testing Multiple Conditions


1 # Multiple numerical conditions
2 age = 45
3 if age < 18:
4 print("Pediatric patient")
5 elif age < 65:
6 print("Adult patient") # This executes
7 else:
8 print("Geriatric patient")
9

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 65 / 143


Python Fundamentals Lists and if Statements

Using if Statements with Lists

Checking for Special Items


1 # Checking for specific values
2 genes = ['TP53', 'BRCA1', 'EGFR', 'MYC']
3 for gene in genes:
4 if gene == 'TP53':
5 print(f"{gene} is a key tumor suppressor")
6 else:
7 print(f"Analyzing {gene}")
8
9 # Checking that a list is not empty
10 expression_data = []
11 if expression_data:
12 print("Analyzing expression data...")
13 else:
14 print("No expression data available") # This executes
15
16 # Using multiple lists
17 cancer_genes = ['TP53', 'BRCA1', 'EGFR']
18 genes_to_test = ['TP53', 'MYC', 'AKT1', 'BRCA1']
19
20 for gene in genes_to_test:
21 if gene in cancer_genes:
22 print(f"{gene} is a known cancer gene")
23 else:
24 print(f"{gene} requires further investigation")
25

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 66 / 143


Python Fundamentals Lists and if Statements

Styling Your if Statements

Python Style Guidelines


1 # Good style - simple comparisons
2 expression = 245
3 if expression > 200:
4 print("High expression")
5
6 # Good style - meaningful variable names
7 is_significant = True
8 if is_significant:
9 print("Result is significant")
10
11 # Avoid - too much whitespace
12 if expression > 200 :
13 print("High expression")
14
15 # Good - testing multiple conditions clearly
16 age = 45
17 has_cancer_history = True
18 if age > 40 and has_cancer_history:
19 print("High risk patient - recommend screening")
20
21 # Using parentheses for clarity
22 if (age > 65) or (has_cancer_history and age > 40):
23 print("Eligible for advanced screening")
24

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 67 / 143


Python Fundamentals Lists and if Statements

Comprehensive Bioinformatics Example

Gene Expression Analysis Pipeline


1 # Sample gene expression data
2 genes = ['TP53', 'BRCA1', 'EGFR', 'MYC', 'KRAS', 'PTEN']
3 expression_levels = [245, 89, 456, 322, 178, 210]
4 p_values = [0.001, 0.23, 0.045, 0.003, 0.067, 0.012]
5
6 print("GENE EXPRESSION ANALYSIS REPORT")
7 print("=" * 40)
8
9 # Analyze each gene
10 for i in range(len(genes)):
11 gene = genes[i]
12 expression = expression_levels[i]
13 p_value = p_values[i]
14
15 print(f"\nGene: {gene}")
16 print(f"Expression: {expression}")
17 print(f"P-value: {p_value}")
18
19 # Classification logic
20 if expression > 300 and p_value < 0.05:
21 print("Status: HIGHLY EXPRESSED AND SIGNIFICANT")
22 elif expression > 200 and p_value < 0.05:
23 print("Status: Moderately expressed and significant")
24 elif p_value < 0.05:
25 print("Status: Significant but low expression")
26 else:
27 print("Status: Not significant")
28
29 # Special handling for cancer genes
30 if gene in ['TP53', 'BRCA1', 'EGFR']:
31 print("Note: Known cancer-related gene")
32

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 68 / 143


Python Fundamentals Lists and if Statements

Advanced List Operations

List Comprehensions and Enumerate


1 # List comprehension for transformations
2 genes = ['tp53', 'brca1', 'egfr']
3 uppercase_genes = [[Link]() for gene in genes]
4 print(uppercase_genes) # ['TP53', 'BRCA1', 'EGFR']
5
6 # Filtering with list comprehensions
7 expression_levels = [245, 89, 456, 322, 178]
8 high_expression = [expr for expr in expression_levels if expr > 200]
9 print(high_expression) # [245, 456, 322]
10
11 # Using enumerate for index and value
12 genes = ['TP53', 'BRCA1', 'EGFR']
13 for index, gene in enumerate(genes):
14 print(f"Position {index}: {gene}")
15
16 # Bioinformatics application with enumerate
17 sequences = ['ATCG', 'GGAT', 'CCCT']
18 for sample_num, sequence in enumerate(sequences, start=1):
19 gc_content = ([Link]('G') + [Link]('C')) / len(sequence)
20 print(f"Sample {sample_num}: {sequence} (GC: {gc_content:.1%})")
21

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 69 / 143


Python Fundamentals Lists and if Statements

Tuples - Immutable Sequences

Working with Tuples


1 # Defining tuples
2 chromosome_sizes = (249, 242, 198, 190, 181) # in million bp
3 print(chromosome_sizes[0]) # 249
4
5 # Tuples are immutable
6 # chromosome_sizes[0] = 250 # This would cause an error!
7
8 # Looping through tuples
9 for size in chromosome_sizes:
10 print(f"Chromosome size: {size} Mbp")
11
12 # Using tuples for fixed data
13 gene_locations = {
14 'TP53': (17, 7668402),
15 'BRCA1': (17, 43044295),
16 'EGFR': (7, 55019017)
17 }
18
19 for gene, location in gene_locations.items():
20 chromosome, position = location
21 print(f"{gene} is on chromosome {chromosome} at position {position}")
22
23 # Tuple unpacking
24 coordinates = (17, 7668402)
25 chromosome, position = coordinates
26 print(f"Chromosome: {chromosome}, Position: {position}")
27

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 70 / 143


Python Fundamentals Lists and if Statements

Practice Exercises

1 # Exercise 1: Gene Analysis Loop


2 genes = ['TP53', 'BRCA1', 'EGFR', 'MYC']
3 for gene in genes:
4 print(f"Now analyzing {gene}...")
5
6 # Exercise 2: Expression Classification
7 expressions = [150, 280, 90, 420, 180]
8 for expr in expressions:
9 if expr > 300:
10 print(f"{expr}: High expression")
11 elif expr > 150:
12 print(f"{expr}: Moderate expression")
13 else:
14 print(f"{expr}: Low expression")
15
16 # Exercise 3: Sequence GC Analysis
17 sequences = ['ATCG', 'GGGG', 'AAAA', 'CCCT']
18 for seq in sequences:
19 gc = ([Link]('G') + [Link]('C')) / len(seq)
20 if gc > 0.6:
21 print(f"{seq}: High GC")
22 else:
23 print(f"{seq}: Normal GC")
24
25 # Exercise 4: Patient Risk Assessment
26 ages = [35, 68, 42, 55, 71]
27 for age in ages:
28 if age >= 65:
29 print(f"Age {age}: High risk")
30 elif age >= 50:
31 print(f"Age {age}: Medium risk")
32 else:
33 print(f"Age {age}: Low risk")
34

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 71 / 143


Python Fundamentals Lists and if Statements

Summary: Lists and if Statements

What We’ve Learned


❒ Looping: Using for loops to work through entire lists
❒ Numerical Lists: Creating and analyzing lists of numbers
❒ List Slicing: Working with specific parts of lists
❒ Conditional Tests: Making comparisons with ==, !=, >, <, >=, <=
❒ if Statements: Making simple decisions in code
❒ if-elif-else Chains: Handling multiple conditions
❒ Lists with if: Checking for special items in lists

Key Bioinformatics Applications


❒ Process multiple sequences or genes efficiently
❒ Classify expression levels automatically
❒ Filter significant results from large datasets
❒ Make decisions based on statistical thresholds
❒ Handle different biological conditions appropriately

Next: Dictionaries
Abdoulaye and User Input
Samaké (USTTB/FST) Introduction to Programming 72 / 143
Python Fundamentals Lists and if Statements

Quick Reference

Essential Commands Covered


Command Purpose
for item in list: Loop through each item
range(start, stop) Generate number sequences
list(range()) Create list of numbers
min(), max(), sum() Basic statistics
list[start:end] Slice a list
if condition: Simple conditional
if-elif-else: Multiple conditions
==, !=, >, <, >=, <= Comparison operators
and, or Combine conditions
item in list Check list membership
list comprehension Create lists concisely
enumerate() Get index and value
tuple = (a, b, c) Create immutable sequence

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 73 / 143


Python Fundamentals Dictionaries and User Input

Storing Complex Data and Interactive Programs

Python Crash Course Approach


“In this chapter you’ll learn to use dictionaries to store pieces of connected infor-
mation, and how to accept user input so your programs can be interactive.”
—Python Crash Course

What We’ll Learn


❒ Working with dictionaries to store connected information
❒ Looping through dictionaries
❒ Accepting user input and storing it
❒ Using while loops for repetitive tasks
❒ Combining dictionaries with lists and other structures

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 74 / 143


Python Fundamentals Dictionaries and User Input

Working with Dictionaries

Storing Connected Information


1 # A simple dictionary
2 gene_info = {'name': 'TP53', 'chromosome': 17, 'function': 'tumor_suppressor'}
3 print(gene_info['name']) # TP53
4 print(gene_info['chromosome']) # 17
5
6 # Adding new key-value pairs
7 gene_info['position'] = 7668402
8 gene_info['expression'] = 245.6
9 print(gene_info)
10
11 # Starting with an empty dictionary
12 patient_data = {}
13 patient_data['age'] = 45
14 patient_data['diagnosis'] = 'breast_cancer'
15 patient_data['treatment'] = 'chemotherapy'
16
17 # Modifying values
18 gene_info['expression'] = 280.3 # Update expression level
19 print(f"Updated expression: {gene_info['expression']}")
20

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 75 / 143


Python Fundamentals Dictionaries and User Input

More Dictionary Operations

Removing Key-Value Pairs and Handling Errors


1 gene_info = {'name': 'TP53', 'chromosome': 17, 'expression': 245.6}
2
3 # Removing key-value pairs
4 del gene_info['expression']
5 print(gene_info) # {'name': 'TP53', 'chromosome': 17}
6
7 # Using get() to avoid errors
8 expression = gene_info.get('expression', 'No expression data')
9 print(expression) # No expression data
10
11 # The get() method is safer than direct access
12 # This would cause an error: print(gene_info['expression'])
13
14 # Dictionary of similar objects
15 expression_levels = {
16 'TP53': 245.6,
17 'BRCA1': 128.3,
18 'EGFR': 456.2,
19 'MYC': 322.1
20 }
21
22 print(f"TP53 expression: {expression_levels['TP53']}")
23 print(f"BRCA1 expression: {expression_levels.get('BRCA1', 'No data')}")
24

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 76 / 143


Python Fundamentals Dictionaries and User Input

Looping Through Dictionaries

Different Ways to Loop Through Dictionaries


1 gene_info = {
2 'name': 'TP53',
3 'chromosome': 17,
4 'position': 7668402,
5 'function': 'tumor_suppressor'
6 }
7
8 # Looping through all key-value pairs
9 for key, value in gene_info.items():
10 print(f"{key}: {value}")
11
12 # Looping through all keys
13 for key in gene_info.keys():
14 print(f"Key: {key}")
15
16 # Looping through all values
17 for value in gene_info.values():
18 print(f"Value: {value}")
19
20 # Looping through keys in sorted order
21 for key in sorted(gene_info.keys()):
22 print(f"{key}: {gene_info[key]}")
23

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 77 / 143


Python Fundamentals Dictionaries and User Input

Nesting in Dictionaries

Storing More Complex Data Structures


1 # A list of dictionaries
2 genes = [
3 {'name': 'TP53', 'chromosome': 17, 'expression': 245.6},
4 {'name': 'BRCA1', 'chromosome': 17, 'expression': 128.3},
5 {'name': 'EGFR', 'chromosome': 7, 'expression': 456.2}
6 ]
7
8 # Accessing nested data
9 for gene in genes:
10 print(f"Gene: {gene['name']}")
11 print(f"Expression: {gene['expression']}\n")
12
13 # A dictionary of lists
14 patient_data = {
15 'lab_results': [120, 135, 118, 142],
16 'medications': ['aspirin', 'statins', 'beta_blockers'],
17 'visits': ['2023-01-15', '2023-02-20', '2023-03-25']
18 }
19
20 print(f"Latest lab result: {patient_data['lab_results'][-1]}")
21 print(f"First medication: {patient_data['medications'][0]}")
22

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 78 / 143


Python Fundamentals Dictionaries and User Input

User Input and While Loops

Accepting User Input


1 # Basic user input
2 gene_name = input("Please enter a gene name: ")
3 print(f"Analyzing gene: {gene_name}")
4
5 # Numerical input
6 expression = input("Enter expression level: ")
7 expression = float(expression) # Convert to number
8 print(f"Expression level: {expression}")
9
10 # Multiple inputs in one line
11 data = input("Enter gene name and expression (separated by space): ")
12 parts = [Link]()
13 gene_name = parts[0]
14 expression = float(parts[1])
15 print(f"Gene: {gene_name}, Expression: {expression}")
16
17 # Bioinformatics example
18 sequence = input("Enter DNA sequence: ").upper()
19 gc_content = ([Link]('G') + [Link]('C')) / len(sequence)
20 print(f"GC content: {gc_content:.1%}")
21

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 79 / 143


Python Fundamentals Dictionaries and User Input

Introduction to While Loops

Repeating Actions with While Loops


1 # Basic while loop
2 current_number = 1
3 while current_number <= 5:
4 print(current_number)
5 current_number += 1
6
7 # User-controlled loop
8 genes = []
9 print("Enter gene names (type 'quit' to finish):")
10
11 gene_name = ""
12 while gene_name != 'quit':
13 gene_name = input("Gene name: ")
14 if gene_name != 'quit':
15 [Link](gene_name)
16
17 print(f"Genes to analyze: {genes}")
18
19 # Counting with while
20 count = 0
21 expression_values = [245, 128, 456, 322, 178]
22 while count < len(expression_values):
23 print(f"Sample {count+1}: {expression_values[count]}")
24 count += 1
25

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 80 / 143


Python Fundamentals Dictionaries and User Input

Using Flags and Break Statements

Controlling While Loops


1 # Using a flag to control the loop
2 active = True
3 patients = []
4
5 while active:
6 patient_id = input("Enter patient ID (or 'quit' to finish): ")
7
8 if patient_id == 'quit':
9 active = False
10 else:
11 [Link](patient_id)
12 print(f"Added patient {patient_id}")
13
14 print(f"Total patients: {len(patients)}")
15
16 # Using break to exit
17 while True:
18 sequence = input("Enter DNA sequence (or 'done' to finish): ")
19
20 if sequence == 'done':
21 break
22
23 sequence = [Link]()
24 if all(base in 'ATCG' for base in sequence):
25 gc_content = ([Link]('G') + [Link]('C')) / len(sequence)
26 print(f"Valid sequence. GC content: {gc_content:.1%}")
27 else:
28 print("Invalid DNA sequence - only A, T, C, G allowed")
29
30 print("Sequence analysis complete!")
31

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 81 / 143


Python Fundamentals Dictionaries and User Input

Using Continue in Loops

Skipping Iterations with Continue


1 # Skipping specific values with continue
2 expression_values = [245, -1, 128, 456, -1, 322]
3
4 print("Processing expression values (skipping missing data):")
5 current_number = 0
6 while current_number < len(expression_values):
7 value = expression_values[current_number]
8 current_number += 1
9
10 if value == -1: # -1 represents missing data
11 print("Skipping missing value")
12 continue
13
14 print(f"Processing value: {value}")
15
16 # User input with validation
17 sequences = []
18 while len(sequences) < 3:
19 sequence = input(f"Enter DNA sequence {len(sequences)+1}: ").upper()
20
21 if not all(base in 'ATCG' for base in sequence):
22 print("Invalid sequence - only A, T, C, G allowed")
23 continue
24
25 [Link](sequence)
26 print(f"Added sequence: {sequence}")
27
28 print(f"Collected {len(sequences)} valid sequences")
29
Abdoulaye Samaké (USTTB/FST) Introduction to Programming 82 / 143
Python Fundamentals Dictionaries and User Input

Comprehensive Bioinformatics Example—Part 1

Gene Database with User Interaction


1 # Gene database application
2 gene_database = []
3
4 print("=== GENE DATABASE MANAGER ===")
5 print("Commands: add, view, search, quit")
6
7 while True:
8 command = input("\nEnter command: ").lower()
9
10 if command == 'quit':
11 break
12
13 elif command == 'add':
14 gene_name = input("Gene name: ").upper()
15 chromosome = input("Chromosome: ")
16 function = input("Function: ")
17
18 gene_data = {
19 'name': gene_name,
20 'chromosome': chromosome,
21 'function': function
22 }
23 gene_database.append(gene_data)
24 print(f"Added {gene_name} to database")
25
26 elif command == 'view':
27 print("\n=== GENE DATABASE ===")
28 for gene in gene_database:
29 print(f"Name: {gene['name']}")
30 print(f"Chromosome: {gene['chromosome']}")
31 print(f"Function: {gene['function']}\n")
32

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 83 / 143


Python Fundamentals Dictionaries and User Input

Comprehensive Bioinformatics Example—Part 2

Gene Database with User Interaction


1 elif command == 'search':
2 search_name = input("Enter gene name to search: ").upper()
3 found = False
4 for gene in gene_database:
5 if gene['name'] == search_name:
6 print(f"Found: {gene}")
7 found = True
8 break
9 if not found:
10 print("Gene not found in database")
11
12 else:
13 print("Invalid command")
14
15 print("Database session ended.")
16

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 84 / 143


Python Fundamentals Dictionaries and User Input

Advanced Dictionary Techniques

Dictionary Comprehensions and Set Operations


1 # Dictionary comprehension
2 genes = ['TP53', 'BRCA1', 'EGFR', 'MYC']
3 expression_levels = [245, 128, 456, 322]
4
5 # Create dictionary from two lists
6 gene_expression = {genes[i]: expression_levels[i] for i in range(len(genes))}
7 print(gene_expression) # {'TP53': 245, 'BRCA1': 128, 'EGFR': 456, 'MYC': 322}
8
9 # Filtering dictionaries
10 high_expression = {gene: expr for gene, expr in gene_expression.items() if expr > 200}
11 print(high_expression) # {'TP53': 245, 'EGFR': 456, 'MYC': 322}
12
13 # Working with sets to find unique values
14 cancer_genes = {'TP53', 'BRCA1', 'EGFR', 'MYC'}
15 tested_genes = {'TP53', 'MYC', 'AKT1', 'RB1'}
16
17 common_genes = cancer_genes & tested_genes # Intersection
18 print(f"Tested cancer genes: {common_genes}") # {'TP53', 'MYC'}
19
20 all_genes = cancer_genes | tested_genes # Union
21 print(f"All unique genes: {all_genes}")
22

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 85 / 143


Python Fundamentals Dictionaries and User Input

Input Validation and Error Handling—Part 1


Robust User Input with Validation
1 # Validating numerical input
2 def get_positive_number(prompt):
3 while True:
4 try:
5 value = float(input(prompt))
6 if value > 0:
7 return value
8 else:
9 print("Please enter a positive number.")
10 except ValueError:
11 print("Please enter a valid number.")
12
13 # Usage
14 expression = get_positive_number("Enter expression level: ")
15 print(f"Expression level: {expression}")
16
17 # Validating DNA sequences
18 def get_dna_sequence(prompt):
19 while True:
20 sequence = input(prompt).upper().strip()
21 if all(base in 'ATCG' for base in sequence):
22 return sequence
23 else:
24 print("Invalid DNA sequence. Only A, T, C, G allowed.")
25
26 # Usage
27 dna_sequence = get_dna_sequence("Enter DNA sequence: ")
28 gc_content = (dna_sequence.count('G') + dna_sequence.count('C')) / len(dna_sequence)
29 print(f"GC content: {gc_content:.1%}")
30
Abdoulaye Samaké (USTTB/FST) Introduction to Programming 86 / 143
Python Fundamentals Dictionaries and User Input

Input Validation and Error Handling—Part 2

Robust User Input with Validation


1 # Menu system with validation
2 def get_menu_choice(options):
3 while True:
4 print("\nOptions:")
5 for key, description in [Link]():
6 print(f"{key}: {description}")
7
8 choice = input("Enter your choice: ").lower()
9 if choice in options:
10 return choice
11 else:
12 print("Invalid choice. Please try again.")
13

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 87 / 143


Python Fundamentals Dictionaries and User Input

Practical Bioinformatics Application—Part 1


Patient Data Management System
1 # Patient data management system
2 patients = {}
3
4 print("=== PATIENT DATA MANAGEMENT ===")
5 while True:
6 print("\n1. Add patient")
7 print("2. View patient")
8 print("3. Add lab result")
9 print("4. List all patients")
10 print("5. Quit")
11
12 choice = input("Choose option (1-5): ")
13
14 if choice == '5':
15 break
16
17 elif choice == '1':
18 patient_id = input("Patient ID: ")
19 patients[patient_id] = {
20 'name': input("Patient name: "),
21 'age': int(input("Age: ")),
22 'diagnosis': input("Diagnosis: "),
23 'lab_results': []
24 }
25 print(f"Added patient {patient_id}")
26

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 88 / 143


Python Fundamentals Dictionaries and User Input

Practical Bioinformatics Application—Part 2


Patient Data Management System
1 elif choice == '2':
2 patient_id = input("Patient ID: ")
3 if patient_id in patients:
4 patient = patients[patient_id]
5 print(f"\nName: {patient['name']}")
6 print(f"Age: {patient['age']}")
7 print(f"Diagnosis: {patient['diagnosis']}")
8 print(f"Lab results: {patient['lab_results']}")
9 else:
10 print("Patient not found")
11
12 elif choice == '3':
13 patient_id = input("Patient ID: ")
14 if patient_id in patients:
15 lab_value = float(input("Lab result: "))
16 patients[patient_id]['lab_results'].append(lab_value)
17 print("Lab result added")
18 else:
19 print("Patient not found")
20
21 elif choice == '4':
22 print("\nAll Patients:")
23 for patient_id, info in [Link]():
24 print(f"{patient_id}: {info['name']}")
25
26 print("System closed.")
27

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 89 / 143


Python Fundamentals Dictionaries and User Input

Practice Exercises

1 # Exercise 1: Gene Information Dictionary


2 gene = {}
3 gene['name'] = input("Enter gene name: ")
4 gene['chromosome'] = input("Enter chromosome: ")
5 gene['function'] = input("Enter function: ")
6 print(f"Gene data: {gene}")
7
8 # Exercise 2: Expression Analysis
9 expressions = {'TP53': 245, 'BRCA1': 128, 'EGFR': 456}
10 for gene, expr in [Link]():
11 if expr > 200:
12 print(f"{gene}: High expression")
13 else:
14 print(f"{gene}: Normal expression")
15
16 # Exercise 3: Sequence Collector
17 sequences = []
18 while True:
19 seq = input("Enter DNA sequence (or 'done'): ").upper()
20 if seq == 'DONE':
21 break
22 [Link](seq)
23 print(f"Collected {len(sequences)} sequences")
24
25 # Exercise 4: Patient Data
26 patients = {}
27 while True:
28 id = input("Enter patient ID (or 'quit'): ")
29 if id == 'quit':
30 break
31 patients[id] = {
32 'name': input("Name: "),
33 'age': int(input("Age: "))
34 }
35 print(f"Registered {len(patients)} patients")
36
Abdoulaye Samaké (USTTB/FST) Introduction to Programming 90 / 143
Python Fundamentals Dictionaries and User Input

Summary: Dictionaries and User Input

What We’ve Learned


❒ Dictionaries: Store connected information as key-value pairs
❒ Dictionary Operations: Adding, modifying, and accessing values
❒ Looping Through Dictionaries: Using items(), keys(), and values()
❒ Nesting: Storing lists and dictionaries within other structures
❒ User Input: Making programs interactive with input()
❒ While Loops: Repeating code while conditions are true
❒ Program Control: Using break, continue, and flags
❒ Input Validation: Ensuring user input is correct and safe
Key Bioinformatics Applications
❒ Store complex gene information in dictionaries
❒ Create interactive data analysis tools
❒ Build patient or sample databases
❒ Validate biological data input
❒ Create menu-driven analysis pipelines
Abdoulaye Samaké (USTTB/FST) Introduction to Programming 91 / 143
Python Fundamentals Dictionaries and User Input

Quick Reference

Essential Commands Covered


Command Purpose
dict = {key: value} Create dictionary
dict[key] = value Add/update key-value pair
[Link](key, default) Safe value access
del dict[key] Remove key-value pair
for key, value in [Link](): Loop through pairs
for key in [Link](): Loop through keys
for value in [Link](): Loop through values
input("prompt") Get user input
while condition: Repeat while true
break Exit loop immediately
continue Skip to next iteration
float(input()) Convert input to number
[Link]() Split input into parts
key in dict Check if key exists

Next: Functions and Modules


We’ll learn to organize code into reusable functions and work with Python modules!
Abdoulaye Samaké (USTTB/FST) Introduction to Programming 92 / 143
Python Fundamentals Functions and Modules

Organizing Code with Functions and Modules

Python Crash Course Approach


“Functions are named blocks of code designed to do one specific job. When you
want to perform that job, you call the function responsible for it.”
Python Crash Course

What We’ll Learn


❒ Writing simple functions and passing information to them
❒ Using return values and making arguments optional
❒ Organizing functions into modules
❒ Styling functions for readability
❒ Building reusable bioinformatics tools

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 93 / 143


Python Fundamentals Functions and Modules

Defining and Calling Simple Functions

Basic Function Structure


1 # Defining a simple function
2 def analyze_sequence():
3 """Display a simple analysis message."""
4 print("Analyzing DNA sequence...")
5 print("Analysis complete!")
6
7 # Calling the function
8 analyze_sequence()
9
10 # Function with parameters
11 def describe_gene(gene_name, chromosome):
12 """Display information about a gene."""
13 print(f"Gene {gene_name} is on chromosome {chromosome}")
14
15 # Calling with arguments
16 describe_gene('TP53', 17)
17 describe_gene('BRCA1', 17)
18 describe_gene('EGFR', 7)
19
20 # Multiple function calls
21 genes = [('TP53', 17), ('BRCA1', 17), ('EGFR', 7)]
22 for gene, chrom in genes:
23 describe_gene(gene, chrom)
24

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 94 / 143


Python Fundamentals Functions and Modules

Passing Arguments to Functions


Positional and Keyword Arguments
1 # Positional arguments (order matters)
2 def analyze_expression(gene, expression, p_value):
3 """Analyze gene expression with statistical significance."""
4 print(f"Gene: {gene}")
5 print(f"Expression: {expression}")
6 print(f"P-value: {p_value}")
7
8 if p_value < 0.05:
9 print("Result is statistically significant")
10 else:
11 print("Result is not significant")
12
13 # Positional arguments
14 analyze_expression('TP53', 245.6, 0.003)
15
16 # Keyword arguments (order doesn't matter)
17 analyze_expression(expression=128.3, gene='BRCA1', p_value=0.23)
18
19 # Mixing positional and keyword arguments
20 analyze_expression('EGFR', p_value=0.045, expression=456.2)
21
22 # Default values
23 def sequence_length(sequence, unit='bp'):
24 """Calculate sequence length with optional unit."""
25 length = len(sequence)
26 print(f"Sequence length: {length} {unit}")
27
28 sequence_length('ATCGATCG') # Uses default 'bp'
29 sequence_length('ATCGATCG', 'bases') # Uses specified unit
30
Abdoulaye Samaké (USTTB/FST) Introduction to Programming 95 / 143
Python Fundamentals Functions and Modules

Return Values—Part 1

Using return Statements


1 # Function that returns a value
2 def calculate_gc_content(sequence):
3 """Calculate GC content of a DNA sequence."""
4 sequence = [Link]()
5 gc_count = [Link]('G') + [Link]('C')
6 return gc_count / len(sequence)
7
8 # Using the return value
9 sequence = "ATCGATCG"
10 gc_content = calculate_gc_content(sequence)
11 print(f"GC content: {gc_content:.1%}")
12
13 # Multiple calculations
14 sequences = ['ATCG', 'GGGG', 'AAAA', 'CCCT']
15 for seq in sequences:
16 gc = calculate_gc_content(seq)
17 print(f"{seq}: {gc:.1%}")
18

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 96 / 143


Python Fundamentals Functions and Modules

Return Values—Part 2

Using return Statements


1 # Multiple calculations
2 sequences = ['ATCG', 'GGGG', 'AAAA', 'CCCT']
3 for seq in sequences:
4 gc = calculate_gc_content(seq)
5 print(f"{seq}: {gc:.1%}")
6
7 # Function with multiple return values
8 def analyze_sequence_comprehensive(sequence):
9 """Comprehensive sequence analysis."""
10 sequence = [Link]()
11 length = len(sequence)
12 gc_content = calculate_gc_content(sequence)
13 a_content = [Link]('A') / length
14
15 return length, gc_content, a_content
16
17 # Unpacking multiple return values
18 length, gc, a_content = analyze_sequence_comprehensive('ATCGATCG')
19 print(f"Length: {length}, GC: {gc:.1%}, A: {a_content:.1%}")
20

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 97 / 143


Python Fundamentals Functions and Modules

Making Arguments Optional—Part 1

Default Parameter Values


1 # Function with optional parameters
2 def analyze_gene(name, chromosome=0, expression=0.0, significance=0.05):
3 """Analyze gene with optional parameters."""
4 print(f"Gene: {name}")
5
6 if chromosome != 0:
7 print(f"Chromosome: {chromosome}")
8
9 if expression > 0:
10 print(f"Expression: {expression}")
11 if expression > 200:
12 print("High expression")
13
14 if significance < 0.05:
15 print("Statistically significant")
16
17 # Different ways to call the function
18 analyze_gene('TP53')
19 analyze_gene('BRCA1', chromosome=17)
20 analyze_gene('EGFR', expression=456.2, significance=0.045)
21 analyze_gene('MYC', 8, 322.1, 0.003)
22

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 98 / 143


Python Fundamentals Functions and Modules

Making Arguments Optional—Part 2

Default Parameter Values


1 # More practical example
2 def sequence_stats(sequence, show_details=False):
3 """Calculate sequence statistics with optional details."""
4 length = len(sequence)
5 gc_content = calculate_gc_content(sequence)
6
7 if show_details:
8 a_count = [Link]('A')
9 t_count = [Link]('T')
10 print(f"A: {a_count}, T: {t_count}")
11
12 return length, gc_content
13
14 # Usage
15 length, gc = sequence_stats('ATCGATCG') # Basic
16 length, gc = sequence_stats('ATCGATCG', show_details=True) # Detailed
17

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 99 / 143


Python Fundamentals Functions and Modules

Practical Bioinformatics Functions—Part 1

Building Reusable Bioinformatics Tools


1 def validate_dna_sequence(sequence):
2 """Validate if a string is a valid DNA sequence."""
3 sequence = [Link]()
4 valid_bases = {'A', 'T', 'C', 'G'}
5 return all(base in valid_bases for base in sequence)
6
7 def reverse_complement(sequence):
8 """Return the reverse complement of a DNA sequence."""
9 complement = {'A': 'T', 'T': 'A', 'C': 'G', 'G': 'C'}
10 return ''.join(complement[base] for base in [Link]()[::-1])
11
12 def calculate_molecular_weight(sequence, sequence_type='dna'):
13 """Calculate approximate molecular weight."""
14 length = len(sequence)
15
16 if sequence_type == 'dna':
17 return length * 330 # Average weight per base pair in Daltons
18 elif sequence_type == 'protein':
19 return length * 110 # Average weight per amino acid
20 else:
21 return 0
22

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 100 / 143


Python Fundamentals Functions and Modules

Practical Bioinformatics Functions—Part 2

Building Reusable Bioinformatics Tools


1 # Using the functions
2 sequence = "ATCGATCG"
3 if validate_dna_sequence(sequence):
4 print(f"Valid sequence: {sequence}")
5 rev_comp = reverse_complement(sequence)
6 print(f"Reverse complement: {rev_comp}")
7 weight = calculate_molecular_weight(sequence, 'dna')
8 print(f"Molecular weight: {weight} Da")
9 else:
10 print("Invalid DNA sequence")
11

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 101 / 143


Python Fundamentals Functions and Modules

Advanced Function Concepts—Part 1

Passing Lists and Modifying Them


1 # Functions can modify lists
2 def standardize_sequences(sequences):
3 """Convert all sequences to uppercase and remove whitespace."""
4 for i in range(len(sequences)):
5 sequences[i] = sequences[i].upper().strip()
6
7 # Original list is modified
8 my_sequences = ['atcg', ' ggat ', 'ccct']
9 print(f"Before: {my_sequences}")
10 standardize_sequences(my_sequences)
11 print(f"After: {my_sequences}")
12
13 # Preventing modification by passing a copy
14 def analyze_sequences(sequences):
15 """Analyze sequences without modifying original."""
16 sequences = sequences[:] # Create a copy
17 standardize_sequences(sequences)
18 # Perform analysis on copy
19 return [calculate_gc_content(seq) for seq in sequences]
20
21 # Passing arbitrary numbers of arguments
22 def analyze_multiple_genes(*genes):
23 """Analyze any number of genes."""
24 print(f"Analyzing {len(genes)} genes:")
25 for gene in genes:
26 print(f"- {gene}")
27

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 102 / 143


Python Fundamentals Functions and Modules

Advanced Function Concepts—Part 2

Passing Lists and Modifying Them


1 analyze_multiple_genes('TP53')
2 analyze_multiple_genes('TP53', 'BRCA1', 'EGFR', 'MYC')
3
4 # Using arbitrary keyword arguments
5 def create_gene_record(**gene_info):
6 """Create a gene record with flexible information."""
7 record = {}
8 for key, value in gene_info.items():
9 record[key] = value
10 return record
11
12 gene_data = create_gene_record(name='TP53', chromosome=17, function='tumor_suppressor')
13 print(gene_data)
14

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 103 / 143


Python Fundamentals Functions and Modules

Storing Functions in Modules—Part 1

Creating and Using Modules


1 # File: bioinformatics_tools.py
2 """
3 A collection of bioinformatics utility functions.
4 """
5
6 def calculate_gc_content(sequence):
7 """Calculate GC content of a DNA sequence."""
8 sequence = [Link]()
9 gc_count = [Link]('G') + [Link]('C')
10 return gc_count / len(sequence)
11
12 def validate_dna_sequence(sequence):
13 """Validate if a string is a valid DNA sequence."""
14 sequence = [Link]()
15 valid_bases = {'A', 'T', 'C', 'G'}
16 return all(base in valid_bases for base in sequence)
17
18 def reverse_complement(sequence):
19 """Return the reverse complement of a DNA sequence."""
20 complement = {'A': 'T', 'T': 'A', 'C': 'G', 'G': 'C'}
21 return ''.join(complement[base] for base in [Link]()[::-1])
22

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 104 / 143


Python Fundamentals Functions and Modules

Storing Functions in Modules—Part 2

Creating and Using Modules


1 # In your main program:
2 import bioinformatics_tools
3
4 sequence = "ATCGATCG"
5 if bioinformatics_tools.validate_dna_sequence(sequence):
6 gc = bioinformatics_tools.calculate_gc_content(sequence)
7 rev_comp = bioinformatics_tools.reverse_complement(sequence)
8 print(f"GC: {gc:.1%}, Reverse complement: {rev_comp}")
9
10 # Alternative import styles
11 from bioinformatics_tools import calculate_gc_content, validate_dna_sequence
12 gc = calculate_gc_content(sequence) # No module prefix needed
13
14 import bioinformatics_tools as bio
15 gc = bio.calculate_gc_content(sequence)
16

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 105 / 143


Python Fundamentals Functions and Modules

The Python Standard Library—Part 1

Useful Built-in Modules


1 # Random module for simulations
2 import random
3
4 # Random sampling
5 sequences = ['ATCG', 'GGAT', 'CCCT', 'TAAA']
6 random_sequence = [Link](sequences)
7 print(f"Random sequence: {random_sequence}")
8
9 # Random expression values for testing
10 random_expression = [Link](100, 500)
11 print(f"Random expression: {random_expression:.1f}")
12
13 # Statistics module
14 import statistics
15
16 expression_data = [245.6, 128.3, 456.2, 322.1, 178.9]
17 mean = [Link](expression_data)
18 median = [Link](expression_data)
19 stdev = [Link](expression_data)
20
21 print(f"Mean: {mean:.1f}, Median: {median:.1f}, Std Dev: {stdev:.1f}")
22

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 106 / 143


Python Fundamentals Functions and Modules

The Python Standard Library—Part 2

Useful Built-in Modules


1 # Math module for advanced calculations
2 import math
3
4 # Log transformations for expression data
5 log_expression = [[Link](x) for x in expression_data]
6 print(f"Log-transformed: {log_expression}")
7
8 # Combinatorics for sequence analysis
9 possible_sequences = [Link](4, 10) # 4 bases, length 10
10 print(f"Possible 10-base sequences: {possible_sequences:,.0f}")
11

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 107 / 143


Python Fundamentals Functions and Modules

Styling Functions—Part 1

Writing Readable and Maintainable Functions


1 # Good function style
2 def analyze_gene_expression(gene_name, expression_level, p_value=0.05):
3 """
4 Analyze gene expression data and determine significance.
5
6 Args:
7 gene_name (str): Name of the gene to analyze
8 expression_level (float): Expression level measurement
9 p_value (float, optional): Significance threshold. Defaults to 0.05.
10
11 Returns:
12 dict: Analysis results including significance and classification
13 """
14 # Descriptive variable names
15 is_significant = p_value < 0.05
16 expression_category = "high" if expression_level > 200 else "normal"
17
18 # Clear, logical organization
19 results = {
20 'gene': gene_name,
21 'expression': expression_level,
22 'significant': is_significant,
23 'category': expression_category
24 }
25
26 return results
27

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 108 / 143


Python Fundamentals Functions and Modules

Styling Functions—Part 2

Writing Readable and Maintainable Functions


1 # Consistent naming conventions
2 def calculate_gc_content(): # snake_case for functions
3 pass
4
5 def validate_dna_sequence():
6 pass
7
8 def reverse_complement_dna():
9 pass
10
11 # Proper spacing and indentation
12 def complex_analysis(sequence, threshold=0.5, detailed=False):
13 if detailed:
14 # Detailed analysis code here
15 pass
16 else:
17 # Basic analysis code here
18 pass
19

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 109 / 143


Python Fundamentals Functions and Modules

Comprehensive Bioinformatics Module—Part 1

Building a Complete Analysis Toolkit


1 # File: genomics_analyzer.py
2 """
3 A comprehensive genomics analysis toolkit.
4 """
5
6 def sequence_statistics(sequence):
7 """Calculate comprehensive sequence statistics."""
8 sequence = [Link]()
9 length = len(sequence)
10
11 base_counts = {}
12 for base in 'ATCG':
13 base_counts[base] = [Link](base)
14
15 gc_content = (base_counts['G'] + base_counts['C']) / length
16
17 return {
18 'length': length,
19 'gc_content': gc_content,
20 'base_counts': base_counts,
21 'at_ratio': base_counts['A'] / base_counts['T'] if base_counts['T'] > 0 else float('inf')
22 }
23

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 110 / 143


Python Fundamentals Functions and Modules

Comprehensive Bioinformatics Module—Part 2

Building a Complete Analysis Toolkit


1 def find_motifs(sequence, motif):
2 """Find all occurrences of a motif in a sequence."""
3 sequence = [Link]()
4 motif = [Link]()
5 positions = []
6
7 start = 0
8 while True:
9 pos = [Link](motif, start)
10 if pos == -1:
11 break
12 [Link](pos)
13 start = pos + 1
14
15 return positions
16

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 111 / 143


Python Fundamentals Functions and Modules

Comprehensive Bioinformatics Module—Part 3

Building a Complete Analysis Toolkit


1 def translate_dna_to_protein(dna_sequence):
2 """Translate DNA sequence to protein (simplified)."""
3 genetic_code = {
4 'ATG': 'M', 'TTT': 'F', 'TTC': 'F', 'TTA': 'L', 'TTG': 'L',
5 'CTT': 'L', 'CTC': 'L', 'CTA': 'L', 'CTG': 'L', 'TCT': 'S',
6 'TCC': 'S', 'TCA': 'S', 'TCG': 'S', 'TAT': 'Y', 'TAC': 'Y',
7 'TAA': '*', 'TAG': '*', 'TGA': '*', 'TGT': 'C', 'TGC': 'C',
8 'TGG': 'W', 'CCT': 'P', 'CCC': 'P', 'CCA': 'P', 'CCG': 'P',
9 'CAT': 'H', 'CAC': 'H', 'CAA': 'Q', 'CAG': 'Q', 'CGT': 'R',
10 'CGC': 'R', 'CGA': 'R', 'CGG': 'R', 'ATT': 'I', 'ATC': 'I',
11 'ATA': 'I', 'ATG': 'M', 'ACT': 'T', 'ACC': 'T', 'ACA': 'T',
12 'ACG': 'T', 'AAT': 'N', 'AAC': 'N', 'AAA': 'K', 'AAG': 'K',
13 'AGT': 'S', 'AGC': 'S', 'AGA': 'R', 'AGG': 'R', 'GTT': 'V',
14 'GTC': 'V', 'GTA': 'V', 'GTG': 'V', 'GCT': 'A', 'GCC': 'A',
15 'GCA': 'A', 'GCG': 'A', 'GAT': 'D', 'GAC': 'D', 'GAA': 'E',
16 'GAG': 'E', 'GGT': 'G', 'GGC': 'G', 'GGA': 'G', 'GGG': 'G'
17 }
18
19 protein = ""
20 for i in range(0, len(dna_sequence)-2, 3):
21 codon = dna_sequence[i:i+3].upper()
22 amino_acid = genetic_code.get(codon, '?')
23 protein += amino_acid
24
25 return protein
26

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 112 / 143


Python Fundamentals Functions and Modules

Using the Bioinformatics Module—Part 1

Practical Application Example


1 import genomics_analyzer as ga
2
3 # Comprehensive sequence analysis
4 sequence = "ATCGATCGATCGATCG"
5
6 # Get sequence statistics
7 stats = ga.sequence_statistics(sequence)
8 print("SEQUENCE STATISTICS:")
9 print(f"Length: {stats['length']} bp")
10 print(f"GC Content: {stats['gc_content']:.1%}")
11 print(f"Base counts: {stats['base_counts']}")
12
13 # Find motifs
14 motif_positions = ga.find_motifs(sequence, "ATCG")
15 print(f"Motif 'ATCG' found at positions: {motif_positions}")
16
17 # Translation example
18 dna_sequence = "ATGGCTTACTGA" # Start codon + some bases + stop codon
19 protein = ga.translate_dna_to_protein(dna_sequence)
20 print(f"DNA: {dna_sequence}")
21 print(f"Protein: {protein}")
22

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 113 / 143


Python Fundamentals Functions and Modules

Using the Bioinformatics Module—Part 1

Practical Application Example


1 # Batch processing multiple sequences
2 sequences = ['ATCGATCG', 'GGATCCGG', 'CCCTAACC']
3 print("\nBATCH ANALYSIS:")
4 for i, seq in enumerate(sequences, 1):
5 stats = ga.sequence_statistics(seq)
6 print(f"Sequence {i}: GC = {stats['gc_content']:.1%}")
7
8 # Building a simple analysis pipeline
9 def analyze_sequence_pipeline(sequence):
10 """Complete analysis pipeline for a DNA sequence."""
11 if not ga.validate_dna_sequence(sequence):
12 return "Invalid DNA sequence"
13
14 stats = ga.sequence_statistics(sequence)
15 motifs = ga.find_motifs(sequence, "ATG") # Start codons
16
17 return {
18 'statistics': stats,
19 'start_codons': motifs,
20 'has_start': len(motifs) > 0
21 }
22
23 result = analyze_sequence_pipeline(sequence)
24 print(f"Pipeline result: {result}")
25

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 114 / 143


Python Fundamentals Functions and Modules

Error Handling in Functions—Part 1

Making Functions Robust


1 def safe_calculate_gc_content(sequence):
2 """Safely calculate GC content with error handling."""
3 if not sequence:
4 raise ValueError("Sequence cannot be empty")
5
6 if not isinstance(sequence, str):
7 raise TypeError("Sequence must be a string")
8
9 sequence = [Link]().strip()
10
11 if not all(base in 'ATCG' for base in sequence):
12 raise ValueError("Sequence contains invalid characters")
13
14 if len(sequence) == 0:
15 raise ValueError("Sequence length cannot be zero")
16
17 gc_count = [Link]('G') + [Link]('C')
18 return gc_count / len(sequence)
19

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 115 / 143


Python Fundamentals Functions and Modules

Error Handling in Functions—Part 2

Making Functions Robust


1 # Using the safe function
2 test_sequences = [
3 "ATCGATCG", # Valid
4 "", # Empty - will raise error
5 "ATCXGATC", # Invalid character
6 12345, # Wrong type
7 "ATCG" # Valid
8 ]
9
10 for seq in test_sequences:
11 try:
12 gc = safe_calculate_gc_content(seq)
13 print(f"Sequence: {seq} -> GC: {gc:.1%}")
14 except (ValueError, TypeError) as e:
15 print(f"Error with '{seq}': {e}")
16
17 # Function with default error value
18 def robust_sequence_length(sequence, default=0):
19 """Get sequence length with default on error."""
20 try:
21 return len(sequence)
22 except TypeError:
23 return default
24
25 print(f"Length: {robust_sequence_length('ATCG')}") # 4
26 print(f"Length: {robust_sequence_length(12345)}") # 0 (default)
27 print(f"Length: {robust_sequence_length(12345, -1)}") # -1 (custom default)
28

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 116 / 143


Python Fundamentals Functions and Modules

Practice Exercises
1 # Exercise 1: Basic Function
2 def describe_gene(gene_name, function):
3 """Describe a gene's function."""
4 print(f"The {gene_name} gene is involved in {function}")
5
6 describe_gene('TP53', 'cell cycle regulation')
7
8 # Exercise 2: Function with Return Value
9 def calculate_at_content(sequence):
10 """Calculate AT content of a DNA sequence."""
11 sequence = [Link]()
12 at_count = [Link]('A') + [Link]('T')
13 return at_count / len(sequence)
14
15 seq = "ATCGATCG"
16 at_content = calculate_at_content(seq)
17 print(f"AT content: {at_content:.1%}")
18
19 # Exercise 3: Function with Default Parameter
20 def analyze_expression(gene, expression, threshold=100):
21 """Analyze if expression is above threshold."""
22 status = "high" if expression > threshold else "low"
23 print(f"{gene}: {expression} ({status})")
24
25 analyze_expression('TP53', 245) # Uses default threshold
26 analyze_expression('BRCA1', 80, 50) # Uses custom threshold
27
28 # Exercise 4: Multiple Return Values
29 def sequence_composition(sequence):
30 """Return length and GC content."""
31 length = len(sequence)
32 gc_content = calculate_gc_content(sequence)
33 return length, gc_content
34
35 length, gc = sequence_composition('ATCGATCG')
36 print(f"Length: {length}, GC: {gc:.1%}")
37

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 117 / 143


Python Fundamentals Functions and Modules

Summary: Functions and Modules


What We’ve Learned
❒ Function Definition: Creating reusable blocks of code with def
❒ Parameters and Arguments: Passing information to functions
❒ Return Values: Getting results back from functions
❒ Default Values: Making parameters optional
❒ Modules: Organizing functions into separate files
❒ Importing: Using functions from modules
❒ Standard Library: Leveraging Python’s built-in modules
❒ Function Style: Writing clear, documented functions

Key Bioinformatics Applications


❒ Create reusable analysis functions for common tasks
❒ Build personal bioinformatics toolkits as modules
❒ Organize complex analysis pipelines into functions
❒ Share and reuse code across different projects
❒ Create robust, error-resistant analysis tools
Abdoulaye Samaké (USTTB/FST) Introduction to Programming 118 / 143
Python Fundamentals Functions and Modules

Quick Reference
Essential Commands Covered
Command Purpose
def function(): Define a function
function() Call a function
def func(param): Function with parameter
func(arg) Call with argument
return value Return a value from function
def func(param=default) Default parameter value
import module Import a module
[Link]() Use module function
from module import func Import specific function
import module as alias Import with alias
*args Arbitrary positional arguments
**kwargs Arbitrary keyword arguments
"""docstring""" Function documentation

Next: Classes and Object-Oriented Programming


We’ll learn to create our own data types and build more complex bioinformatics
applications!
Abdoulaye Samaké (USTTB/FST) Introduction to Programming 119 / 143
Practical Aspects of Python Programming

Outline

1 Introduction and Motivation


2 Setting up the Python Environment
3 Python Fundamentals
Variables and Simple Data Types
Lists and if Statements
Dictionaries and User Input
Functions and Modules
4 Practical Aspects of Python Programming
Introduction & Environment Setup
Python Path & Module Discovery
Virtual Environments Management
Module Import Strategies & Best Practices
Summary & Best Practices

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 120 / 143


Practical Aspects of Python Programming Introduction & Environment Setup

Workshop Overview

What You’ll Learn Today


VS Code Python Environment Management
Module Import Strategies & Best Practices
Python Path & Module Discovery
Virtual Environments (conda/venv)
Large Project Organization
Debugging Import Issues

Why This Matters


80% of Python errors in bioinformatics stem from environment issues
Proper module management saves hours of debugging
Essential for reproducible research
Critical for collaborative projects

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 121 / 143


Practical Aspects of Python Programming Introduction & Environment Setup

VS Code: Your Bioinformatics IDE

Essential VS Code Extensions


Python (Microsoft) - Core Python support
Pylance - Type checking, auto-completion
Jupyter - Notebook integration
GitLens - Version control visualization
Docker - Container management
Rainbow CSV - CSV file visualization

Quick Setup Command


1 # Install essential extensions
2 code --install-extension [Link]
3 code --install-extension [Link]-pylance
4 code --install-extension [Link]

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 122 / 143


Practical Aspects of Python Programming Python Path & Module Discovery

Understanding Python’s Module Search Path

The [Link] List


1 import sys
2 print([Link])
3 # Typical order:
4 # 1. Current directory
5 # 2. PYTHONPATH environment variable
6 # 3. Installation-dependent default paths
7 # 4. site-packages directory

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 123 / 143


Practical Aspects of Python Programming Python Path & Module Discovery

Module Not Found Error: Diagnosis

Common Error Messages


1 ModuleNotFoundError: No module named 'biopython'
2 ImportError: cannot import name 'Seq' from 'Bio'

Diagnosis Steps
Check if module is installed:
1 pip list | grep biopython

Verify Python interpreter:


1 which python

Check [Link] for module location


Test import in interactive mode

VS Code Tip
Use Ctrl+Shift+P =⇒ Python: Select Interpreter to ensure you’re using the correct
Python environment
Abdoulaye Samaké (USTTB/FST) Introduction to Programming 124 / 143
Practical Aspects of Python Programming Python Path & Module Discovery

Adding Custom Paths to [Link]

Temporary Addition (Runtime)


1 import sys
2 [Link]('/path/to/your/modules')
3 # Or insert at beginning for priority
4 [Link](0, '/path/to/your/modules')

Permanent Solutions
PYTHONPATH environment variable:
1 export PYTHONPATH="/path/to/modules:$PYTHONPATH"

.pth files in site-packages


[Link]/[Link] for installable packages

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 125 / 143


Practical Aspects of Python Programming Python Path & Module Discovery

VS Code Workspace Settings for Paths

.vscode/[Link] Configuration
1 {
2 "[Link]": [
3 "./src",
4 "./lib",
5 "../shared_modules"
6 ],
7 "[Link]": [
8 "./src",
9 "./lib"
10 ],
11 "[Link]": {
12 "PYTHONPATH": "${workspaceFolder}/src:${env:PYTHONPATH}"
13 }
14 }

Workspace vs User Settings


Workspace settings: Project-specific (in .vscode folder)
User settings: Global for all projects
Use workspace settings for project-specific paths

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 126 / 143


Practical Aspects of Python Programming Virtual Environments Management

Multiple Python Installations: The Problem

Common Scenario
System Python 3.8 (/usr/bin/python3)
Anaconda Python 3.9 (/opt/anaconda3/bin/python)
Homebrew Python 3.10 (/usr/local/bin/python3)
Project-specific virtual environment

Check Your Environment


1 # Which python am I using?
2 which python
3 python --version
4 # List all python installations
5 whereis python
6 ls -la /usr/bin/python*
7 ls -la ~/anaconda3/bin/python*

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 127 / 143


Practical Aspects of Python Programming Virtual Environments Management

Virtual Environments: Why and How

Benefits of Virtual Environments


Isolation: Project-specific dependencies
Reproducibility: Exact package versions
Cleanliness: No system-wide changes
Multiple versions: Different Python versions per project

Creating Virtual Environments


1 # Using venv (built-in)
2 python -m venv ./venv
3
4 # Using conda
5 conda create -n bioenv python=3.9
6 conda activate bioenv
7
8 # Using pipenv
9 pipenv --python 3.9

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 128 / 143


Practical Aspects of Python Programming Virtual Environments Management

VS Code and Virtual Environments

Selecting Interpreter in VS Code


Ctrl+Shift+P =⇒ "Python: Select Interpreter"
Choose from detected environments
Or enter path manually

Best Practice
Commit .vscode/[Link] to version control for team consistency

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 129 / 143


Practical Aspects of Python Programming Virtual Environments Management

Environment Configuration Files


Requirements Files
1 # [Link]
2 biopython==1.79
3 numpy==1.21.2
4 pandas>=1.3.0,<2.0.0
5 scipy
6 # For development
7 -e . # Install current directory in editable mode

Conda [Link]
1 # [Link]
2 name: bioinformatics
3 channels:
4 - conda-forge
5 - bioconda
6 - defaults
7 dependencies:
8 - python=3.9
9 - biopython
10 - numpy
11 - pandas
12 - jupyter
13 - pip
14 - pip:
15 - some-pip-only-package

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 130 / 143


Practical Aspects of Python Programming Module Import Strategies & Best Practices

Import Statement Variations

Different Import Styles


1 # 1. Basic import
2 import numpy
3
4 # 2. Import with alias
5 import numpy as np
6 import pandas as pd
7
8 # 3. Import specific functions/classes
9 from Bio import SeqIO
10 from [Link] import Seq
11
12 # 4. Import everything (NOT RECOMMENDED)
13 from math import * # Dangerous!
14
15 # 5. Conditional imports
16 try:
17 import fast_library
18 except ImportError:
19 import slow_library as fast_library

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 131 / 143


Practical Aspects of Python Programming Module Import Strategies & Best Practices

Why NOT to Import Everything

Problems with Wildcard Imports


1 from numpy import *
2 from pandas import *
3
4 # Now we have conflicts!
5 # Both numpy and pandas have 'array' function
6 # Which one gets called? Unpredictable!
7 result = array([1, 2, 3]) # Which array function?

Negative Impacts
Namespace pollution: Too many names in current scope
Hidden dependencies: Hard to trace where functions come from
Performance: Slower startup, more memory
Readability: Difficult to understand code origins

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 132 / 143


Practical Aspects of Python Programming Module Import Strategies & Best Practices

Selective Import Benefits


Good Practice Examples
1 # Clear and explicit
2 import numpy as np
3 import pandas as pd
4 from [Link] import Seq
5 from [Link] import SeqRecord
6
7 # Only import what you need
8 from math import sqrt, log10, pi
9 from collections import defaultdict, Counter
10
11 # Local imports (later in file)
12 def complex_analysis():
13 # Import heavy libraries only when needed
14 import tensorflow as tf
15 import torch
16 # ... heavy computation

Performance Impact
import numpy: ~50ms
from numpy import array: ~30ms
Selective imports can reduce startup time by 40%
Abdoulaye Samaké (USTTB/FST) Introduction to Programming 133 / 143
Practical Aspects of Python Programming Module Import Strategies & Best Practices

Multiple Imports on One Line

Acceptable vs Problematic
1 # ACCEPTABLE: Related modules from same package
2 from Bio import SeqIO, SeqRecord, Seq
3 from sklearn import metrics, preprocessing, model_selection
4
5 # PROBLEMATIC: Unrelated modules
6 import os, sys, numpy, pandas, matplotlib # AVOID!
7
8 # BETTER: Separate lines
9 import os
10 import sys
11 import numpy as np
12 import pandas as pd
13 import [Link] as plt

PEP 8 Recommendation
"Imports should usually be on separate lines, but putting multiple imports on one
line is acceptable when importing multiple items from the same module."

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 134 / 143


Practical Aspects of Python Programming Module Import Strategies & Best Practices

Import Order Convention (PEP 8)


Standard Import Order
1 # 1. Standard library imports
2 import os
3 import sys
4 import json
5 from typing import List, Dict
6
7 # 2. Third-party imports
8 import numpy as np
9 import pandas as pd
10 from Bio import SeqIO
11
12 # 3. Local application/library imports
13 from . import my_module
14 from .utils import helper_function
15 import config

VS Code Auto-organize
Ctrl+Shift+P =⇒ "Python: Sort Imports"
Uses isort automatically
Configurable via .[Link]
Abdoulaye Samaké (USTTB/FST) Introduction to Programming 135 / 143
Practical Aspects of Python Programming Module Import Strategies & Best Practices

__init__.py Files: Purpose & Usage


Package Initialization Files
1 # src/analysis/__init__.py
2
3 # Version
4 __version__ = "1.0.0"
5
6 # Import key functions for easier access
7 from .sequence_analysis import calculate_gc_content
8 from .statistical_tests import t_test_expression
9
10 # Define what gets imported with "from analysis import *"
11 __all__ = ['calculate_gc_content', 't_test_expression']

Usage Benefits
1 # Instead of
2 from [Link].sequence_analysis import calculate_gc_content
3
4 # You can do
5 from [Link] import calculate_gc_content
6 # Or even
7 import [Link] as ana
8 gc = ana.calculate_gc_content(sequence)
Abdoulaye Samaké (USTTB/FST) Introduction to Programming 136 / 143
Practical Aspects of Python Programming Module Import Strategies & Best Practices

Relative vs Absolute Imports

Within Your Project


1 # Assuming this is src/analysis/sequence_analysis.py
2
3 # Relative import (within same package)
4 from . import statistical_tests
5 from .statistical_tests import t_test_expression
6 from ..utils.bio_tools import validate_sequence
7
8 # Absolute import (clear but longer)
9 from [Link].statistical_tests import t_test_expression
10 from [Link].bio_tools import validate_sequence

Best Practices
Use relative imports within your package
Use absolute imports for external packages
Never use implicit relative imports (Python 2 style)

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 137 / 143


Practical Aspects of Python Programming Module Import Strategies & Best Practices

VS Code Multi-root Workspaces


Managing Multiple Projects
1 // [Link]-workspace
2 {
3 "folders": [
4 {
5 "path": "genome_analysis",
6 "name": "Genome Analysis Project"
7 },
8 {
9 "path": "rnaseq_pipeline",
10 "name": "RNA-Seq Pipeline"
11 },
12 {
13 "path": "../shared_libraries",
14 "name": "Shared Bioinformatics Library"
15 }
16 ],
17 "settings": {
18 "[Link]": [
19 "${workspaceFolder:shared_libraries}/src"
20 ]
21 }
22 }

Usage
File → Open Workspace from File...
Share settings across related projects
Abdoulaye Samaké (USTTB/FST) Introduction to Programming 138 / 143
Practical Aspects of Python Programming Summary & Best Practices

Top 10 Python Import Best Practices

Essential Rules
Use virtual environments for every project
Import at module level (top of file) for clarity
Avoid wildcard imports (from module import *)
Use aliases for commonly used packages (import numpy as np)
Follow PEP 8 import order: stdlib → third-party → local
Keep imports minimal – only what you need
Use absolute imports for external packages
Handle ImportError gracefully with try/except
Document unusual imports with comments
Test imports work in your target environment

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 139 / 143


Practical Aspects of Python Programming Summary & Best Practices

VS Code Python Workflow Checklist

Project Setup Checklist


Create virtual environment (python -m venv venv)
Select interpreter in VS Code (Ctrl+Shift+P)
Configure .vscode/[Link]
Set up [Link] or [Link]
Configure Python path if needed
Install essential extensions
Set up launch configurations for debugging
Configure linting and formatting
Create useful snippets for common imports
Set up tasks for common operations

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 140 / 143


Practical Aspects of Python Programming Summary & Best Practices

Troubleshooting Quick Reference

Common Problems & Solutions


Problem Solution
ModuleNotFoundError Check Python interpreter, install package
Circular imports Restructure code, use local imports
Slow startup Use selective imports, lazy loading
Version conflicts Use virtual environments
Cross-platform issues Use platform detection
Memory issues Process files in chunks
Team inconsistencies Share .vscode/[Link]
Testing imports fail Check PYTHONPATH in test runner

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 141 / 143


Practical Aspects of Python Programming Summary & Best Practices

Resources & Further Learning

Essential Resources
Python Packaging User Guide: [Link]
PEP 8 - Style Guide: [Link]
VS Code Python Tutorial:
[Link]
Bioconda Documentation: [Link]
Python Import System: [Link]

Recommended Books
Fluent Python by Luciano Ramalho
Python for Bioinformatics by Sebastian Bassi
Effective Python by Brett Slatkin

Abdoulaye Samaké (USTTB/FST) Introduction to Programming 142 / 143


Practical Aspects of Python Programming Summary & Best Practices

Final Exercise: Environment Setup Challenge

Test Your Skills


Set up a complete bioinformatics project environment:
Create project directory with proper structure
Set up conda environment with Python 3.9
Install: biopython, numpy, pandas, matplotlib
Configure VS Code with proper settings
Create a module with proper imports
Write a simple FASTA parser using best practices
Set up debugging configuration
Create requirements file for reproducibility

Success Criteria
All imports work without errors
Code follows PEP 8 guidelines
Environment is reproducible
VS Code provides full IntelliSense
Abdoulaye Samaké (USTTB/FST) Introduction to Programming 143 / 143

You might also like