Skip to Main Content

Programming with Python

An introduction to programming with Python. Includes how to get started with Python, coding in Python with Jupyter Notebooks, and various links where you can learn more.

Introduction

There are many ways to work with Python. Those learning Python for the first time often find it easiest to practice Python on the cloud using platforms like Google Colab or Dartmouth's JupyterHub. But, for researchers and students ready to build their own projects, it is often preferable to download and install Python on your own machine.

Working with Python on your own computer

There are various different options for installing and working with Python locally on your own computer. Some common approaches include:

1. Installing the Anaconda distribution package for Python. This allows you to install hundreds of packages at once. For more on this option scroll down.

2. One folder - one project - one environment approach: It is good practice to create a separate folder on your computer for each project. However, it is also good practice to set up separate "virtual environments" for each project. This allows you to only install the packages necessary for a project and to, thus, more easily share your project with others. We provide our suggested method to follow this approach next:

Instructions for our recommended Python setup

Visual Studio Code with Virtual Environments Option

While there are different options for installing and working with Python locally, the Dartmouth Library's Research Data Services team recommends the following option: working with Python within Visual Studio Code and setting up a unique virtual environment for each project. For more on what this means and how to do this, follow the instructions below:

Step 1a: Install Python

Download and install Python following the instructions below.

Instructions for MacOS (Ventura or later)

  1. Using a web browser of your choice, navigate to www.python.org.
  2. In the `Downloads` menu, click on the gray button to download the latest stable version of Python.
  3. Install the downloaded `pkg` file with the default settings.
  4. In the `Finder` window that pops up after installation, double-click the file `Install Certificates.command`.
  5. Close the `Finder` window and the installer.
  6. Move the `pkg` file to the Trash
  7. Open the `Terminal` application (located under `Other` in the Launchpad)
  8. In the terminal, type the command `python3` and hit `return`.
  9. The terminal will show the version of Python just installed and a command prompt starting with `>>>`.

Instructions for Windows 11

  1. Using a web browser of your choice, navigate to www.python.org.
  2. In the `Downloads` menu, click on the gray button to download the latest stable version of Python.
  3. Start the downloaded installer:
    1. Check the box next to `Add python.exe to PATH`.
    2. Click `Install Now` and wait for installation to finish
    3. Click `Disable path length limit`.
    4. Close the installer
  4. From the Start Menu, open the Python executable (e.g. `Python 3.12 (64-bit)`).
  5. The terminal will show the version of Python just installed and a command prompt starting with ">>>".

Step 1b: Install Visual Studio Code

Visual Studio Code (or VS Code) is a code editor developed by Microsoft and available on all major platforms (Linux, macOS, and Windows). It is entirely free and largely open-source. Essentially a text editor with superpowers, it supports not just Python but many other programming languages and is incredibly versatile thanks to a plethora of optional extensions. Since it can open, display, or run all kinds of different files, you rarely have to leave the program when working on a project, which makes it a great Integrated Development Environment (IDE).

MacOS (Ventura or later)

  1. Navigate to code.visualstudio.com.
  2. Download the latest stable version.
  3. Open your `Downloads` folder.
  4. Drag and drop the downloaded file `Visual Studio Code` into your `Applications` folder on the left pane.

Windows 11

  1. Navigate to code.visualstudio.com.
  2. Download the latest stable version.
  3. Open the downloaded installer:
  4. Follow the instructions and click `Next` three times.
  5. When prompted, select (or leave selected) all checkboxes under `Other`.
  6. Click `Install`.

