Vpython Physics Tutorial Homework

I recently facilitated a workshop for high school physics teachers in South Africa (two workshops actually—one in Johannesburg and one in Cape Town). The goal of the workshop was to introduce teachers to using python in physics. Since this was my first python-physics workshop, I feel I should share the details and some of the things I learned.

The Workshop Content

This was a four hour workshop so I had plenty of time (or so I thought) to let the teachers actually work on some python code. I started off with an introduction and short lecture on the basic idea of numerical calculations. After that, I would start with some example code (maybe complete or maybe incomplete) and then give the teachers time to work on some "homework" questions about that code.

You can find all my workshop notes (with links to code) in this Google doc. Yes, I probably should have used something other than a Google doc, but more on that later. But let me go over the basic outline.

  • Start with an object moving at a constant velocity and in one dimension. Go over the code and then give the participants an opportunity to change the code to answer some homework questions. Note: I decided to start off with very simple code. The results are printed out and there are no graphs and no 3D elements.
  • An object moving in 1D with a constant acceleration. This is essentially the same as the program above but with a non-zero acceleration.
  • Introduction to graphs. First, I show how to add a graph to the same constant acceleration problem and then I give the teachers a problem with two moving objects and they use a graph to find when these objects meet.
  • Mass on a vertical spring. This is a short mini-lecture in which I show both how to model the force due to a stretched spring and then how to make a python model of a mass oscillating on a vertical spring. I show what the output should look like and then give the participants code with some parts missing. After they get the program running, there are some questions to suggest things they could change.
  • Vectors and vector operations. This is just a demonstration of how VPython handles vectors. I have a sample code, but I don't give them any questions to work on. Instead we just move to the next thing.
  • Introduction to 3D objects. I show the VPython objects: sphere, box, arrow. After that I show a simple example of a ball tossed in the air (straight up) with 3D visualizations. There is no homework for the participants, this is just a demo.
  • Projectile motion. The teachers are given the program of the ball tossed in the air (from the previous example) and then they need to make it a program with a ball tossed at angle.
  • I have more programs to go over, but in both workshops we were running out of time. I showed a demonstration of projectile motion with air resistance and orbital motion.

Again, all of these starter programs are in the resource document. That document also contains a link to the presentation I used in the workshop as well as other useful links.

Issues and Suggestions

As with any workshop, there are unexpected issues that come up. Here are some of the things that I learned from the two workshops.

  • This was a BYOD (bring your own device) workshop. About half the faculty used a laptop computer but the others used tablets (the iPad was popular) or even their phones. I have to admit that I was surprised at how well these things worked on just a phone—sure it's difficult to edit and read, but it works.
  • Make sure you have enough power outlets. For the second workshop, there were only about 6 power outlets available to the faculty. This was an obvious issue in the second half of the workshop when the laptop users started running out of energy.
  • Trinket.io works better than Glowscript. In general, I like to use Glowscript over Trinket. However, in a workshop it seemed easier to provide links to sample programs in Trinket.io. With Trinket, the users could just go ahead and start running/editing the code. In Glowscript, they need to first login with a Google ID then open my code and copy-paste into a new window. Those extra steps can really cause some problems.
  • A four-hour workshop might seem like a long time, but it's pretty difficult to get through all the examples I wanted. I don't think the faculty could handle anything longer—maybe it should be a two day event.
  • There might be some issues with browsers. I noticed at least one case where a user had a problem with Safari on an iPad. However, the code worked when it was tried in the Chrome browser. Just be aware of these issues.
  • Originally, I had all of my resources on an editable Google doc file. It was editable so that participants could add questions as they worked through the material. This was a huge mistake. There were several cases where a link was accidentally deleted. For the second workhops, I just decided to make the document viewable only.
  • Speaking of editing, be careful with Trinket. I created some sample programs for the users to start the activities. Trinket is nice since they can just start editing the program but it doesn't change the "master" code. However, if I want to show an example on the projector to the whole workshop, I have to be careful. Editing the code when logged in as me (the creator) changes it for everyone. Oops.

OK, some final comments. First, I would like to thank Mark Horner and Colleen Henning for their excellent hospitality during my time in South Africa. Second, before my trip everything I knew about South Africa I learned from Lethal Weapon 2 and District 9. Neither of these movies accurately portray South Africa.

Lastly, here is a picture of some penguins near Cape Town.


GlowScript VPython and

Using VPython to create 3D animations

VPython makes it unusually easy to write programs that generate navigable real-time 3D animations. It is based on the Python programming language which is widely used in introductory programming courses thanks to its clean design, and it is also widely used in science and business.

