DEV Community

Cover image for Computational physics with Python: tool setup
Paul Cochrane đŸ‡ȘđŸ‡ș
Paul Cochrane đŸ‡ȘđŸ‡ș

Posted on ‱ Originally published at peateasea.de on

Computational physics with Python: tool setup

Imagine you want to learn computational physics and Python as an advanced high-school student or undergraduate. Where to start? Assuming no prior programming experience, a quick introduction to programming concepts won’t go amiss. To get to that point, though, you’ll need to prepare some tools first.

In this post, I describe how to install Python and Visual Studio Code, two tools we need before we can start programming and learning computational physics. I then describe how to configure VS Code to use Python, finishing up by writing a toy Python program and running it within VS Code.

A high school student that I tutor asked me a while ago if one can learn physics by programming in Python. I answered: “Of course!” Since then, I’ve had all kinds of ideas about how to introduce computational physics and numerical methods to advanced high-school or early-level university students.

This is the first post in a (long-term) series focusing on numerical methods and computational physics. The intent is to collect enough topics and examples to create a course in computational physics using Python.

A rough plan

My rough plan is to discuss concepts already taught at school, for which we know the analytical solution. This way, we focus on learning the numerical methods, secure in the knowledge that we have a firm understanding of the mathematics and physical concepts.

Then we implement the numerical solution in Python and compare it with the analytical one to see how well we did. This reduces cognitive load: we’re not introducing new physics and maths concepts. The only things that are new to us are programming and the relevant numerical methods.

One long-term goal is to build sufficient understanding of the numerical methods so that we can move out of our comfort zone and learn to solve physical problems where an analytical solution is either unknown or difficult to calculate.

Before we can really get going, we need to set up our working environment.

Getting started

To run Python programs, we need a working Python development environment. And to create Python programs, we need software in which we can write code. Thus, we need to do some boring administrative work before we can start doing interesting physics and programming stuff.

This post will focus on getting a Python environment up and running within Visual Studio Code. The following article will introduce some basic programming concepts and show a simple example of using the NumPy and Matplotlib libraries. This foundation will enable us to focus on computational physics topics later.

The installation guide described here assumes a Windows environment. I made this decision because I assume that most students either use Windows or have access to a Windows computer.

Some students will have macOS. Unfortunately, I don’t have access to a macOS system. Hence, I can’t describe the installation process in that environment.

Other students likely use Linux. From personal experience, Linux users are often in the minority. So, even though I would like to describe the process from a Linux perspective, I chose Windows because it is relevant to most students.1

We now focus on installing Python and the Visual Studio Code integrated development environment (known simply as VS Code). As you will see below, there’s a lot of setup required before we can get to the fun stuff and start programming. Fortunately, we only have to do this setup once, so it’s worth taking our time to do it properly.

Installing Python

According to the Visual Studio Code tutorial on installing Python, it’s recommended to install Python first, so we’ll start there. This ensures that Python is available for VS Code to find when we install it later.

There is also good documentation on the VS Code website for writing and running Python programs. You can find more information under the “Python” link on that site.

Before installing Python, we have to download it. The best place to get it for Windows is from the Python website. Using a browser, navigate to the Python downloads page:

Python downloads page

Now click on the “Download Python” button to download the most recent version of Python (note that the version number you see will be different to that shown in the screenshot above).2

After the download has completed, open your Downloads folder and search for the installer application. It’ll be called something like python-3.15.5-amd64.exe (where 3.15.5 is the version number and is likely different in your case). You should see an icon which looks like this:

Python on Windows installer icon

Double-click on the installer icon. You should then see the Python for Windows installer startup dialog box:

Python on Windows installer startup dialog

This window has two unchecked options at the bottom. One mentions using admin privileges when installing Python (which we don’t need), and the other mentions adding python.exe to your PATH. Your PATH tells your computer where to look when it wants to find the program to run Python. It’s therefore a good idea to check this option.

