Using Python as a calculator#

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

Important

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. For example, we can compute the sum of two numbers as:

2+2
4

Python allows spaces between the numbers and the addition operator, so it is usually more readable 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}.\]

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.0

Note

This example is intentionally trivial, so that the order of operations is extremely clear, but 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 library, which must be imported before use:

import math

After running the import statement above, we can calculate the sin of a number as:

math.sin(2)
0.9092974268256817

math.sin is an example of a function. 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. In the example above, math.sin is the name of the function and we put the number 2 in a set of brackets: this indicates that we want to calculate the sin of 2.

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 constant for this under the name math.pi.

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

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 a logarithm to base \(10\), you can use the math.log10 function.

Computing an exponential:

math.exp(2)

Exercise#

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 relation below.

\[\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 using the code below. This will ensure that you avoid unnecessary rounding errors.

import scipy
scipy.constants.R
8.31446261815324

Answers

\[K = 5.40 \times 10^{-5}\]
\[\Delta G = 24.3\,\mathrm{kJ\, mol^{-1}}\]