Skip to content
Skip to main content

About this free course

Download this course

Share this free course

Learn to code for data analysis
Learn to code for data analysis

Start this free course now. Just create an account and sign in. Enrol and complete the course for a free statement of participation or digital badge if available.

1.5 Expressions

I’ve told the computer the deaths in Angola, Brazil and Portugal. I can now ask it to add them together to obtain the total deaths.

In []:

deathsInAngola + deathsInBrazil + deathsInPortugal

Out[]:

11440

A fragment of code that has a value is called an expression. Calculating the value of an expression is called evaluating the expression. If the expression is on a line of its own, the Jupyter notebook displays its value, as above.

The value of an expression can of course be assigned to a variable.

In []:

totalDeaths = deathsInAngola + deathsInBrazil + deathsInPortugal

Note that no value is displayed because the whole line of code is not an expression, it’s a statement , a command to the computer. In this case the statement is an assignment. You will see another kind of statement later this week.

To see the value, you learned that you must write the variable’s name.

In []:

totalDeaths

Out[]:

11440

This is really just a special case of the general rule that writing an expression on its own shows its value. A variable (which stores a value) is just an example of an expression (which is anything that has a value).

I can now write an expression to compute the average number of deaths: it’s the total divided by the number of countries.

In []:

totalDeaths / 3

Out[]:

3813.3333333333335

Python has of course all four arithmetic operators : addition (+), division (/), subtraction (-) and multiplication (*). I’ll use the last two later in the week. Python follows the conventional operator precedence: multiplication and division before addition and subtraction, unless parentheses are used to change the order. For example, (3+4)/2 is 3.5 but 3+4/2 is 5.

An image of many colourful painted skulls with different drawings and textures.
Figure 4

Now practice writing expressions and complete Exercise 2 in the notebook.

Exercise 2 Expressions

Go back to the Exercise notebook 1 you used in Exercise 1. In Exercise 2 you’ll see an example of operator precedence and practise writing expressions.

If you’re using Anaconda, remember that to open the notebook you’ll need to navigate to it using Jupyter. Whether you’re using Anaconda or CoCalc, once the notebook is open, run all the code before doing the exercise.

Writing code for the first time can be difficult but stick with it.

In the next section, you will find out about functions.