Python Tutorial for Chemists

In this tutorial, we will learn the basics of Python, which is an incredibly versatile and powerful programming language. Python is widely used in all fields of science, including Chemistry, due to its simplicity and flexibility. Specifically, we will focus on the concept of variables and types, then comparison and conditional operators.

Note: Other resources

Lecture 02 and 03 do not cover all Python functionality, but give you a concise overview with examples. There are a lot of resources online, if you want to learn more. - RealPython - SIB Swiss - first steps - Kaggle Learn - Python

Variables and Types

A large part of programming involves manipulating variables - containers that hold data. A variable can be of different types - integer, float, string, among others. Python automatically assigns a variable the type that is appropriate for its value.

Integer

An Integer variable holds integer values. In Python, you don’t have to specify the type of a variable when you create it. When you assign an integer value to a variable, Python knows that the variable is an integer.

Let’s see an example:

atom_count = 6
print(atom_count)
print(type(atom_count))
6
<class 'int'>

In chemistry, there are many times when we use integers. For example, number of atoms, electrons etc.

Float

Float stands for ‘floating point number’. You can use it for rational numbers, usually ending with a decimal figure, such as 1.11 or 3.14.

atomic_weight_carbon = 12.01
print(atomic_weight_carbon)
print(type(atomic_weight_carbon))
12.01
<class 'float'>

In chemistry, atomic weights, concentration values etc are commonly represented as floating point numbers.

String

In Python, String variables are used to store textual data, a sequence of characters.

element_name = "Carbon"
print(element_name)
print(type(element_name))
Carbon
<class 'str'>

In chemistry, we often deal with strings when handling names of compounds, elements etc.

Examples

Now that we have learned about Variables and Types in Python, let’s test your understanding with the following exercises:

  1. Create an integer variable named molecule_count and assign it a value of 20. Print its value and type.
molecule_count = 20
print(molecule_count)
print(type(molecule_count))
20
<class 'int'>
  1. Create a float variable named molar_mass_oxygen and assign it a value of 16.00. Print its value and type.
molar_mass_oxygen = 16.00
print(molar_mass_oxygen)
print(type(molar_mass_oxygen))
16.0
<class 'float'>
  1. Create a string variable named chemical_formula_water and assign it a value of “H2O”. Print its value and type.
chemical_formula_water = "H2O"
print(chemical_formula_water)
print(type(chemical_formula_water))
H2O
<class 'str'>
  1. Change the value of molecule_count to 50. Print the new value.
molecule_count = 50
print(molecule_count)
50

Operators in Python

Operators are used to perform operations on variables and values. Python divides the operators in the following groups:

  • Arithmetic operators
  • Assignment operators
  • Comparison operators

Arithmetic Operators

Arithmetic operators are used to perform mathematical operations like addition, subtraction, multiplication and division.

number_of_atoms = 12
# Addition
print(number_of_atoms + 5) #Output: 17
 
# Subtraction
print(number_of_atoms - 5) #Output: 7

# Multiplication
print(number_of_atoms * 5) #Output: 60

# Division
print(number_of_atoms / 3) #Output: 4.0
17
7
60
4.0

Assignment Operators

Assignment operators are used in Python to assign values to variables. There are various types of assignment operators in Python.

x = 5  # x is now 5
print(x)

x += 3 # same as x = x + 3; x is now 8
print(x)

x -= 1 # same as x = x - 1; x is now 7
print(x)

x *= 2 # same as x = x * 2; x is now 14
print(x)

x /= 7 # same as x = x / 7; x is now 2.0
print(x)
5
8
7
14
2.0

Comparison Operators

Comparison operators are used in Python to compare values. It either returns True or False according to the condition.

#Suppose we have two variables
a = 5
b = 10

print(a == b) #Output: False

print(a != b) #Output: True

print(a < b)  #Output: True

print(a > b)  #Output: False

print(a <= b) #Output: True

print(a >= b) #Output: False
False
True
True
False
True
False

In chemistry, comparison operators could be useful in checking equivalences, for example, if two volumes or two masses are equal, or if one is greater or smaller than the other.

