0% found this document useful (0 votes)
8 views13 pages

Python Programming Advanced

The document provides an advanced overview of Python programming tailored for chemists, focusing on data structures, functions, and object-oriented programming concepts. It covers built-in data structures like lists, tuples, sets, and dictionaries, as well as the importance of functions for code reusability and modularity. Additionally, it explains procedural versus object-oriented programming, emphasizing how OOP can effectively model chemical entities such as atoms and molecules.
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)
8 views13 pages

Python Programming Advanced

The document provides an advanced overview of Python programming tailored for chemists, focusing on data structures, functions, and object-oriented programming concepts. It covers built-in data structures like lists, tuples, sets, and dictionaries, as well as the importance of functions for code reusability and modularity. Additionally, it explains procedural versus object-oriented programming, emphasizing how OOP can effectively model chemical entities such as atoms and molecules.
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

Python Programming advanced 24/1/2026, 8:05 PM

Advanced Python for Chemists


Data Structures are a way of organizing data so that it can be accessed more
efficiently depending upon the situation.

1. Built-in data structures in Python


Python provides a powerful collection of built-in data structures that allow
scientists and programmers to efficiently store, organize, and manipulate data. In
computational chemistry and scientific research, data structures are essential for
handling molecular information, chemical properties, reaction datasets, and
simulation results.

1.1 Lists, Tuples, Sets, and Dictionaries


Python offers a rich set of built-in data structures that enable efficient data storage,
manipulation, and retrieval — crucial for scientific computing, chemical data
analysis, and simulation modeling.

1.1.1 Lists
Definition: A list is an ordered, mutable collection that can hold heterogeneous
data types.

Syntax:

elements = [item1, item2, item3]

Example (Chemistry context):


In [6]: elements = ["H", "He", "Li", "Be", "B"]
atomic_weights = [1.008, 4.003, 6.941, 9.012, 10.811]
print(elements)
print(atomic_weights)

['H', 'He', 'Li', 'Be', 'B']


[1.008, 4.003, 6.941, 9.012, 10.811]

about:srcdoc Page 1 of 13
Python Programming advanced 24/1/2026, 8:05 PM

Key Properties of lists:


Ordered → maintains insertion sequence

Mutable → supports item reassignment and modification

Useful Operations:
In [8]: [Link]("C") # Add element
del elements[1] # Remove by index
[Link]() # Sort alphabetically
print(elements)

['B', 'C', 'C', 'H', 'Li']

1.1.2 Tuples
Definition: A tuple is an ordered, immutable collection used for fixed data.

Syntax:

In [ ]: data = (item1, item2, item3)

Example (Molecular Data):

In [ ]: molecule = ("H2O", 18.015, "liquid") # (formula, molar mass, state)

Why Use Tuples?

Immutability ensures data integrity in computations

Faster than lists due to fixed structure

1.1.3 Sets
Definition: A set is an unordered, mutable, and unique collection of elements.

In [ ]: unique_elements = {item1, item2, item3}

Example (Chemical Elements):

In [10]: sample_A = {"H", "O", "C"}


sample_B = {"O", "N", "C"}

Useful Operations:

about:srcdoc Page 2 of 13
Python Programming advanced 24/1/2026, 8:05 PM

In [14]: sample1 = sample_A | sample_B # Union → {'H', 'O', 'N', 'C'}


sample2 = sample_A & sample_B # Intersection → {'O', 'C'}
sample3 = sample_A - sample_B # Difference → {'H'}

print(sample1)
print(sample2)
print(sample3)

{'C', 'N', 'O', 'H'}


{'O', 'C'}
{'H'}

1.1.4 Dictionaries
Definition: A dictionary is an unordered, mutable, key–value mapping structure.

Syntax:

In [ ]: data = {key1: value1, key2: value2}

In [2]: elements_data = {
"H": {"atomic_number": 1, "atomic_weight": 1.008},
"O": {"atomic_number": 8, "atomic_weight": 15.999},
"C": {"atomic_number": 6, "atomic_weight": 12.011}
}

print(elements_data)

print(elements_data["O"]["atomic_weight"])

{'H': {'atomic_number': 1, 'atomic_weight': 1.008}, 'O': {'atomic_number':


8, 'atomic_weight': 15.999}, 'C': {'atomic_number': 6, 'atomic_weight': 1
2.011}}
15.999

In [16]:

Summary Table
Structure Ordered Mutable Duplicates Typical Use Case

Storing sequential data (e.g., atomic


List Yes Yes Yes
masses)

Tuple Yes No Yes Fixed data (e.g., molecule info)