Step 2: Getting a Project Started in Visual Studio Code

  1. Open Visual Studio Code (VSC)
    1. When you open VS Code for the first time, you will be greeted by a Welcome screen. For now, choose a theme that you like and close it.
  2. Open a project folder
    1. VS Code works best if you open a folder that contains all files for a particular project (the one project - one folder - one environment approach).
    2. If you don't have a project folder already, create one in your "Documents" folder (or wherever you keep your project files)
    3. Within VSC select File --> Open Folder
    4. You should see this folder and its contents appear in the Explore window on the left panel of VSC
  3. Exploring folder structure
    1. With the "Explorer" view open in the left-side pane of VS Code, experiment by right-clicking (Windows) or CTRL-click (Mac) inside the project folder and create a new folder called Notebooks. Then right/CTRL-click this new folder and select "New File". When creating a new file this way, you need to give it a name and a proper file extension. For example, try creating a plain text file called Notes.txt, a Python file called test_code.py, and a Jupyter Notebook called test_notebook.ipynb.
    2. Note: in the VS Code Explorer window, there are two different ways to open a file:
      1. Selecting a file with a single click opens it in a new tab, but closes it again if you switch to another file (note the name in italics on the tab)

      2. Selecting a file with a double click opens it in a new tab and keeps it open until you close the tab (note the non-italicized name on the tab)

  4. Installing Extensions in VS Code 1: Python extension

    1. Open the Extensions view on the left-side pane. You can add additional functionality to VS Code by installing extensions.

    2. To get started we will install the Python and Jupyter extensions.

    3. Search for Python.

    4. Click on "Install."

    5. Close the "Welcome" tab that opens up

    6. To check that it works, we will write some Python code to a file and execute it:

      1. Open the test_code.py file you created above.

      2. Type the following lines of code in the .py file:

      3. print("Hello World!")
        4 * 7
        x = 26 / 4
        print("x = ", x)

      4. Run the code by clicking the ▶️ icon in the top right

      5. A Python terminal should open in the bottom pane of VS Code. Examine what the output that was produced after running your code file. What information was returned? What was omitted?

  5. Installing Extensions in VS Code 1: Jupyter extension(see fn. 1)

    1. Python scripts always run from top to bottom in their entirety. This is great when you have a fully-formed program that you want to execute, but it is somewhat inconvenient when you want to have more of a back-and-forth, interactive experience. This is often the case when you are doing data analysis, create visualizations, or do any other kind of more iterative work.

    2. To support such use cases, there is an extension for Python called Jupyter. We can install Jupyter on VS Code's `Extensions` tab:

      1. Choose the `Extensions` tab on the Primary Side Bar

      2. The `Jupyter` extension should be listed under the `Popular` heading, otherwise type `Jupyter` into the search box

      3. Click on `Install`

Step 3: Setting Up a Virtual Environment in VSC

[Explain more about importance of virtual environments]

  1. Setup a Virtual Environment in Visual Studio Code (fn. 2)
    1. Select the Search Bar at the top center of VS Code.
    2. Select "Show and Run Commands" --> "Python: Create Environment" --> "Venv".
    3. Select the Python version you installed in Step 1b.
    4. In the Explorer view on the left you should now see a folder called ".venv". Whenever you install new Python packages (also called "libraries") to your local environment they will be installed in this folder.
    5.  
    6. At the top right-hand corner of the notebook you should see a "Select Kernel" button. Click on it and select the "Python Environments" --> select the .venv environment you just created.

