1 + 12
In this first workshop we will cover
Python is a programming language that can be used to build programs (i.e. a “general programming language”), but it can also be used to analyse data by importing a number of useful modules.
We are using Positron to interact with Python more comfortably. If you have used RStudio to interact with R before, you should feel right at home: Positron is a program designed for data science with Python (and developed by the RStudio devs!).
Python can be used interactively in a console, or we can build scripts and programs with it, making the most out of Positron’s code editor.
We will start by using the console to work interactively. This is our direct line to the computer, and is the simplest way to run code. Don’t worry about any unfamiliar language, fonts or colours - we can ignore most of it for now.
To start with, we can use Python like a calculator. Type the following commands in the console, and press Enter to execute them:
After running each command, you should see the result as an output.
Like language, Python has nouns and verbs. We call the nouns variables: they are the ‘things’ we manipulate with our code.
Essentially, a variable is a named container. We access it by its name, and we get its value.
To create a variable, you need to choose a name and a value with name = value. For example
Whenever you use the variable’s name, Python will now access its value:
We can use the variables in place of the values
Positron helps us with extra panels and features apart from the Console. To see what variables you have created, look at the “Variable explorer” tab in the top right.
Variables have different types. So far, we’ve just looked at storing numbers, of which there are three types:
int - integers store whole numbers, e.g. 1, 5, 1000, -3.float - floating point numbers store decimals and scientific notation, e.g. 1.5, -8.97, 4e-6.complex - complex numbers express the imaginary unit with j, e.g. z = 1+2j is \(z = 1+2i\).Let’s look at some other types
Even simpler than integers is the boolean type. These are either 1 or 0 (True or False), representing a single binary unit (bit). Don’t be fooled by the words, these work like numbers: True + True gives 2.
In Python, the boolean values
TrueandFalsemust begin with a capital letter.
Let’s look at variable types which aren’t (necessarily) numbers. Sequences are variables which store multiple pieces of data. For example, strings store a sequence of characters and are created with quotation marks 'blah blah blah' or "blah blah blah":
We can also create lists, which will store several variables (not necessarily of the same type). We need to use square brackets for that:
Lists are very flexible as they can contain any number of items, and any type of data. You can even nest lists inside a list, which makes for a very flexible data type.
Operations on sequences are a bit different to numbers. We can still use + and *, but they will concatenate (append) and duplicate, rather than perform arithmetic.
[38, 3, 54, 17, 7, 38, 3, 54, 17, 7, 38, 3, 54, 17, 7]
However, depending on the variable, some operations won’t work:
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[12], line 1 ----> 1 example_string + example_int TypeError: can only concatenate str (not "int") to str
There are other data types like tuples, dictionaries and sets, but we won’t look at those in this session. Here’s a summary of the ones we’ve covered:
| Category | Type | Short name | Example | Generator |
|---|---|---|---|---|
| Numeric | Integer | int |
3 |
int() |
| Numeric | Floating Point Number | float |
4.2 |
float() |
| Numeric | Boolean | bool |
True |
bool() |
| Sequence | String | str |
'A sentence ' |
" " or ' ' or str() |
| Sequence | List | list |
['apple', 'banana', 'cherry'] |
[ ] or list() |
The generator commands are new. We use these to manually change the variable type. For example,
yields 1, converting a boolean into an integer. These commands are functions, as opposed to variables - we’ll look at functions a bit later.
We can access part of a sequence by indexing. Sequences are ordered, starting at 0, so the first element has index 0, the second index 1, the third 2 and so on. For example, see what these commands return:
If you want more than one element in a sequence, you can slice. Simple slices specify a range to slice, from the first index to the last, but not including the last. For example:
That command returns elements from position 0 up to - but not including! - position 4.
So far, we’ve been working in the console, our direct line to the computer. However, it is often more convenient to use a script. These are simple text files which store code and run when we choose. They are useful to
Let’s set things up
You should now have a blank Python script which you can edit.
Try typing a line of code in your new script, such as
Press ctrl+enter to run each line, making sure they’re selected, or ctrl+shift+enter for the whole script. You should see the result appear in the console.
If you find that nothing is happening, make sure you’re using ctrl+enter and selecting a line. Unlike in the console, pressing enter by itself just makes a new line,
We’ll work out of a script for the rest of the session. Don’t forget to save your script by pressing ctrl+S or the save button.
Functions are little programs that do specific jobs. These are the verbs of Python, because they do things to and with our variables. Here are a few examples of built-in functions:
6
Functions always have parentheses () after their name, and they can take one or several arguments, or none at all, depending on what they can do, and how the user wants to use them.
Here, we use two arguments to modify the default behaviour of the round() function:
Notice how Positron gives you hints about the available arguments after typing the function name?
Operators are a special type of function in Python with which you’re already familiar. The most important is =, which assigns values to variables. Here is a summary of some important operators, although there are many others:
| Operator | Function | Description | Example command |
|---|---|---|---|
= |
Assignment | Assigns values to variables | a = 7 |
# |
Comment | Excludes any following text from being run | # This text will be ignored by Python |
| Operator | Function | Description | Example command | Example output |
|---|---|---|---|---|
+ |
Addition | Adds or concatenates values, depending on variable types | 7 + 3 or "a" + "b" |
10 or 'ab' |
- |
Subtraction | Subtracts numerical values | 8 - 3 |
5 |
* |
Multiplication | Multiplies values, depending on variable types | 7 * 2 or "a" * 3 |
14 or 'aaa' |
** |
Exponentiation | Raises a numerical value to a power | 7 ** 2 |
49 |
/ |
Division | Divides numerical values | 3 / 4 |
0.75 |
// |
Floor division | Divides numerical values and then rounds down | 3 // 4 |
0 |
% |
Remainder | Takes the remainder of numerical values | 13 % 7 |
6 |
| Operator | Function | Description | Example command | Example output |
|---|---|---|---|---|
== |
Equal to | Checks whether two variables are the same and outputs a boolean | 1 == 1 |
True |
!= |
Not equal to | Checks whether two variables are different | '1' != 1 |
True |
> |
Greater than | Checks whether one variable is greater than the other | 1 > 1 |
False |
>= |
Greater than or equal to | Checks whether greater than (>) or equal to (==) are true | 1 >= 1 |
True |
< |
Less than | Checks whether one variable is less than the other | 0 < 1 |
True |
<= |
Less than or equal to | Checks whether less than (<) or equal to (==) are true | 0 <= 1 |
True |
To find help about a function, you can use the help() function, or a ? after a function name:
Help on built-in function max in module builtins:
max(...)
max(iterable, *[, default=obj, key=func]) -> value
max(arg1, arg2, *args, *[, key=func]) -> value
With a single iterable argument, return its biggest item. The
default keyword-only argument specifies an object to return if
the provided iterable is empty.
With two or more arguments, return the largest argument.
For a comprehensive manual, go to the official online documentation. For questions and answers, typing the right question in a search engine will usually lead you to something helpful. If you can’t find an answer, StackOverflow is a great Q&A community.
Python, on its own, requires a lot of manual programming for advanced tasks. What makes it versatile is the capacity to use other people’s code with modules.
To bring in advanced variables and functions that other’s have made, we need to import the module. For example
--------------------------------------------------------------------------- NameError Traceback (most recent call last) Cell In[20], line 1 ----> 1 pi NameError: name 'pi' is not defined
returns an error, because it’s undefined. But the math module contains a variable called pi:
To access objects from within a module, we use a full stop:
module.object_inside.
Arrays are a data type introduced by numpy, a module with many functions useful for numerical computing.
For example, you can convert the list we created before to then do mathematical operations on each one of its elements:
pandas introduces dataframes, which are often used to store two-dimensional datasets with different kinds of variables in each column. If your data is stored as a spreadsheet, you probably want to import it with a pandas function.
First, we’ll need to install and import the pandas module. Install it as before (either with pip or conda), and then run
Now, let’s import some data to get ready for the next session.
datadata folderpd.read_csv() to load the data:You’ll see that it’s now in your variable explorer. You can double-click on a dataframe in the Variable explorer to explore it in a separate window.
We’ll look at manipulating these dataframe objects in the next session. For now, try running the df.head() function to examine the first few rows:
| name | birth_date | height_cm | positions | nationality | age | club | |
|---|---|---|---|---|---|---|---|
| 0 | James Milner | 1986-01-04 | 175.0 | Midfield | England | 38 | Brighton and Hove Albion Football Club |
| 1 | Anastasios Tsokanis | 1991-05-02 | 176.0 | Midfield | Greece | 33 | Volou Neos Podosferikos Syllogos |
| 2 | Jonas Hofmann | 1992-07-14 | 176.0 | Midfield | Germany | 32 | Bayer 04 Leverkusen Fußball |
| 3 | Pepe Reina | 1982-08-31 | 188.0 | Goalkeeper | Spain | 42 | Calcio Como |
| 4 | Lionel Carole | 1991-04-12 | 180.0 | Defender | France | 33 | Kayserispor Kulübü |
matplotlib is a large collection of data visualisation functions, and pyplot is a submodule of matplotlib that contains essentials.
This shows a plot in the Plots pane of Positron.
The default look is a line plot that joins all the points, but we can style a plot with only a few characters:

