Python basics of programming

Getting help

Python comes with built in documentation that can be accessed using the help() function:

help(name_function)

It will show the documentation of the function that you specified as an argument.

The Python documentation is also available online.

In the quiz on Python basic concepts the first lines of code from the harpy pipeline that is used in the spatial trainings was shown. I don’t know if you noticed but some lines start with a #

# The dataset will downloaded from the registry.
# If path is set to None, example data will be downloaded in the default cache folder of your os.
# Change path to your directory of choice to overwrite this behaviour.
registry = get_registry(path = path)

These lines are comments. Python ignores them, they are not executed but they are extremely helpful as you can use them to document your code and explain what you are doing. They make it much easier for you and others to read and interpret your code.

Homework

  • Go to the online Python documentation and check what the tempfile package that was imported in the code from the spatial trainings is doing?
  • Open the Python help notebook in VSCode and run the code blocks.

Basic syntax in Python

  • Text in Python is called a string and is written in between (double or single) quotes: e.g. I am a string and ‘me too’. Check out all these examples of Python strings.
  • Numbers in Python are called ints or integers (positive and negative whole numbers) and floats or floating point numbers (real numbers). They are written as they are e.g. 42 or 3.14
  • Booleans in Python are True and False, written without quotes.
  • The null value in Python represents an empty variable, is written as None without quotes.

Python has mathematical operators:  

  • addition, works on numbers and on text! When used on text it concatenates strings.
  • subtraction 
  • * multiplication 
  • /  division
  • ** exponentation

Homework

  • Open the Python syntax notebook in VSCode, read and run the following sections:
    • Basic syntax
    • Variables
    • Assigning (creating) variables
  • Make the exercises of the Assigning (creating) variables section.
  • Take the Python basics of programming quiz (see window on the left here in e-learning).

Comparisons in Python generate booleans

Check this overview of comparison operators in Python. When you try the code you see that comparisons in Python always generate True or False.

Homework

  • Make the exercises of the Comparisons section in the Python syntax notebook.

Conditional statements

Because comparisons generate a Boolean, they can be used in conditional statements. In these statements you specify a condition, and if that condition is met, something happens. If the condition is not met, something else can happen.

if condition:
     what happens when True
else:
     what happens when False

More information and examples of conditional statements can be found here.

Homework

  • Make the exercises of the Conditional statements section in the Python syntax notebook.
  • Take the Python conditional statements quiz (see window on the left here in elearning).

Functions

Functions are blocks of reusable code with a name that perform a specific action. They have inputs and produce an output, a result.

You apply a function by writing its name followed by round brackets (). Inside the () you write the arguments (inputs and options), separated by commas.

function(input, option, option)

This means that you have to know which arguments the function expects before you can use it. To check the arguments of a function, you use the documentation of the function by using help().

help(function)

Python has a set of built-in functions, functions that come with the basic Python installation. You can use them as such without specifying a package in front of their name.

Homework

  • Make the exercises of the Functions section in the Python syntax notebook.
  • Take the Python functions quiz (see window on the left here in elearning).

Tuples

Python contains data types that can store multiple values like tuples, lists and dictionaries. We’ll start with tuples.

Tuples contain multiple elements of any type. The elements have a position or index. In Python, indexes start at 0! Tuples are immutable: they cannot change once they are created. This is why they are typically used to store parameter settings that stay constant during the whole workflow, like dimensions of figures, color settings…

Tuples are created using round brackets. Inside the brackets you specify the elements, all separated by commas:

tup <- (2,0,6)

Homework

  • Make the exercises of the Tuples section in the Python syntax notebook.
  • Take the Python tuples quiz (see window on the left here in elearning).

Lists

Lists allow to store multiple elements of any type and they are mutable. List elements can be modified, added and removed. Each element has a value and an index and indexes start at 0.

Lists are created using square brackets. Inside the brackets you specify the elements, all separated by a comma:

L <- [2,0,6]

Homework

  • Make the exercises of the Creating a list section in the Python syntax notebook.

To retrieve elements from a list, you write square brackets after the name of the list and specify the index of the element you want to retrieve inside the brackets, e.g. to retrieve the first element from L:

L[0]

To retrieve multiple elements you need to define a slice:

L[start:stop:step]
L[1:6:2]
  • start = index of first element to retrieve, in the example we start retrieving from the second element.
  • stop = index of the first element you don’t want to retrieve anymore, in the example we stop retrieving before the seventh element.
  • step = how many indexes to move each time, in the example we move 2 indexes each time.

So in this example we’ll retrieve the second, fourth and sixth element from the list.

Homework

  • Make the exercises of the Retrieving elements from a list section in the Python syntax notebook.
  • Read the section Checking if an element is present in a list in the Python syntax notebook and make the exercises.
  • Read the section The list() function in the Python syntax notebook.

For-loops to repeat actions

To repeat one or multiple actions we use for-loops in Python. For-loops have the following structure:

for x in [1,2,3]:
     print(x)
  • x is a variable, whose value changes in each iteration of the loop
  • after the in keyword you specify a list of values that variable x is going to take.
  • on the next lines you write the actions you want to do with the changing variable. You have to respect the indentation: it defines the body of the for-loop, the code that runs in each iteration.

You can use anything that contains multiple values to loop over, we use a list of values, but you could also use:

  • a list of files to loop over
  • a range of indexes
  • a string to loop over the characters

Homework

  • Make the exercises of the For-loops section in the Python syntax notebook.
  • Take the Python lists quiz (see window on the left here in elearning).

Dictionaries

Unlike lists and tuples, dictionaries don’t just store multiple values, they store key – value pairs.
Each value in the dictionary has a key, a name that you can use to refer to that value and to retrieve it.

You create a dictionary using curly brackets. Inside the curly brackets you write one or more key-value pairs, all separated by commas:

dict = {"key1":value1, "key2":value2}

Methods

Methods are functions that will only work on one type (or class) of variables, for instance only on lists or only on dictionaries. You use them by writing the name of the variable followed by a dot and then the name of the method:

variable.method()

Methods exist because Python is object oriented. Variables (aka objects or instances) are assigned to classes, groups of similar objects. For instance, there is a class of lists in Python and each list belongs to that class. 

Methods are defined on the class level: which is why they apply only to objects that belong to that class. 
In the documentation of the class, you find an overview of all the methods that are specific to that class. 

Homework

  • Make the exercises of the Dictionaries section in the Python syntax notebook.
  • Take the Python dictionaries quiz (see window on the left here in elearning).
  • Read and make the exercises of the Opening text files section in the Python syntax notebook.