Unique collections (e.g., detected


Set No Yes No
elements)

Keys
Dictionary No Yes Key-value mapping (e.g., periodic data)
unique

about:srcdoc Page 3 of 13
Python Programming advanced 24/1/2026, 8:05 PM

2. Functions in Python
Functions are essential building blocks in Python programming. They allow us to
organize code, avoid repetition, and perform complex chemical or mathematical
computations in a modular and reusable way.

2.1. What is a Function?


A function is a block of organized, reusable code that performs a specific task.

Syntax:

def function_name(parameters):
"""Optional docstring describing the function"""
# Function body
return result

1. def: keyword used to declare a function


2. function_name : any name given to the function
3. Parameters or Arguments : Parameter is the value passed to the function. We
can pass any number of parameters.
4. Statement or function body : The function body contains one or more
statements that perform some actions. It can also use pass keyword.
5. return (optional) : returns value from a function

Example:
In [1]: def greet():
print("Welcome to Python for Chemists!")

greet()

Welcome to Python for Chemists!

2.2. Why Use Functions?


Functions help in:

about:srcdoc Page 4 of 13
Python Programming advanced 24/1/2026, 8:05 PM

Code reusability — avoid rewriting similar logic.

Modularity — structure large programs into smaller, manageable parts.

Readability — clear separation of logic.

Testing and debugging — easier to isolate errors.

2.3. Function Parameters and Arguments


Functions can accept input parameters (arguments) that make them more flexible.

Term Definition Example

A variable declared inside the def calc_energy(moles): →


Parameter
function definition. moles is a parameter

The actual value supplied to a calc_energy(2.5) → 2.5 is an


Argument
function when it is called. argument

Example (Molar Mass Calculation):

In [3]: # Function definition


def calc_mass(moles, molar_mass): # moles and molar_mass are parameters
mass = moles * molar_mass
return mass

# Function call # 2.5 and 18.02 are arguments — the actual values passed when
result = calc_mass(2.5, 18.02) # 2.5 moles of H2O (molar mass = 18.02 g/mol)
print("Mass:", result, "grams")

Mass: 45.05 grams

2.4. Return Statement


Functions can return one or more values.

Example (Bond Energy Calculation):

In [22]: def bond_energy(bond_length, bond_strength):


energy = bond_length * bond_strength
return energy

result = bond_energy(0.74, 435) # H–H bond (Å × kJ/mol)


print("Approx. bond energy =", result, "kJ/mol·Å")

Approx. bond energy = 321.9 kJ/mol·Å

about:srcdoc Page 5 of 13
Python Programming advanced 24/1/2026, 8:05 PM

2.5. Lambda (Anonymous) Functions


A lambda function is a small, one-line, anonymous function — often used for quick
calculations.

Syntax:

In [ ]: lambda arguments: expression

Example (Energy Conversion):

In [24]: # Convert kJ/mol to eV/molecule


kJ_to_eV = lambda energy: energy * 0.0103643
print(kJ_to_eV(100))

1.03643

2.6. Practical Chemistry Examples


Example 1: Calculate Average Atomic Mass

In [25]: def average_atomic_mass(isotopes):


"""Compute weighted average atomic mass."""
total = 0
for isotope, (mass, abundance) in [Link]():
total += mass * abundance
return total / 100

chlorine = {"Cl-35": (34.969, 75.78), "Cl-37": (36.966, 24.22)}


print("Average atomic mass of Cl =", average_atomic_mass(chlorine))

Average atomic mass of Cl = 35.4526734

Example 2: Reaction Yield

In [26]: def reaction_yield(theoretical, actual):


"""Calculate reaction yield percentage."""
return (actual / theoretical) * 100

print("Reaction Yield =", reaction_yield(10.0, 8.5), "%")

Reaction Yield = 85.0 %

2.7. Conclusion
Functions are the foundation of structured scientific programming in Python. They
enable chemists and researchers to model reactions, automate analysis, and
encapsulate formulas into reusable, efficient computational tools.

about:srcdoc Page 6 of 13
Python Programming advanced 24/1/2026, 8:05 PM

3. Procedural vs. Object-Oriented Programming


3.1 Procedural Programming
Procedural programming is a structured programming approach that organizes
code in a linear, step-by-step manner — much like following a laboratory protocol.

A program is broken down into functions or procedures, each responsible for a


specific task.
The program executes instructions sequentially, with the flow of control
determined by function calls and return values.

This approach is efficient for simple tasks but becomes difficult to maintain for
large, complex systems due to tightly coupled dependencies.