Extra arguments can be used to style further:

To find out about the styling shorthand and all other arguments, look at the documentation:
The math module is built-in - the module came with the Python installation. Other, external modules need to be installed before they can be used.
For non-Anaconda users, you can run the following code in the console:
%pip install ...
to install modules (replace ... with the module name(s), separated by spaces). You only need to do this once, so you should use the console to do so.
The % symbol is a ‘magic’ code - it doesn’t mean anything in Python (and non-Positron users will find this breaks), but Positron has interpreted it to mean send the rest of the line to a terminal.
Anaconda users should replace pip with conda.
You should run the following to get the modules you need for this intensive:
%pip install pandas seaborn matplotlib plotly scipy statsmodels
One module that isn’t built-in is plotly, which we can use for interactive visualisations.
Press “Save” or Ctrl + S to save your script. Note that, while your variables are not saved, you can execute the whole script in one go to get everything back.
This morning we looked at a lot of Python features, so don’t worry if they haven’t all sunk in. Programming is best learned through practice, so keep at it! Here’s a rundown of the concepts we covered
| Concept | Desctiption |
|---|---|
| The console vs scripts | The console is our window into the computer, this is where we send code directly to the computer. Scripts are files which we can write, edit, store and run code, that’s where you’ll write most of your Python. |
| Variables | Variables are the nouns of programming, this is where we store information, the objects and things of our coding. They come in different types like integers, strings and lists. |
| Indexing | In order to access elements of a sequence variable, like a list, we need to index, e.g. example_numbers[2]. Python counts from 0. |
| Functions | Functions are the verbs of programming, they perform actions on our variables. Call the function by name and put inputs inside parentheses, e.g. round(2.5) |
| Help | Running help( ... ) will reveal the help documentation about a function or type. |
| Packages | We can bring external code into our environment with import .... This is how we use packages, an essential for Python. Don’t forget to install the package first! |