Gregg Eschelmuller

PhD Student at the University of British Columbia

Learning Python for research (Part I)

Welcome to the first post in my Python programming series! As a PhD student in motor control and neuromechanics, I've found that learning to program has been one of the most valuable skills I've developed during my graduate studies. In this series, I'll share my journey of learning Python and how it has enhanced my research work.

Why Python?

Python has become the go-to programming language for researchers and scientists for several reasons:

  • Readable and intuitive syntax
  • Extensive libraries for scientific computing
  • Strong community support
  • Cross-platform compatibility

How Programming Helps with Grad School Work

In my research, I use Python for:

  • Data analysis and visualization
  • Statistical modeling
  • Automating repetitive tasks
  • Processing experimental data
  • Running motor control experiments with psychopy
  • Building models of motor control

Getting Started with Python

To begin your Python journey, you'll need to install Python on your computer. I recommend using Anaconda, which comes with many scientific computing packages pre-installed.

What is Anaconda?

  • Anaconda is a distribution of Python and many other packages
  • You can use it to install Python and organize all the libraries you may use
  • You will also use it to create virtual environments, which is a great way to manage your Python libraries
  • There are other distributions of Python, but I recommend Anaconda because it's what I use and I'm familiar with it. Additionally, it is pretty straightforward to use and comes with a GUI if you are not comfortable with using your terminal

How to Install Anaconda

  1. Visit Anaconda's download page
  2. Download the installer for your operating system
  3. Run the installer and follow the prompts

How to Use Your Terminal

If you're not comfortable using the terminal, I recommend starting with Anaconda Navigator, a graphical interface that makes it easy to manage environments and packages. However, learning to use the terminal can be incredibly helpful. Relying solely on GUIs often means juggling multiple programs for different tasks. For instance, you'd use Anaconda Navigator to manage virtual environments, GitHub Desktop to handle repositories, and so on. By contrast, the terminal allows you to streamline your workflow and automate repetitive tasks through tools like Bash scripting, making you much more efficient in the long run.

Opening the Terminal

macOS

On macOS, you can open the terminal by searching for it in Spotlight or by pressing Command + Space and typing "terminal".

Windows

On Windows, you can open the terminal by searching for it in the start menu or by pressing Windows + R and typing "cmd".

However, on Windows, I would recommend using Git Bash, which is a terminal emulator that allows you to use a bash shell in Windows. You can download it here. You will likely want to download Git anyway, so this is a good time to set it up. To link up your Git Bash with Conda, you can follow the steps in this post here.

Linux

If you are on Linux, I am going to assume you know how to open the terminal. But do check that your Conda is installed properly (see below).

Checking That Conda is Installed

To check that Conda is installed, you can type conda --version in your terminal. If it is installed, you will see something like conda 4.14.0.

If you see something like conda: command not found, then check that you completed the installation steps above.

Basic Terminal Commands

If you want to learn about your terminal, you can start here here. But here are a few a simple exercises to get familiar with basic terminal commands. Try these commands in your terminal:

$ ls
Documents  Downloads  Pictures

The command ls shows the contents of your current directory. Now let's create a new directory using the command mkdir:

$ mkdir test
$ ls
Documents  Downloads  Pictures  test

Notice the new 'test' directory in the list. Let's move into it using the change directory command cd:

$ cd test
$ ls

The directory is empty. Let's create a new file using the touch command:

$ touch test.txt
$ ls
test.txt

Now let's remove the file using rm:

$ rm test.txt
$ ls

The directory is empty again. Here's a summary of what each command does:

  • ls - Lists files and directories in the current location
  • mkdir test - Creates a new directory named "test"
  • cd test - Changes into the "test" directory
  • touch test.txt - Creates an empty file named "test.txt"
  • rm test.txt - Removes the file named "test.txt"

Creating a Virtual Environment

A virtual environment is like a separate container for your Python project. It allows you to:

  • Install specific versions of Python packages without affecting other projects
  • Keep your project dependencies isolated and organized
  • Easily share your project setup with others
  • Avoid conflicts between different projects' requirements

Here's how to create and manage a virtual environment using Conda:

1. Create a New Environment

Note: The exact text and output you see may vary depending on your operating system and current directory. Don't worry if your output looks different! Most of the text I have added here was simplified for ease.

First, you will need to create a new environment. You can do this by running the following command: conda create -n learn-python python=3.11

