Você está na página 1de 11

PiP Reference Guide

A Guide to Programming in Physics with Vpython and


Glowscript

Dominik Roje
University of Auckland
Physics121
1 Introduction to Python
Python is a high-level, simple to learn, interpreted programming language which makes it
ideal for scientific computing and for beginner programmers.
Python is read from top to bottom, with the computer executing only one line at a time.
Everything in python is case sensitive and order matters. You must define variables before
(above) they are used in your program.
In this reference guide each line of example code will be enclosed in a gray, numbered box
and the output of the sample program (if any) will be displayed in the box below.
It’s also important to know that most programming languages will start counting from 0.
As unintuitive as this sounds it makes a lot of things easier.

1.1 Vpython
Vpython stands for Visual-Python and is a form of python designed to remove the difficulty
of creating visuals from scratch. We’ll be using Glowscript, which is an online interpreter
that lets us write code in a web-browser and store code online.

2 Data Types
Variables allow us to store the information we’ve created. This is done by choosing some
collection of characters and equating it to our data.
e.g.
1 number = 5
This stores the value of 5 into the variable number which can be accessed later at other
parts of your code. However more than just numbers can be stored in variables. Below are
some data types.

2.1 Numbers
-Declaration: Number
e.g.
1 number = 5

2.2 Scientific Notation


-Declaration: mantissa e exponent
e.g.
1 s c i n u m b e r = 3 e2

(3 × 102 , 300, 3 ∗ 10 ∗ ∗2)

2.3 Vectors
-Declaration: vector(Number, Number, Number )
e.g.

1
1 my vector = v e c t o r ( 1 , 2 , 0 )
(Corresponds to (1,2,0) vector)

-Accessing Vector components: my vector.component


Component can be x, y, z, or mag
x, y, and z will return the corresponding coordinates and mag will return the calculated
magnitude of the vector.
e.g.
1 p r i n t ( my v e c t o r . mag)

2.4 Standard Output


While not a data type, python supports a function to output information to the screen in
the form of:
- print(Data)
One can print text to the screen by enclosing the text in quotation marks.
e.g.
1 p r i n t ( ” H e l l o , World” )

Hello, World

Or you can display the contents of variables by directly referencing them within the paren-
theses.
e.g.
1 my number = 100
2 p r i n t ( my number )

100

To output multiple things at once, separate items by comma.


e.g.
1 var=3
2 p r i n t ( ”My number i s : ” , var )

My number is 3

The print function is particularly useful in Debugging, which you can see in Section 5. It’s
useful to output the value of your variables throughout your program to see how they behave
during runtime.

2
2.5 Arithmetic
Programming relies on being able to update variables so that their values will change
throughout the execution of the program. One of the most common methods of updat-
ing a variable is through basic mathematical expressions.
e.g.
1 a = 1
2 a = a+2
3 print (a)

Numbers Most standard operators for arithmetic are available for numbers.
Addition: A + B
Subtraction: A - B
Multiplication: A * B
Division: A \ B
Exponents: A ** B

Vectors A variety of in-built functions for vector arithmetic are built into Vpython. Note
that these are not included in plain python.
Addition: A + B
Subtraction: A - B
Cross Product: cross(A, B)
Dot Product: dot(A, B)

3 Objects
Vpython has a collection of objects that can be drawn onto a canvas. These can be assigned
to variables as shown in the examples but don’t have to be. An instance of the object will
be generated regardless.
Note that this section is specific to Vpython.
pos will set the position of the object.
axis will set the direction in which the object will point.
radius will set the radius.
color will set the color.
It’s important to note the type of data you need to pass to the objects you create. For
example, you cannot define the position of a sphere with a number. You have to use a
vector.

3.1 Creating a Canvas


In Vpython, a canvas on which every object you will draw, must be created. Declare the
canvas creation at the top of your program before you start creating any objects.
-Declaration: scene = canvas(title=Text, background=color.color, width=Number, height=Number,

3
forward=Vector )
Unlike the following objects, the canvas must be named scene every time. Text is the name
of the program you would like to appear above the canvas (Enclose this in quotation marks),
forward is the position of the camera in the scene, and width and height are measured
in pixels.

3.2 Spheres
-Declaration: sphere(pos=Vector, radius=Number, color=color.color )
e.g.
1 b a l l = s p h e r e ( pos=v e c t o r ( 1 , 2 , 0 ) , r a d i u s =1.5 , c o l o r=c o l o r . g r e e n )

The position vector will set the center of the sphere.

3.3 Arrows
-Declaration: arrow(pos=Vector, axis=Vector, color=color.color )
e.g.
1 p o i n t = arrow ( pos=v e c t o r ( 2 , 1 , 2 ) , a x i s=v e c t o r ( 0 , 1 0 , 0 ) , c o l o r=c o l o r .
orange )

The position vector will set the tail of the arrow and the axis vector will set the direction
of the arrow relative to the tail.