3.2 Object-Oriented Programming (OOP)


Object-Oriented Programming (OOP) organizes software around objects — entities
that combine both data (attributes) and behavior (methods).
This mirrors how we model systems in chemistry — atoms, molecules, and reactions
can all be represented as interacting objects.

OOP emphasizes four fundamental principles:

Principle Description Example (Chemistry Analogy)

An Atom object encapsulates


Bundling data and methods
Encapsulation properties like atomic number and
within a single unit (class).
methods like bond formation.

Deriving new classes from A HydrogenAtom inherits from the Atom


Inheritance
existing ones. class.

Methods with the same


bond() behaves differently for ionic
Polymorphism name behave differently for
vs. covalent compounds.
different classes.

Hiding complex details while Abstracting a Reaction as reactants


Abstraction exposing only essential → products without showing
features. mechanism steps.

3.3 Key Benefits of OOP


Modularity: Code is organized into independent, reusable classes.
Reusability: Classes can be reused and extended across different programs.

about:srcdoc Page 7 of 13
Python Programming advanced 24/1/2026, 8:05 PM

Maintainability: Code updates are localized and easier to manage.


Scalability: Large projects are more manageable through modular design.

4. Fundamental Concepts in Python OOP


4.1 Objects
In Python, everything is an object — integers, strings, functions, and even modules.
An object is an instance of a class, with attributes and methods defining its data and
functionality.

[ \text{Object} = \text{Instance of a Class} ]

For example, if a Molecule is a class, each specific molecule (H₂O, CO₂) is an object
of that class.

4.2 Classes
A class is a blueprint for creating objects.
It defines what data (attributes) and what actions (methods) its objects will have.

Syntax: Defining a Class


class ClassName:
# class attribute(s)
# method(s)
pass

In [2]: class Car:


def __init__(self, brand, color):
[Link] = brand # Attribute 1
[Link] = color # Attribute 2

def drive(self):
print(f"The {[Link]} {[Link]} is driving.")

Explanation:

__init__() is a constructor, automatically executed when the class is instantiated.

self refers to the current object instance.

Attributes like brand and color are instance variables.

4.3 Creating (Instantiating) Objects


about:srcdoc Page 8 of 13
Python Programming advanced 24/1/2026, 8:05 PM

Objects are created by instantiating a class.

In [3]: # Create two Car objects


car1 = Car("Toyota", "Red")
car2 = Car("Honda", "Blue")

# Call their methods


[Link]()
[Link]()

The Red Toyota is driving.


The Blue Honda is driving.

4.4 The __init__() Constructor


The constructor initializes an object’s attributes when it is created.

Constructor: _ _ 𝑖 𝑛 𝑖 𝑡 _ _ ( 𝑠 𝑒 𝑙 𝑓 , parameters ) Constructor: init(self,parameters)

It’s similar to initializing experimental conditions before running a chemical reaction.

In [4]: # Example: Using constructor in a Molecule class


class Molecule:
def __init__(self, formula, molecular_mass):
[Link] = formula
self.molecular_mass = molecular_mass

