M2: Python Foundations#

Now that you have set up everything and know how to run Python code, we can get started with writing our first algorithms! In this module we will go over the basic building blocks you need to write a Python code such as variables, conditional blocks, and error handling. At the end of this module you will be able to already do some basic manipulations and calculations of biomedical data using Python code.

1. Python Syntax#

Before we dive deeper, it’s important to get a feel for how Python code is organised — in other words, its syntax.

1.1. Indentation and Code Blocks#

In Python, each new statement normally starts on a new line. This means you don’t need to end each line with a semicolon ;, unlike some other programming languages.

Python also uses indentation to define blocks of code. In other languages, you might see curly braces {} or keywords to group code together. In Python, you just add spaces or a tab at the beginning of a line to show that it belongs to a block. One indent is usually either one tab (Tab) or four spaces (Space).

When you indent a line, you’re creating a “child” of the previous line. Usually, a “parent” line ends with a colon : (you’ll see more examples of when colons are used when we cover conditionals later in Chapter M2-conditional-blocks-header). You can also have multiple blocks nested inside each other.

To end a block, just remove the indentation (using Shift + Tab). It’s also a good habit to leave a blank line between big blocks of code to make everything easier to read.

im_a_parent:
    im_a_child:
        im_a_grandchild:
            print("I am a grandchild!")
        im_a_second_grandchild:
            print("I am another grandchild!")
    im_a_second_child:
        im_a_third_grandchild:
            print("I am the third grandchild!")

im_a_new_parent:
    im_a_new_child:
        print("I am a new child!")

These syntax rules do not only help to keep your code neat, but also make it easier and quicker to write them, eliminating common mistakes (such as forgetting to put a semicolon at the end of a line).

Below is an example of an if statement using indentation. The if statement checks whether the age variable is greater than 18. The line print("The patient is an adult.") is indented to show that it belongs to — or is a child of — the if statement’s code block. This line is only executed if age is greater than 18.

Do not worry if you are not yet familiar with the specific details in the code snippet — we will learn them throughout this course! The most important takeaway here is that consistent indentation is crucial. If the indentation in your code is inconsistent, Python will raise an error!

age = 20

if age > 18:
    print("The patient is an adult.")
The patient is an adult.

1.2. Comments#

We have already briefly introduced comments in the previous module. As a reminder,comments are lines or parts of lines that Python does not execute. They can be used to explain your code. It is very useful to have comments throughout your code. When other people read your code (or even when you read it yourself later), it is often difficult to understand what it is trying to achieve based on the executable lines alone. Having comments alongside the code, explaining its purpose, makes understanding it a lot easier.

Comments are also useful when debugging, as they can be used to temporarily disable lines of code. Just remember to either uncomment or delete these lines later to keep your code neat!

There are two types of comments: single-line comments and multi-line comments.

  • Single-line comments: Start the comment text with a hashtag #, for example:

# This is a single-line comment.
print("Hello, World!") # This part is also a comment.
Hello, World!
  • Multi-line comments: Use triple quotes (""" or ''') around the comment text, for example:

"""
This is a multi-line comment.
It can span multiple lines.
"""

1.3. Basic Print Statements#

While not technically part of the syntax rules, the print() function is a very useful feature, which is why we introduce it early on. As mentioned in the previous module, it is used to display output on the screen. In a jupyter notebook it will display everything in a print statement underneath the code cell. When running code in the terminal it will show all your print statements in the terminal. Print statements are very useful for keeping track of where you are in your code, preliminary results, and whether your code is working as expected. Note: in Jupyter notebook the last line of a cell will also always be displayed. But it is a good habit to always use a print statement and to not rely on the automatic output since your code structure can change easily.

'Hello, from the first line in the cell' #this string will not be printed
print("Hello, Python!")
print("Hello, User!")
'Hello, from the last line in the cell' # this string will be printed since it is the last line in a jupyter notebook cell
Hello, Python!
Hello, User!
'Hello, from the last line in the cell'

1.4. Quick Practice#

We have reached the end of the first chapter! You should now be able to write your first snippet of Python code. Let’s start with the standard first programme: printing ‘Hello, World!’.

To practise the syntax, you will create an if statement (similar to the example before). The code should have a variable called say_hello which is set to True (can be defined the same way as age in the above example - you will learn what variables are in the next chapter). It should have then an if statement that calls the print() function if say_hello == True . The print() function should output 'Hello, World!'. Try to also add both multi-line and single-line comments to explain your code.

Try creating the code in the following empty code block. Remember that you can click the spaceship symbol at the top right hand side of the page and then ‘Live Code’ to be able to write and run your code directly in this book. If you get stuck or what to compare solutions, open the hidden solution code block underneath.

# Put your code here
💡 Solution

"""
Example of a simple if statement with indentation.
It will print 'Hello, World!' if say_hello is True.
"""

say_hello = True # we want to say hello

if say_hello == True:
    print("Hello, World!")

🎯 Mini-Challenge: Test Your Code

Try changing the value of say_hello to False.

What happens when you run the code now?

💡 Solution

Because the condition in the if statement is no longer True, the print() line will not be executed!