3.4 Cylinders
-Declaration: cylinder(pos=Vector, axis=Vector, radius=Number, color=color.color )
e.g.
1 rod = c y l i n d e r ( pos=v e c t o r ( 0 , 0 , 0 ) , a x i s=v e c t o r ( 1 0 , 0 , 0 ) , c o l o r=c o l o r .
yellow )

The position vector will set the center of one of the circular caps of the cylinder and the
axis vector will point the rest of the cylinder relative to the base.

3.5 Changing Attributes of Objects


If you’ve assigned a variable to an object or reference it indirectly, you are able to change
the properties you defined when you first declared the object.
Object.property = Type defined by property
The property can be any that you defined while creating the object.
e.g. if we’ve created a sphere, we can change its radius accordingly
1 p a r t i c l e = s p h e r e ( pos=v e c t o r ( 1 , 0 , 1 ) , r a d i u s =3 , c o l o r=c o l o r . b l u e )
2 rod . r a d i u s = 2

Note that the radius only takes numbers. If you assigned a vector to the radius instead of
a number, an error would be thrown. The same would occur if you tried to reassign the
position with a number. The position will only take vectors and thus you must make sure
you pass the correct data type.

4
4 Loops
Loops create a means for us to repeat lines of code without having to write them out by
hand. This becomes useful when you wish to perform a task for multiple instances of an
object or if you want to continuously displace one. (Make it appear to move)
Python, unlike other languages, relies on indentation to declare which code lies within the
loop. Every instance of a loop will run code that is beneath it and indented by one tab-length
to the right. The end of the loop is determined by the end of indentation (The following
lines are no longer one indentation to the right of the loop) or the end of the program itself.
For animation the rate(Number ) command will ensure that the loop will run at Number
loops per second.

4.1 While Loops


-Declaration:
while condition:
— Execute Indented Code Until Condition is False
e.g.
1 counter = 1
2 while counter < 5:
3 print ( counter )
4 counter = counter + 1

1
2
3
4

Make sure that the variable used in the condition is being manipulated inside the loop so
that it tends towards a state where the condition is no longer true. If it isn’t then the loop
condition won’t change and will thus loop forever.

4.2 For Loops


*Note: start is optional and defaults to 0
-Declaration:
for i in range(start, stop):
— Execute Indented Code Until i reaches stop
e.g.
1 f o r i in range (3) :
2 print ( i )

0
1
2

5
4.3 Conditions
Conditions make use of comparison operators to take two variables or data types and com-
pare them, yielding either True or False.
Greater than: a > b
Greater than or equal to: a >= b
Less than: a < b
Less than or equal to: a <= b
Equal to: a == b
Not equal to: a ! = b

5 Debugging
When writing code it is important to understand that your code will not run the first time.
Probably not even the first few times. And when it does run, it won’t be as expected. So
it’s important to read the errors python gives you to help understand what went wrong and
where.
Error codes often look scary to beginners so they tend to avert their eyes but it’s important
to learn to read them.
e.g.
Traceback(most recent call last):
File ”errors.py”, line 1, in <module>
NameError: name ’a’ is not defined
This error message occurred because the program tried to use a variable ’a’ in line 1 without
defining it first. And so a NameError was thrown
Error messages change depending on which version of python you use but the basics are
essentially the same.
The following are the different kinds of errors you can get:
• NameError A NameError is raised when a variable that does not exist (yet) is accessed.
• RunTimeError This error is relatively different from the rest. Runtime errors occur
when your code is syntactically correct but does something that eventually leads the
program to crash.
• TypeError Functions in programming languages can usually only take one type of data.
A type error will occur when you’ve passed an incorrect data type to some function.
For example trying to multiply lists together. The operation doesn’t make much sense.
• ValueError A ValueError will occur when invalid values are passed to an in-built func-
tion. This means that the type of value passed was correct but was not within a
specific range of values. E.g. passing negative numbers to a natural log function.
• IndentationError Python relies heavily on indentation to distinguish which block of
code you’re working within. An indentation error occurs when you violate such rules.
E.g. not indenting by a full tab-space when writing loops.

• IndexError An Index Error will occur when you try to access an item that doesn’t exist
through indexing. E.g. if you try to access the (n+1)th element of list n-long.

6
• ZeroDivisionError This will occur if you divide by zero. If you’re writing a program
where this might occur, you should probably use an ’If’ statement to make sure it’s
controlled.
• SyntaxError Syntax errors are raised when your code has been written incorrectly.
This means that you’ve declared something incorrectly or used characters in the wrong
place.
e.g.
Forgetting to include a colon after a loop
File ”errors.py”, line 2
while counter < 2
ˆ
SyntaxError: invalid syntax

5.1 Common Errors