Examples

  1. Calculate the atomic weight of CO2 (C=12.01, O=16.00).
weight_C = 12.01
weight_O = 16.00

weight_CO2 = weight_C + (weight_O * 2)
print(weight_CO2)
44.01
  1. Create a variable containing a number of moles of oxygen and calculate the weight.
# Lets assume we have 6 moles of oxygen
moles_of_oxygen = 6
total_weight = moles_of_oxygen * weight_O

print(total_weight) 
96.0
  1. Check if the weight of 4 moles of hydrogen is less than the weight of a mole of helium (H=1.01, He=4.00).
H = 1.01  # Atomic weight of Hydrogen
He = 4.00  # Atomic weight of Helium

print(4*H < He)  #Output: False
False

Handling Floating Point Numbers in Python

Indeed, performing operations on floating point numbers may sometimes yield unexpected results. This unusual behavior is due to the internal representation of these numbers as binary fractions, which can cause rounding errors.

Here’s an example to illustrate this issue:

x = 0.1 + 0.1 + 0.1
y = 0.3
print(x == y)  
False

You might expect the output to be True since 0.1 + 0.1 + 0.1 is 0.3. But it’s not!

This is because floating-point numbers are represented in computer hardware as base 2 (binary) fractions and most decimal fractions cannot be exactly represented as binary fractions results in small roundoff errors.

But don’t worry, Python provides a solution to this problem.

Enter the round() function!

The round() function rounds a floating point number to the nearest integer if no number of digits is specified, otherwise it rounds to the specified number of digits.

x = round(0.1 + 0.1 + 0.1, 2)
y = round(0.3, 2)
print(x == y) 
True

Use the round() function when you need precise calculation with floating point numbers.

Another solution is to use the math.isclose() function, which checks whether two values are close enough (within some tolerance) to consider them equal:

import math

x = 0.1 + 0.1 + 0.1
y = 0.3

print(math.isclose(x, y))  #Output: True
True

In this code snippet, we use the isclose() function to check if x and y are approximately equal, considering some small error. This function is quite handy when working with floating point arithmetic!

Another important note: If precision really matters in your calculations and rounding or checking closeness still doesn’t seem acceptable, you may want to look into using the decimal module in Python, which was designed specifically to handle more precise floating-point arithmetic.

More examples

Try to calculate the molar mass of benzene with a precision up to 3 decimal places, given that:

  • Carbon (C): 12.0096
  • Hydrogen (H): 1.0079

Benzene’s formula is C6H6.

C = 12.0096
H = 1.0079

benzene_molar_mass = round((C * 6) + (H * 6), 3)
print(benzene_molar_mass)  #Output: 78.114
78.105

In this code snippet, the round() function helps prevent any unwanted inaccuracies.

Conditionals in Python

Conditionals are used to perform different computations or actions depending on whether a condition evaluates to true or false.

If Statements

In Python, if statement is used for conditional execution.

temperature = 25

if temperature > 20:
    print("It's warm outside") 
It's warm outside

In this example, the message It's warm outside is printed to the screen if the temperature is higher than 20.

Elif and Else Statements

Python supports multiple conditions in one if statement using elif (abbreviation of else if). The else clause serves as a default condition; its block is executed when none of the conditions is true.

pH = 3

if pH < 7:
    print("Solution is acidic") 
elif pH > 7:
    print("Solution is alkaline")
else:
    print("Solution is neutral")
Solution is acidic

In this example, information about the nature of a solution given its pH is printed to the screen.

Using Logical Operators

Logical operators (and, or, not) allow to build more complex conditional statements.

temperature = 25
pressure = 2

if temperature > 20 and pressure > 1:
    print("Reaction rate will be high!") 

if not temperature < 20:
    print("It's not cold outside") 
Reaction rate will be high!
It's not cold outside

In these examples, a message about reaction rate is printed to the screen if both temperature is higher than 20 and pressure is higher than 1. The second condition checks if the temperature is not lower than 20.

Ternary Operator (Conditional Expressions)

Python supports one more conditional expression which is called ternary operator:

message = "It's warm outside" if temperature > 20 else "It's cold outside"
print(message)
It's warm outside