Python on Windows installer with Add python.exe to PATH checkbox checked

Now we’re ready to install Python. Click on the “Install Now” option in the middle of the window. This will install Python and any supporting software it needs.

Once the installation has completed, you’ll see the “Setup was successful” dialog box appear.

Python on Windows installer setup successful dialog box

Click on the “Close” button to continue.

Now that Python is installed, we’re ready to install Visual Studio Code.

Installing Visual Studio Code

One thing to note first: Visual Studio Code is not Visual Studio; they’re different things. Yes, Visual Studio is also an IDE.3 Yes, it’s a product from the same company. Yes, this is confusing. Sorry about that.

Go to the Visual Studio Code download page and choose an installer appropriate for your operating system.

VS Code downloads page

Because we’re using Windows, click on the “Windows” button to download the installer application. This will download a file called VSCodeUserSetup-x64-1.101.2.exe (the 1.101.2 part is the version number; it’ll be different for you).

Open your Downloads folder and double-click on the .exe file’s icon:

VS Code installer icon

This will start the VS Code installer:

VS Code license agreement dialog box

To continue, we have to click on “I accept the agreement”. This way, the “Next” button becomes active.

VS Code license agreement dialog box with license accepted

Click on the “Next” button. You’ll see a window asking you to choose a destination location.

VS Code installer with select destination location dialog

The default option should be good enough, so click on “Next” in this window. A dialog box will appear, asking you if you want a Start Menu folder entry for Visual Studio Code.

VS Code installer start menu folder dialog

This is handy to have, so click on “Next” to continue.

The following dialog box asks which additional tasks the installer should perform.

VS Code installer additional tasks dialog

One option you might want to select, which isn’t one of the default options, is to add a desktop icon. If you want that, go for it, and click on the “Create a desktop icon” checkbox. In this case, I chose not to do this and simply clicked on “Next”.

You’re now presented with an overview of what will be installed.

VS Code installer ready to install dialog

Click on “Install” to install Visual Studio Code. The installation will now start.

You should see that the installation completed successfully.

VS Code installer finish installation dialog

The dialog box has a checkbox to ask if you want to launch Visual Studio Code. This is a good idea, so click on “Finish” to complete the installation and start the IDE.3

The VS Code start page will then appear.

VS Code start page

You could take the walkthrough setup of VS Code at this stage, if you want. We’ll skip that, though, and start installing the extensions we need to get Python up and running within VS Code.

Installing the Python VS Code extension

The next task is to install the Python VS Code extension. This allows us to develop and run Python programs within the VS Code IDE.

To see a list of available extensions, you could either click on the extensions icon from the toolbar on the left-hand side of the page:

VS Code extensions icon

or click on the settings icon (the cog symbol at the bottom left of the page) and select the Extensions menu option.

VS Code extensions menu via settings icon

Either way, you’ll see a list of extensions populated in the left-hand frame in VS Code.

VS Code extensions list

Fortunately for us, Python appears as one of the recommended extensions at the top of the list. If it weren’t, we could have searched for it in the search box above the list of extensions.

To install the Python extension, click on its “Install” button. If you look carefully, you’ll see that VS Code also installs the Pylance and Python Debugger extensions.

VS Code installing the Python extension

Once the Python extension has been installed, you’ll see a help page for getting started with Python development:

VS Code showing Getting Started with Python Development steps

Now we’re ready to set up a project, which will contain the computational physics topics we’re going to investigate as part of this course.

Setting up the project folder

Our next goal is to write a simple Python program. Again, there’s some setup we have to do before we can do that. Such is life when starting at the very beginning. Don’t worry, we’ll soon have enough foundation that we won’t have to spend any time on setup.

