Using Python as a calculator

Our eventual goal is to cover all of the programming basics, with a particular focus on data analysis in chemistry. We’re going to start by coding up some basic mathematics, essentially learning how to use Python as a calculator.

Warning

Before you read on: as you work through this course book, you may be sorely tempted to copy and paste the relevant examples rather than typing out everything from scratch. We strongly discourage you from doing this.

As we will discuss later in more detail, you’d be amazed how little time you spend as a programmer writing code. Often, you will be spending much more time fixing code that you have already written. This is why we recommend that, for the most part, you avoid copy and pasting code snippets during this course.

Instead of copy and pasting, we recommend that you type out the examples from scratch and regularly modify/mess with them to really test your understanding at each stage.

Basic mathematical operations

Simple arithmetic operations such as addition and subtraction are written in Python much like we would write them on pen and paper. As you’ve seen, we can add two numbers using the + operator.

2+2
4

Python allows spaces between the numbers and the addition operator, so it’s more readable, and preferred, to type this as:

2 + 2

Subtraction, multiplication and division are all written in a similar manner, with a different symbol used to denote the operator in each case.

Subtraction

4 - 2

Multiplication

5 * 5

Division

36 / 6

We can also raise one number to the power of another by sticking two multiplication operators together. For example, to calculate \(3^{2}\)

3 ** 2

Whilst all of the examples above use integers, Python is also perfectly capable of performing these operations on floats (numbers with a decimal point)

3.52 * 6.28

Similarly, Python also allows us to use standard form. For example, to evaluate \(6.8 \times 10^{3} + 2.7 \times 10^{-2}\):

6.8e3 + 2.7e-2

In addition to the basic mathematical operations outlined above, Python also supports integer division: division followed by rounding down to the nearest integer. In other words, we can calculate how many times one number goes into another, ignoring the remainder

13 // 4
3

Sometimes we want to explicitly calculate the remainder, this can be accomplished with the “modulo” operator. Using the same example as above

13 % 4
1

Order of operations

So far, we have only considered expressions containing one mathematical operation. More often than not, we are interested in mathematical expressions containing several operations - the order in which these operations are carried out is therefore very important. Thankfully, Python’s order of operations is exactly the same as is considered standard mathematical procedure: B(rackets), I(ndices), D(ivision), M(ultiplication), A(ddition), S(ubtraction) or BIDMAS.

For an illustrative example, consider the expression

\[\frac{3 + 7}{5} = 2\]

Written as is in Python, we get

3 + 7 / 5
4.4

Python does the division before the addition as per BIDMAS order. To get the intended result, we insert brackets

(3 + 7) / 5
2
Note

This example is intentionally trivial so that the order of operations is extremely clear. The same principle applies to much more difficult calculations that cannot be easily verified in our heads.

More complex mathematical operations

In addition to the basic mathematical objects we have introduced thus far, Python also allows us to evalute other common mathematical operations such as trigonometric functions. This functionality is contained in the math module, which must be imported before use

import math

After running the import statement above, we can are able to use any of the functions from math. As an example, calculate \(\sin(2)\) using

math.sin(2)
0.9092974268256817

math.sin is an example of a function.

NoteSyntax

To use a function in Python - otherwise referred to as “calling” the function - we type the name of the function followed by a set of brackets in which we supply the relevant inputs, for example

name_of_function(input_variable1, input_variable2...)

In the example above, math.sin is the name of the function and we provide the input 2 in a set of brackets. We’ll learn more about functions in Session 3.

Warning

The trigonometric functions in the math library (and other Python libraries) expect the inputs to be in radians, not degrees.

The other trigonometric functions in the math library are similarly intuitively named: math.cos, math.tan etc. These can all be accessed in the same way as the math.sin function; this process can be generically written as

name_of_function(input_to_function)

So to take the cosine of a number, we would type:

math.cos(15)
-0.7596879128588213

Given that we’re dealing with radians, it would be nice if we had access to the value of \(\pi\). Thankfully, the math library provides us with a value for this under the name math.pi.

math.pi
3.141592653589793

math.pi is an example of a variable - we’ll see more of these later.

To calculate \(\sin(\pi/2)\) we can use

math.sin(math.pi / 2)
1.0
Warning

You should always use math.pi as a variable as above, and never copy the number back into the code - this can lead to errors, loss of precision, and makes the code hard to read!

The math library also provides us with various other mathematical functions:

Taking the square root

math.sqrt(4)

Taking the logarithm

math.log(12)
Warning

The math.log function (and the equivalent functions in other Python libraries) takes the natural log of a number: \(\ln(x)\). To calculate the common logarithm \(\log_{10}(x)\), you can use the math.log10 function.

We can also compute an exponential, \(\exp(x)\) or \(e^x\) using math.exp, e.g.

math.exp(2)

Exercise

You should now apply your new knowledge to the following problem.

The Haber-Bosch process is the main reaction used in industry to produce ammonia.

\[\ce{N2} + 3\ce{H2} \rightarrow 2\ce{NH3}\]

At \(298\,\mathrm{K}\) under atmospheric pressure, the equilibrium partial pressures of nitrogen, hydrogen and ammonia are \(1.00\,\mathrm{bar}\), \(3.00\,\mathrm{bar}\) and \(3.82 \times 10^{-2}\,\mathrm{bar}\) respectively.

  • Calculate the equilibrium constant for this reaction using Python.
  • Using your calculated equilibrium constant, compute the change in the Gibbs free energy for the Haber-Bosch process at \(298\,\mathrm{K}\) with Python.

You will need the following Equation.

\[\Delta G= -RT\ln K\]

Tip

You may wish to approximate the gas constant as \(8.314\,\mathrm{J \, mol^{-1} \, K^{-1}}\), but a better alternative is to access a more accurate value directly the scipy constants module as below. This will ensure that you avoid unnecessary rounding errors.

import scipy
scipy.constants.R

See here for the full list of constants and their units

\[K = 5.40 \times 10^{-5}\]

\[\Delta G = 24.3\,\mathrm{kJ\, mol^{-1}}\]