Classic VPython was originated by David Scherer in 2000. In 2011 David Scherer and Bruce Sherwood initiated the development of GlowScript, a similar programming environment but which runs in a browser. In 2014 it became possible to use RapydScript, a programming language very similar to Python, to support VPython programs in the GlowScript environment.

Here is an overview of the project, and here is a log of developments. Here is the open source for this project. There is also technical documentation about the GlowScript environment, including how to use JavaScript or RapydScript for your programs.

There is also VPython 7 originated by John Coady in 2014 and under continuing development by John Coady, Ruth Chabay, Bruce Sherwood, Steve Spicklemire, and Matt Craig. It uses GlowScript VPython syntax but with standard Python, thereby providing access to standard Python modules. For details seevpython.org. Also of interest is a discussion about plans for the future evolution of VPython.

This documentation describes both GlowScript VPython and VPython 7.

For a quick introduction, see the following YouTube videos, but be aware that for the current version of VPython the name of the module is "vpython", not "visual", and the graphics display is shown in a browser tab rather than in a bare window. (For GlowScript VPython, you can omit importing vpython.)

3D Objects

Variable Assignment

Beginning Loops

Loops and Animation

Scale Factors

Debugging Syntax Errors

Lists, Part 1

Lists, Part 2

There is a series of GlowScript VPython tutorials by Rhett Allain in the context of predicting motion computationally, at the level of an introductory physics course. Using tools at trinket.io it is easy to add both editing and execution of GlowScript VPython to your own web pages, and Allain in his physics blog for Wired magazine has shown examples of this.

Getting started

To write a VPython program, sign in at glowscript.org.

* You will see the sentence "You are signed in as <your user name> and your programs are here." Click on here.

* Click Create New Program. (You may wish to click on the Public tab before creating your program, as programs in your Private folder are not accessible to others.) Choose a name for the program, which should not include spaces or underscores.

* Below the line GlowScript 2.6 VPython, type box(). Click Run this program to run your program. You will see a white box on a black background.

* Use the right button (or CTRL-drag left button) of the mouse to rotate the camera to view the scene from different angles.

* To zoom in and out use two buttons, or ALT/OPTION-drag, or the mouse scrollwheel. Touch screen: swipe or two-finger rotate; pinch/extend to zoom.

Using the text editor

Here is a list of keyboard shortcuts for find, replace, etc. While editing, press Ctrl-1 (Cmd-1 on Mac) to run your program in the same window. Press Ctrl-2 (Cmd-2 on Mac) to run your program in a separate window, which lets you view your program and its execution side by side. If you change your program, press Ctrl-2 again in the editor display to re-run the program with the new changes. GlowScript uses the ACE text editor. Because ACE doesn't work on mobile devices, a simpler editor is used there.

A particularly useful shortcut is Ctrl-/ (Cmd-/ on Mac). Select one or more lines in your program and use this keypress to toggle whether those lines are commented out or not. Also, select one or more lines and press Tab to indent or Shift-Tab to unindent.

It is recommended to use the Chrome browser for developing programs, as it provides the most useful error messages, though programs can be written and run in all browsers, including on smartphones and tablets. In some cases program errors are visible only if you press Shift-Ctrl-J to display the Chrome console.

Letting others run your programs

While viewing the text of your program, click Share this program to see how to let other people run your program. For people to run your program by linking to it, the program must be in a public folder or be exported to your own web site. In fact, the code available on the share page can simply be pasted into a file and saved with the extension ".html", and then you can run the program simply by doubleclicking the html file.

Descriptions of the options available in the left margin

Introduction: The basics of Python and VPython.

Tutorial: More on VPython, including making an animation

Pictures of 3D objects: What the objects look like

Choose a 3D object: Details of cylinder, box, etc. Start with cylinder for an overview.

Work with 3D objects: Issues that apply to all 3D objects: color, material, etc.

Windows, Events, & Files: Creating/modifying windows; handling mouse/ keyboard events; reading/writing files

Vector operations: Magnitude, dot and cross product, rotation, etc.

Graphs: Making graphs of data.

factorial/combin: Special functions used in probability calculations.

What's new: VPython in GlowScript, plus the history of VPython..

Be sure to explore the many GlowScript example programs, written using JavaScript, RapydScript, or VPython. The VPython option is based on the RapydScript-NG Python-to-JavaScript compiler. For most programs, RapydScript is nearly the same as Python, but there are differences which can be seen in the RapydScript documentation.


Do not use "wait" or "_" as a variable name. All GlowScript languages (VPython, RapydScrpt, JavaScript) use "wait" or "_" as a special signal for the compilation process. This signal is inserted for you where needed.

For experienced programmers

As a convenience to novice programmers to provide everything that is needed to get started, VPython by default imports all of the VPython features and includes standard math functions such as sqrt. The documentation is written as though "from vpython import *" were present. Also provided are clock(), random(), and arange().