In software development, which is part of what we’re doing here, one often collects related files together into a project. This is an organisational structure that keeps related things together; things that share a similar topic or theme. In theory, you could put all files from all projects into your user directory. And yes, I’ve seen people who work like that. However, you’ll find that over time, as you write more and more code, things get hard to find. Such chaos slows you down and makes your life harder. Hence, it’s a good idea to bundle code into projects and–as necessary–into subfolders to keep things organised.

The top-level organisational unit we have is the overarching topic of computational physics. Thus, we’ll create a project folder in VS Code for this topic. Subtopics live in their own folders within the main project folder. The main project folder will also contain the environment we need to run Python programs.

There are two ways to create a project folder. We can either click on the “File” menu and choose the “Open Folder
” option, or we can click on the “Open Project Folder” button from the “Get Started with Python Development” page. For example:

VS Code open folder menu

We’ll choose the second option, because it’s a single click. Clicking on the “Open Project Folder” button in the middle of the page will open the “Open Folder” system dialog.

VS Code open folder dialog

The issue right now is that we don’t have a prior project folder we want to open: we’ve got to create a new one. To do this, click on the “New folder” button at the top left of the “Open Folder” dialog box.

VS Code new folder created

This created a new folder in the current directory. You should see that the folder’s name (“New folder”) is highlighted and thus ready for us to rename. Let’s call this folder ComputationalPhysics.

VS Code rename folder to computational physics

Click on the “Select Folder” button at the bottom right to select it as our project folder for use in VS Code.

VS Code will now open the project folder. But first, it will ask you if you trust the authors of the files in this folder. Since you yourself are the author, you can click on the “Yes, I trust the authors” button. Assuming, of course, that you trust yourself. 😉

VS Code trust authors of project folder

Creating a Python virtual environment

Theoretically, we’re ready to create a simple Python program and start playing. However, later we want to install some external Python libraries (i.e. libraries that aren’t distributed as part of Python itself) so that we can define and plot data. Thus, we need to set up a virtual environment which will contain these extra libraries.

Setting up a virtual environment is a good idea when writing Python programs. It allows you to keep the extra libraries you install separate from any other Python software you might have, thus avoiding conflicts between libraries with different versions.

Conflicts between different library versions can arise surprisingly easily. Hence, it’s useful to isolate software libraries within their own project context. Our computational physics project is one instance of such a context. Were we to install a library in a global context (i.e. where the library could be used across multiple projects), it’s possible for different projects to need different library versions.

For instance, let’s say program blah needs version 5.2 of a library called buzz, but program foo needs version 3.7 of that same library. It’s not possible to satisfy both requirements had we installed buzz at a global level. But using a virtual environment allows us to keep things isolated. Thus, if programs blah and foo each use their own virtual environment, we can install the appropriate buzz version for each program and avoid conflict.

There are a few ways to set up a virtual environment in VS Code.

One way to do this is to go to the “View” menu and select the “Command Palette
” option:

VS Code view command palette

You will see a list of items in a drop-down menu at the top of the screen.

VS Code command palette options list

You can either type “Python: Create Environment” into the box at the top:

VS Code Python create environment in command palette

or scroll down the (very) long list of options until you see the “Python: Create Environment
” option. Either way, click on this option now to create your Python environment.

Another way to do this is to click in the box at the top middle of the screen containing a magnifying glass icon and the name of our project folder, ComputationalPhysics. Clicking here will bring up a menu including the option “Show and Run Commands”.

VS Code search box options

Assuming that the “Get Started with Python Development” window is still available, click on the “Select or create a Python environment” option and then click on the “Create Environment” button.

VS Code create Python environment from first steps

VS Code will ask us what type of environment we want to create.

VS Code select virtual environment type

Since we aren’t using Anaconda, we only want to use the standard Python virtual environment, so click on the “Venv” option. This will create a folder within our project folder with the name .venv.

VS Code now asks us which Python installation we want to use in our virtual environment. If you’ve installed multiple versions of Python, you’ll see several options in the drop-down list that now appears. In our case, we’ve only installed the one Python version, so we only see one version appear:

VS Code select Python installation