Here, the message about the weather is chosen based on the temperature.

Example

  1. Write a program that prints out whether a solution with a given pH is acidic, alkaline or neutral.
pH = 8

if pH < 7:
    print("Solution is acidic") 
elif pH > 7:
    print("Solution is alkaline")
else:
    print("Solution is neutral")
Solution is alkaline
  1. Write a program that prints out whether a substance is solid, liquid or gas given its boiling point and the current temperature.
boiling_point = 100
temperature = 50

if temperature < boiling_point:
    print("Substance is solid or liquid!")
else:
    print("Substance is gas!")
Substance is solid or liquid!
  1. Write a program that uses logical operators to print out whether the reaction rate will be high given temperature and pressure.
pH = 8

if pH < 7:
    print("Solution is acidic") 
elif pH > 7:
    print("Solution is alkaline")
else:
    print("Solution is neutral")
Solution is alkaline
  1. Use a ternary operator to print out whether a reaction is exothermic or endothermic given its ∆H.
delta_H = -10

message = "Reaction is exothermic" if delta_H < 0 else "Reaction is endothermic"
print(message)
Reaction is exothermic

Type Conversion in Python

Sometimes, it’s necessary to perform conversions between the built-in types. To convert between types, you simply use the type name as a function.

There are several built-in functions that allow you to convert data types. These functions include int(), float(), str(), etc.

In applications like Chemistry, type conversion becomes handy while doing mathematical calculations or concatenating strings and numbers.

Converting to Integer

To convert a value to an integer, you use the int() function. For example:

x = "123"
y = int(x)
print(y) #Output: 123
print(type(y)) #Output: <class 'int'>
123
<class 'int'>

Converting to Float

To convert a value to a float, you use the float() function. For example:

x = "123.45"
y = float(x)
print(y) #Output: 123.45
print(type(y)) #Output: <class 'float'>
123.45
<class 'float'>

Converting to String

To convert a value to a string, you use the str() function:

x = 123
y = str(x)
print(y) #Output: '123'
print(type(y)) #Output: <class 'str'>
123
<class 'str'>

This conversion is especially helpful when you want to concatenate some text with a number:

x = "The atomic number of Carbon is: " + str(6)
print(x) #Output: The atomic number of Carbon is: 6
The atomic number of Carbon is: 6

As seen from these examples, type conversion is an valuable utility in Python as working between different data types is quite common. Keep in mind that each of the type conversion functions (float, str, etc.) returns a new object and does not modify the original object.

Increment Operator

An increment operator is an operator that increases the value of a variable by 1. This is often used in loops and other control structures. Python does not technically have built-in increment operators like some languages such as C++, but it provides equivalent mechanisms.

The typical way of incrementing a variable in Python is x = x + 1.

But Python provides a shorthand to do the same, x += 1.

Here are some examples:

x = 5

# incrementing the value
x = x + 1
print(x) # Output: 6

# Alternate way to increment the value
x += 1
print(x) # Output: 7
6
7

Other Arithmetic Assignment Operators

In addition to +=, there are other arithmetic assignment operators:

  • -=: Decreases the current value of the variable by the specified amount.
  • *=: Multiplies the current value of the variable by the specified amount.
  • /=: Divides the current value of the variable by the specified amount.
  • **=: Raises the current value of the variable to the power of the specified amount.
  • //=: Performs floor division on the current value of the variable.
  • %=: Modulo assignment, provides the remainder of the division.

Here are examples of using these operators:

x = 10
x -= 2  # equivalent to x = x - 2
print(x) # Output: 8

x = 5
x *= 3  # equivalent to x = x * 3
print(x) # Output: 15

x = 20
x /= 4  # equivalent to x = x / 4
print(x) # Output: 5.0

x = 3
x **= 2  # equivalent to x = x ** 2
print(x) # Output: 9

x = 10
x //= 3  # equivalent to x = x // 3
print(x) # Output: 3

x = 17
x %= 5  # equivalent to x = x % 5
print(x) # Output: 2
8
15
5.0
9
3
2

Experiment with these different assignment operators to become familiar with them, they can simplify your code and make it easier to read.