You can however import selectively, as shown in the following examples, which are compatible with VPython 7. (To help with converting from Classic VPython, VPython 6, you can refer to "vis" or "visual" instead of "vpython".)

import vpython
import vpython as vp # "vp" is any name of your choice
from vypthon import box, color

For those who have used Classic VPython

A few Classic VPython objects are not currently available in VPython: convex, faces, and frame. The objects vertex, triangle, and quad represent a more powerful alternative to faces. Many applications of frame can be handled with the compound object.

One way to deal with differences is to check the elements of the "version" variable that is available in all versions of VPython:

Classic VPython:    version is ['X.Y', 'release']
GlowScript VPython: version is ['X.Y', 'glowscript']
VPython 7:          version is ['X.Y.Z', 'jupyter']
and in VPython 7, the version of the GlowScript
graphics library is given by
                  GSversion is ['X.Y', 'glowscript']

The curve and points objects are somewhat different from Classic VPython. Note that now the list of points in a curve object is not a numpy array, so that a loop is required to change all of the points.

To handle mouse events one cannot use scene.getevent() but must use scene.bind(), which is available in all versions of VPython, starting with Classic VPython 6. Also available are scene.pause() and scene.waitfor('click') and related options.

In GlowScript VPython it is not possible to import arbitrary Python modules such as numpy, and any program that uses numpy will have to be modifed. However, loops are fast in the JavaScript language to which GlowScript programs compile, so if you are using numpy solely for the speed of array manipulation, you may be able to replace a numpy calculation easily and efficiently with a loop.

The difference between RapydScript and VPython programs in the GlowScript context is that the VPython option mimics important elements of the syntax and semantics of Classic VPython programs, whereas the RapydScript option implements the same semantics for 3D objects as that of JavaScript programs. For example, in a RapydScript program the sphere object has a size attribute but no radius attribute, and like box, the default bounding box of the sphere is 1x1x1. Also, changing the length of the axis in a RapydScript program has no effect on the size (except for an arrow, which has a special axis_and_length attribute), but in a VPython program, as in Classic VPython, changing the length of the axis also changes the length of the object (the first component of the object's size).

GlowScript by default processes VPython programs as though they had the following statements at the start of the program (which you don't need to include; they will be ignored):

from __future__ import division, print_function
from vpython import *

GlowScript treats 3/2 as 1.5 as in Python 3.x, not 1 as in the Python 2.x language, and the print statement must take the Python 3.x form of print('hello') rather than the Python 2.x form of print 'hello'.

Many programs written in Classic VPython 6 will run in GlowScript VPython or VPython 7 without change after being run through a conversion program written in Python. This program converts (x,y,z) => vector(x,y,z) and obj.x => obj.pos.x. These changes are necessary because GlowScript does not recognize (x,y,z) as a vector nor obj.x as a shorthand for obj.pos.x. The program also converts display => canvas and gdisplay => graph. The program also converts scene.mouse.getclick() => scene.waitfor('click'), which works in both environments.

In GlowScript VPython and VPython 7 you can use the shorthand "vec" for "vector". If you wish to use a GlowScript program containing "vec" in the Classic VPython environment, just add the statement "vec = vector" at the start of the program.


Salvatore di Dio demonstrated in his RapydGlow experiment
how he was able to use the RapydScript Python-to-JavaScript compiler with GlowScript graphics. This inspired the implementation of the VPython (vpython.org) API at glowscript.org. He provided the file papercomp.js for operator overloading, based on the work of
    Jürg Lehni (PaperScript: http://scratchdisk.com/posts/operator-overloading).
He also assembled support for operator overloading and the ability to write synchronous code in the file transform-all.js, based on the work of
    Bruno Jouhier (Streamline: https://github.com/Sage/streamlinejs), and
    Marijn Haverbeke (Acorn.js: https://github.com/marijnh).
Supporting the VPython API in a browser is possible thanks to the work of
    Alexander Tsepkov (RapydScript: https://github.com/atsepkov/RapydScript) and
    Charles Law (browser-based RapydScript: https://github.com/charleslaw/RapydScript_web).

In January 2017 the original RapydScript compiler was replaced with RapydScript-NG by Kovid Goyal, which comes closer to handling true Python syntax.

When the GlowScript project was launched in 2011 by David Scherer and Bruce Sherwood,
Scherer implemented operator overloading and synchronous code using libraries existing at that time. In 2015 it became necessary to upgrade to newer libraries because compilation failed on some browsers; Salvatore di Dio provided crucial help in this update. In January 2017 the operator overloading machinery was further updated.



Leave a Reply

Your email address will not be published. Required fields are marked *