Selecting the Python installation will create the Python environment. You’ll see an info box in the bottom right-hand part of the window telling you about this.

VS Code creating virtual environment

Creating a new Python file

To make sure that everything works as expected, let’s create a simple Python file to check. Usually, you create new files by going to the “File” menu and selecting the “New Text File” option.

VS Code New Text file menu option

However, because we’re just getting started, we click on the “Create a Python file” step from the “Get Started with Python Development” window:

VS Code Create Python File from first steps

Doing so will open a Python file called Untitled-1 in a tab next to the “Welcome” tab containing the “Get Started with Python Development” stuff.

VS Code new Python file next to Welcome tab

Note that if you open a new file via the “File” menu, you’ll only see the new file in a tab and the “Welcome” tab will be hidden.

A personal statistics program

We’re now going to create a small program which asks you some questions and prints back that information in a slightly different form. It’s not very interesting, but it allows us to see that the Python environment is working, and we can start some basic programming.

Click in the tab named Untitled-1 and enter the following text:

name = input("What's your name? ")
age = int(input("What's your age (in years)? "))
height = float(input("What's your height (in m)? "))

print(f"Hello {name}! You are {age} years old and {height} m tall.")
Enter fullscreen mode Exit fullscreen mode

You need to save this file before you can run it. You save files by either selecting the “File” menu and then the “Save” option:

VS Code Save menu option

or you could use the key combination Ctrl+S. This means you press the control key (labelled Ctrl on your keyboard) together with the s key.

Either way, you’ll see a dialog box to save the file as a certain name.

VS Code Save As dialog box

In the “File name:” field at the bottom, where the text “Untitled-1” is highlighted, enter the name print-personal-stats.py. Then click on the “Save” button in the bottom right-hand corner.

Now we’re ready to run the file. At the top right of the VS Code tab with our Python code in it, there’s a small triangle which looks like the symbol for “Play”. If you hover your mouse over this triangle, you’ll see the text “Run Python File”.

VS Code Run Python File icon

Click on the triangle to run the file.

You will see a new window appear in VS Code. This is your terminal window where your program runs.

VS Code terminal window, stats program started

You’ll also notice that your program has started, and it’s already asking you a question. To enter text into the terminal, you have to click in its area at the bottom of your VS Code window to focus it. This will allow you to interact with your running program. A cursor (a small white rectangle) will appear where you can now start entering information.

As an example, enter the following information:

  • When asked for the name, enter: Alice
  • When asked for the age, enter: 42
  • When asked for the height, enter: 1.57

After typing each piece of information, press the “Enter” key to pass it to the program. You should see output like this:

VS Code terminal window, stats program input and output

Congratulations! You’ve run your first Python program in VS Code!

We’ve fulfilled a large number of the first steps listed in the “Get Started with Python Development” welcome tab, and we’re able to continue with confidence. We can close this tab and free up some room in the VS Code window.

Close the “Welcome” tab by clicking on the small “x” next to the word “Welcome”.

VS Code close Welcome tab

That gave us a lot more room to see our code. Nice!

More next time

That will do for this time. We’ve come quite far in getting everything we need up and running. Next time, we’ll discuss the Python code in detail, talking about programming concepts such as variables, assignment, and data types.

  1. As a long-time Unix and Linux user, this does break my heart a bit. However, I have to realise that Windows is the most common environment for students in the wild and adapt to that. ↩

  2. Note that you could go to the Python for Windows downloads page. But it turns out to be easier to click on the “Download Python” button on the main downloads page. If you’re on Windows, it will detect that and will provide you with a direct link to download Python. ↩

  3. IDE stands for Integrated Development Environment. This is a term for a very powerful code editor packed with lots of functionality that makes editing and running code very easy. You could use something simpler, such as vim orEmacs, to write Python code, and many people do. IDEs such as VS Code are very prevalent in software development circles. ↩ ↩2

Top comments (0)