.
$ conda create -n learn-python python=3.11
Collecting package metadata (current_repodata.json): done
Solving environment: done

## Package Plan ##

  environment location: /Users/username/anaconda3/envs/learn-python

The following packages will be downloaded:
    package                    |            build
    ---------------------------|-----------------
    python-3.11.0             |       hb7a2778_3        21.2 MB
    ------------------------------------------------------------
                                           Total:        21.2 MB

Proceed ([y]/n)? y

Preparing transaction: done
Verifying transaction: done
Executing transaction: done

This command creates a new environment named "learn-Python" with Python 3.11 installed. The prompt will ask for confirmation before proceeding.

2. Activate the Environment

Now that you have created an environment, you can activate it by running the following command: conda activate learn-python

$ conda activate learn-python
(learn-python) $

Notice how the prompt changes to show the active environment name in parentheses. This indicates you're now working within the "learn-Python" environment.

3. Verify Your Environment

You can verify that you are using the correct Python version by running the following command: python --version

(learn-python) $ python --version
Python 3.11.0
(learn-python) $ conda list
# packages in environment at /Users/username/anaconda3/envs/learn-python:
#
# Name                    Version                   Build  Channel
python                    3.11.0               hb7a2778_3

These commands confirm you're using the correct Python version and show the installed packages.

4. Deactivate When Done

When you're finished working, you can deactivate the environment to return to your base environment using the command conda deactivate.

(learn-python) $ conda deactivate
$

Additional Tips

  • To see all your environments: conda env list
  • To remove an environment: conda env remove -n learn-python
  • To update all packages: conda update --all

Now that you have your environment set up, you're ready to start coding! Let's move on to some basic Python syntax.

Installing a text editor/IDE

Now that we have our environment set up, we can install a text editor or IDE. I recommend VS Code or PyCharm. However, there are many other options out there and I encourage you to explore, or if you have used one already stick with that one. I would recommend choosing one and sticking with it while you are learning, as you want to focus on learning Python, not figuring out how to use a new text editor.

You may have also heard of JupyterLab, which is very common for jupyter notebooks. I personally don't use it, as I don't find the support for other languages and features in Python as good as VS Code or PyCharm/DataSpell. But if you want to use it, you can install it via Conda by running: conda install -c conda-forge jupyterlab in the environment you want to install it in. Link to JupyterLab installation page. This will install it like other packages/libraries. Then, to launch JupyterLab, type jupyter lab in your terminal (make sure you are in the environment where JupyterLab is installed). JupyterLab will then open in your default browser.

Basic Python Syntax

Now that you have your environment set up and a text editor/IDE installed, you can start coding! First open a new file in your text editor/IDE and save it as hello_world.py. Now open that file in your text editor/IDE and you will see a blank screen. Hello World is a traditional first program to write when learning a new programming language, so let's write that first. In your .py file, write the following code:


print("Hello, world!")
                

Now, you can run the program by clicking the run button in your text editor/IDE. Or you can run it in your terminal by typing python hello_world.py and pressing enter. If you are in the environment you created earlier, you should see the following output:


Hello, world!
                

Congratulations! You have just written your first Python program. Now let's move on to some more fundamental concepts.

Variables and Data Types


# Variables can store different types of data
name = "Gregg"  # String
age = 28        # Integer
height = 1.75   # Float
is_student = True  # Boolean

# Print variables
print(f"My name is {name} and I am {age} years old")
                

Comments


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

Python as a calculator


# addition and subtraction
x = 5 + 7   # x is now 12
y = 10 - 4  # y is now 6
z = x + y   # z is now 18

# multiplication
a = 3 * 4   # a is now 12

# division
b = 15 / 3  # b is now 5.0 (result is always a float)

# floor division
c = 15 // 2 # c is now 7 (integer division)

# modulus (remainder)
d = 15 % 4  # d is now 3

# exponentiation
e = 2 ** 3  # e is now 8
                

Keeping It Low-Stakes and Experimental

Remember that learning to program is a journey, and it's okay to make mistakes. Here are some tips for success:

  • Start with small, manageable projects
  • Use online resources and documentation
  • Practice regularly, even if it's just 15 minutes a day
  • Don't be afraid to experiment and break things

In the next post, we'll dive deeper into Python's data structures and control flow. Stay tuned!