Learning to recognise the errors is only the first step. Learning how to resolve them and
what mistakes you usually made can only be taught by practice. However there are some
common pitfalls.
Python errors will tell you the line where the error occurred. It’s useful to check this but
very often the error will occur on the line before.
Spelling mistakes in variable names are very common. Be sure to check how you spelt your
variable and keep it consistent throughout your program.
Remember to place colons after your if statements and loops. If the editor you’re using
doesn’t automatically indent, you’ve probably forgotten it.
Python, like most programming languages, defaults to American English. This means that
any existing variables or functions will probably have been named using their spelling stan-
dards. e.g. any variable related to colour will be spelt ’color’.
While this guide helps with common errors, if you’re stuck you shouldn’t hesitate to Google
your error. There are many helpful websites that can help with debugging.

5.2 Debugging Techniques


Errors will often only occur on one line (If you’re lucky) so a good way to find your error
is to comment out lines of code one after the other using the ’#’ symbol and running your
code to see if the error still occurs.
Runtime errors are tricky. So the best technique to work around them it to use the ’print’
statement and output the values of your variables at different points throughout the pro-
gram. This means you can see if your variables are storing the values you expect them
to.

6 Examples
6.1 Arithmetic
Create a variable to store the result of a cross product:
1 f i r s t = vector (1 ,2 ,3)
2 second = vector ( 2 , 3 , 4 )

7
3 t h i r d = c r o s s ( f i r s t , second )
4 print ( third )

< −1, 2, −1 >

Output of unstored arithmetic:


1 print (5∗∗2)

25

Finding a unit vector:


1 my vec = v e c t o r ( 5 , 5 , 0 )
2 u n i t v e c = m y v e c t o r / m y v e c t o r . mag
3 print ( unit vec )

< 0.707107, 0.707107, 0 >

6.2 Animation
Make an object move in a straight line
1 time = 0
2 b a l l = s p h e r e ( pos=v e c t o r ( 0 , 0 , 0 ) , r a d i u s =1 , c o l o r=c o l o r . r e d )
3 w h i l e time < 1 0 0 :
4 rate (24)
5 b a l l . pos . x = b a l l . pos . x + 0 . 1
6 time = time+1

In this example the ball is moving at a constant speed and the x position is changing by
a fixed value. Alternatively you could call upon an acceleration or other variables that
manipulate the position of the ball to make the animation more interesting.

6.3 Loops
Making For Loops and While Loops do the same thing
For:
1 f o r i in range (2 ,10) :
2 print ( i )

While:
1 counter = 2
2 while counter < 10:
3 print ( counter )
4 counter = counter + 1

8
Both have the same output:

2
3
4
5
6
7
8
9

Making For loops and While Loops do different things


For:
1 m y l i s t = [ ” Apples ” , ” Bananas ” , ” Coconuts ” ]
2 f o r item i n m y l i s t :
3 p r i n t ( item )

Apples
Bananas
Coconuts

While:
1 s t r i n g = ”a”
2 w h i l e s t r i n g != ” aaaa ” :
3 print ( string )
4 s t r i n g += ” a ”

a
aa
aaa

7 Exercises
7.1 Pythagoras
Part I:
Create a program that, given the length of two sides of a triangle will calculate the length
of the hypotenuse.

Part II:
Create a program that, given the length of two side of a triangle and the specification of
which sides they are, will calculate the length of the other side.

Part III:

9
Create a program that, given the lengths of three sides of a triangle, will determine if the
triangle is Obtuse, Acute, Right Angle, or not a valid triangle.

7.2 Charges
Part I:
Create a program that takes a distance and outputs the force of repulsion exerted on two
electrons separated by that distance.

Part II:
Create a program that takes a distance and the charges of two particles separated by the
distance. And then outputs the force exerted on each particle.

Part III:
Create a program that takes the charge and location from the origin of n particles and
calculates the force exerted on each particle.

7.3 Momentum
Part I:
Create a program that simulates two spheres crashing and bouncing off of each other in a
perfectly elastic collision such that they conserve momentum. Do this in 1 dimension.

Part II:
Create a program, using rods and a sphere, to simulate a ball inside a box bouncing off the
sides.

Part III:
Do the same as Part II but with n balls.

8 Note: Python Outside of Glowscript


Glowscript is technically not python. It’s a version of python designed to make graphics
programming easier and more intuitive. For those who wish to program in Python offline,
you can install the latest version at www.python.org
Python outside of Glowscript is slightly different. It doesn’t automatically support many of
the features Glowscript has, like the ability to easily create shapes and other objects, but
instead has access to a wide library of modules that allow you to do more than what you’re
limited doing in Glowscript. If you want to code with Vpython outside of the Glowscript
environment, you can download the packages and follow tutorials at www.vpython.org/.
Glowscript automatically includes packages that allow you to do things like access mathe-
matical functions. In standard python you have to include these packages yourself.

8.1 Resources
www.learnpython.org
www.codecademy.com
www.docs.python.org/3

10

Você também pode gostar