Step 4: Getting Started with Python in VSC

  1. Open the Jupyter notebook you created called test_notebook.ipynb.
    1. or you can create a new notebook by selecting: File --> New File --> Jupyter Notebook; Save the new notebook: File --> Save As
  2. Setup Python Kernel
    1. click on Select Kernel in the top right of the notebook. Select Python Environments and .venv.
  3. Experiment with the new notebook
    1. Add new cells using ESC + B or clicking on + Code (to add a new code cell) or + Text (to add a new text cell).
    2. try typing in some text in the markdown / text cells
    3. try running some basic code in the code cells
      1. upon running your first code cell, VSC may ask you if you want to install the ipykernel package. Select Install.
    4. try importing a Python package in a code cell, such as pandas running import pandas as pd
      1. Note: you will receive a ModuleNotFoundError. This is because we need to install pandas into the local virtual environment before importing it. To do that we need to return to the terminal in VSC:
  4. Install Python Packages to local virtual environment (.venv)
    1. to install packages into the virtual environment you will want to:
      1. Open a Terminal (select Terminal --> New Terminal). You should see a new terminal pane open at the bottom of VS Code.
      2. check to see if the virtual environment is activated (you will see (.venv) at the start of each new line in the terminal.
      3. install a new package using pip. The most common syntax for installing packages in the terminal is:
        1. Windows: pip install [package-name]
        2. Macs: pip3 install [package-name]
        3. Note: Some Python packages require more specific instructions. You will want to find the online documentation for such packages.
    2. Install pandas, a popular package used for working with dataframes, by typing the following in the terminal:
      1. Windows: pip install pandas
      2. Macs: pip3 install pandas
    3. Return to your notebook and run the cell importing pandas again import pandas as pd. It should work now.
  5. Create requirements.txt file for sharing package requirements
    1. After installing several packages into your virtual environment you can view what packages have been installed typing pip freeze (for Windows) or pip3 freeze (for Macs) in the terminal. Note: you will see far more than those packages you manually installed. This is because when you install a new package, pip automatically installs other packages that your requested package depends on.
    2. You can save the list of packages you have installed into a virtual environment by typing pip freeze > requirements.txt (for Windows) or pip3 freeze > requirements.txt (for Macs) into the terminal. You should see a new file called "requirements.txt" in the Explorer window on the left. Open the text file and review its contents. The requirements.txt will allow others to reproduce the exact same virtual environment on their computers and thus ensure they can run the same code as you.
      1. Note: the requirements.txt file does not automatically update when you install new packages. Run pip freeze > requirements.txt (for Windows) and pip3 freeze > requirements.txt (for Macs) as needed before sharing the requirements.txt file with a collaborators.
  6. Recreating someone else's virtual environment.
    1. If you wish to recreate someone else's virtual environment or a virtual environment you used on another project, the requirements.txt file comes in handy.
    2. With the requirements.txt file moved into your project folder, type pip install -r requirements.txt (for Windows) or pip3 install -r requirements.txt (for Macs) into the terminal. This will install all packages (and their specific versions) listed in the .txt file.
  7. Deactivate the virtual environment
    1. if you ever need to deactivate your virtual environment from within the terminal just run deactivate.
  8. Customizing Visual Studio Code (VSC)
    1. Open the Extensions pane in the lefthand window of VSC
    2. Search for and install Jupyter and Python extensions

 

 

Other Ways to Work with Python

Other Options for using Python on your own computer

Besides the above method, there are other ways to install Python on your own computer. Perhaps the most popular alternative is to install the Anaconda distribution package. To do so:

  1. Install the Anaconda distribution package for Python. This will install 1000s of the most popular Python packages and a dozen or so software tools for working with Python. You can then open Anaconda and experiment with coding in Python using Jupyter Notebooks, PyCharm, Spyder, or other included software.Additional instructions for installing Anacaonda can be found here.
  2. To install packages with Anaconda, you will use conda instead of pip in a terminal. But keep in mind many of the packages you will most commonly used are already installed with anaconda. To see a full list of available packages with conda, type "conda list" in the Anaconda Powershell terminal.

Working with Python on the cloud (the no-installation option)

Teachers and students may choose to use Google Colab or Dartmouth's JupyterHub server. These are great options for instruction and training. However, neither resource allow you to save your work long-term, so are not recommended for research and project work.

For instructors and students using the JupyterHub, please see instructions below:

JHub

Instructions: Opening JupyterHub and Getting Started

1. Open jhub.dartmouth.edu in a browser.

2. Choose "Reproducible Research Workshops"

3. Select "Start My Server." It may take a few minutes to load. Once open, your JHub page should look something like this (if you've opened it before, however, you may already have a notebook or other files open):

4. Use the screenshot below to find the root folder of your JHub directory:

5. You should then navigate to your workshop folder. For the Text Analysis in Python series, for example, you will want to go to the following directory: RR-workshops/text-analysis/text-analysis-with-python to find workshop materials. To get started with the Week 1 ("Strings and Files") workbook you will want to also open the strings-and-files folder

Footnotes

Fn. 1: Installing Jupyter Notebooks with the Terminal

  1. Open a terminal in VSC - VSC allows a user to move back and forth between a terminal (also known as "The Command Line") and Python scripts and notebooks
    1. Select the Terminal tab --> New Terminal
    2. A terminal window will appear at the bottom of VSC.
    3. [explain diff types of terminals available]
    4. We will use the terminal to install Jupyter Notebooks
    5. In the terminal type:
      • Windows: pip install notebook
      • Macs: pip3 install notebook

 

Fn. 2: Creating a Virtual Environment (.venv) with the Terminal

1. In the terminal type:

Windows: python -m venv .venv

Mac: python3 -m venv .venv