# Instantiate an object
water = Molecule("H2O", 18.015)
print(f"Molecule: {[Link]}, Molecular Mass: {water.molecular_mass} g/mol

Molecule: H2O, Molecular Mass: 18.015 g/mol

5. OOP Applied to Chemistry


Object-Oriented Programming is well-suited for modeling chemical entities such as
atoms, molecules, and reactions.

5.1 Example: Modeling Atoms and Molecules


In [5]: # Define Atom and Molecule classes
class Atom:
def __init__(self, symbol, atomic_number, atomic_mass):
[Link] = symbol
self.atomic_number = atomic_number
self.atomic_mass = atomic_mass

class Molecule:
def __init__(self, name, atoms):
[Link] = name

about:srcdoc Page 9 of 13
Python Programming advanced 24/1/2026, 8:05 PM

[Link] = atoms # List of Atom objects

def molecular_mass(self):
return sum(atom.atomic_mass for atom in [Link])

In [6]: # Instantiate objects


H = Atom("H", 1, 1.008)
O = Atom("O", 8, 15.999)

# Create a water molecule


water = Molecule("Water", [H, H, O])

# Display molecular mass


print(f"{[Link]} has molecular mass = {water.molecular_mass():.3f} g/mol")

Water has molecular mass = 18.015 g/mol

This demonstrates composition, where a Molecule object is made up of several


Atom objects — analogous to the real-world structure of molecules.

6. Summary of Core Concepts


Concept Description Example

A blueprint or template defining


Class the structure and behavior of class Molecule:
objects.

An instance of a class containing water = Molecule("H2O",


Object
specific data. atoms)

Constructor A special method used to initialize


__init__(self, ...)
( __init__ ) object attributes during creation.

Bundling data (attributes) and


Encapsulation methods (functions) together into [Link]
one unit.

The process of creating an object


Instantiation obj = ClassName()
from a class.

Deriving new classes from existing


class
Inheritance ones to reuse code and add new
OrganicMolecule(Molecule):
features.

Allowing methods with the same


bond() behaves differently for
Polymorphism name to behave differently for
ionic vs. covalent molecules.
different objects.

Hiding complex details while


Representing a Reaction as
Abstraction exposing only essential
Reactants → Products .
functionalities.

about:srcdoc Page 10 of 13
Python Programming advanced 24/1/2026, 8:05 PM

7. Practice Exercises
Exercise 1: Create a Reaction Class
Objective:
Model a simple chemical reaction between two molecules.

Instructions:

1. Create a class Reaction that takes two Molecule objects as reactant1


and reactant2 , and one as product .
2. Define a method display_equation() that prints the reaction in a readable
chemical format.

Example Code:

In [7]: class Reaction:


def __init__(self, reactant1, reactant2, product):
self.reactant1 = reactant1
self.reactant2 = reactant2
[Link] = product

def display_equation(self):
print(f"{[Link]} + {[Link]} → {[Link].n

In [8]: # Example usage


water = Molecule("H2O", [])
hydrogen = Molecule("H2", [])
oxygen = Molecule("O2", [])

reaction = Reaction(hydrogen, oxygen, water)


reaction.display_equation()

H2 + O2 → H2O

Exercise 2: Extend the Molecule Class


Objective: Enhance the Molecule class to count atoms by element.

Instructions:

Add a method count_atoms() that returns a dictionary showing how many atoms of
each element are present.

Use this to analyze molecular composition.

Example Code:

about:srcdoc Page 11 of 13
Python Programming advanced 24/1/2026, 8:05 PM

In [9]: class Molecule:


def __init__(self, name, atoms):
[Link] = name
[Link] = atoms

def molecular_mass(self):
return sum(atom.atomic_mass for atom in [Link])

def count_atoms(self):
atom_counts = {}
for atom in [Link]:
atom_counts[[Link]] = atom_counts.get([Link], 0) + 1
return atom_counts

# Example usage
H = Atom("H", 1, 1.008)
O = Atom("O", 8, 15.999)
water = Molecule("H2O", [H, H, O])
print(water.count_atoms())

{'H': 2, 'O': 1}

Exercise 3: Implement Inheritance


Objective: Demonstrate inheritance by creating a subclass of Molecule.

Instructions:

Create a class OrganicMolecule that inherits from Molecule.

Add an attribute carbon_count.

Define a method is_hydrocarbon() that checks if the molecule contains only carbon
and hydrogen atoms.

Example Code:

In [10]: class OrganicMolecule(Molecule):


def __init__(self, name, atoms):
super().__init__(name, atoms)
self.carbon_count = sum(1 for atom in [Link] if [Link] == "C")

def is_hydrocarbon(self):
elements = {[Link] for atom in [Link]}
return [Link]({"C", "H"})

# Example usage
C = Atom("C", 6, 12.011)
H = Atom("H", 1, 1.008)
methane = OrganicMolecule("CH4", [C, H, H, H, H])
print(methane.carbon_count)
print(methane.is_hydrocarbon())

about:srcdoc Page 12 of 13
Python Programming advanced 24/1/2026, 8:05 PM

1
True

Exercise 4 (Optional): Polymorphism Example


Objective: Demonstrate polymorphism using different types of molecules.

Instructions:

Create a base class Molecule with a method describe().

Override describe() in subclasses like OrganicMolecule and InorganicMolecule.

Call the same method name on objects of different classes to show different
behavior.

Example Code:

In [1]: class Molecule:


def describe(self):
print("This is a generic molecule.")

class OrganicMolecule(Molecule):
def describe(self):
print("This is an organic molecule containing carbon.")

class InorganicMolecule(Molecule):
def describe(self):
print("This is an inorganic molecule, usually without carbon.")

# Example usage
molecules = [Molecule(), OrganicMolecule(), InorganicMolecule()]
for mol in molecules:
[Link]()

This is a generic molecule.


This is an organic molecule containing carbon.
This is an inorganic molecule, usually without carbon.

In [ ]:

about:srcdoc Page 13 of 13

You might also like