VPython Loops: Difference between revisions

From Physics Book
Jump to navigation Jump to search
Afalis3 (talk | contribs)
No edit summary
 
(72 intermediate revisions by 7 users not shown)
Line 1: Line 1:
Claimed by Alyx Falis
<strong>Krish Katariya, Spring 2026 Editing This Page!</Strong> Please don't remove until wiki resource is graded! For my contribution, I noticed the page didn't really explain why we need to use loops with small time steps for physics, so I explained the importance of loops for motion. I also created a simulation using glowscript+trinket, which highlights the importance of using smaller time steps instead of large ones for the motion of objects. I also added a section explaining how to actually write the loops using syntax, a section on common mistakes one would make when writing loops. I noticed that some of the examples given were using python 2 instead of python 3 syntax (or the syntax was just wrong), so I fixed that and generally improved the other sections as well when I saw fit.


What loops are and how to use them in a VPython Program
An introduction to creating and using loops in VPython.


==The Main Idea==
==The Main Idea==


In programming, loops exist to execute a singular or series of statements for a specified number of times. This simplifies executing any function multiple times. Depending on the type of loop, the functions will know when to be carried out and how many time/for how long it will be carried out.
Loops are generally used in VPython in order to repeat a set of specific instructions without writing the same code many times over and over. The two most common loop structures are the 'for' loop and the 'while' loop. A 'for' loop is usually used when the number of times we need to loop is known, while a 'while' loop is used when code is supposed to repeat until a condition is no longer true.


===While Loop===
===Mathematical Model: Why Loops Work for Motion===


While loops are used to repeat a function until a certain value or criteria is met.
In physics, motion is usually described using continuous equations, such as Newton’s Second Law, which will relate force and momentum with: <pre> dP/dt = Fnet </pre> This equation tells us how momentum changes continuously over time.  


===Examples===
However, in computational modeling, we cannot directly calculate continuous changes easily. To combat this, we instead approximate the process using very tiny time steps (Δt) and updating the values at each step. While this isn't continuous, if our time steps are small enough, we can approximate the process closely enough.  
While loops are very useful in physics for representing time intervals. For example, if you wanted to express that a object was moving over a certain time period you could represent it as such:
<nowiki>
#initial values
ball = sphere(pos=vector(0, 0, 0), radius=1)
time = 0
velocity = 5
#calculations
while time < 100
    time = time+10
    pos = velocity*time </nowiki>
This loop starts with the initial values of position = 0 meters, time = 0 seconds, and velocity = 5 m/s. The loop will run until the time value reaches 100 seconds. Inside the loop, time is first updated so that every iteration of the loop increases the time value (i.e. the first run of the loop time becomes 10 seconds, the second run time becomes 20 seconds, and so on). Next the position is updated using a physics formula: change in distance = velocity * time.


While loops can also be used to create objects in a pattern. For example, if you wanted to create series of spheres in a line you could use the following code:
Using the momentum principle in discrete form, we write:
<nowiki>
#initial values
distance = 0
#calculations
while distance < 100:
    distance = distance + 10
    ball = sphere(pos=(distance,0,0) , radius=1) </nowiki>
This loop will create a ball of the same radius in a line along the x axis every 10 meters. It's possible to alter distances along the y and z axis the same why simply by creating a variable for the y or z part of the vector.
[[File:15-12-05 - balls in circle.png]]


While loops can also be used to create objects in a circular path!
<pre>
<nowiki>
delta P = Fnet * deltat
#initial values
</pre>
theta = 0
#calculations
while theta < 2*pi:
    theta= theta + pi/6
    location = vector(cos(theta),sin(theta),0)
    ball = sphere(pos=(location), radius=0.1) </nowiki>
This code creates a series of 12 spheres in a circle by changing theta each time the loop is iterated. Changing the the increment by which theta is increased (in this case pi/6) you can change the number of spheres that are formed.


===For Loop===
This equation is saying that, during each small time interval (deltat), the momentum of an object changes based on the net force acting on it. After updating the momentum, we then can update position using the kinematics formulas that we are familiar with.


For loops are used to repeat a function a specific number of times.
<pre>
position = position + velocity * deltat
</pre>


Now imagine we want to have many tiny steps over a long time period, writing these equations over and over in VPython would take way too long, which is why glowscript has the concept of loops. A loop allows us to repeatedly run the same lines of code many times, meaning we can  apply these updates many times. Thus, using loops, we are effectively simulating continuous motion using small time steps.


The smaller the value of deltat, the closer this approximation is to real physical behavior. Large time steps can lead to inaccurate results, while very small time steps produce more realistic simulations.


===Interactive Model: Why Time Step Size Matters===


Click this link to see the simulation: https://trinket.io/glowscript/030ca409f33d?outputOnly=true


The embedded GlowScript model below compares falling objects simulated with different values of deltat. A larger deltat updates the motion in bigger jumps, which makes the approximation less accurate.


Be sure to show all steps in your solution and include diagrams whenever possible
A smaller deltat updates the motion more frequently, so the simulated motion stays closer to the exact solution. This shows why loops are useful in VPython: they approximate continuous motion by repeatedly updating momentum and position over small time intervals. This is also why we want to use relatively small values for delta t!
 
===Computational Model: How to Write Loops===
 
A loop repeats a block of code until a condition is no longer true. In Python/VPython, the loop statement ends with a colon, and the repeated lines must be indented underneath it.
 
We write while loops by typing 'while' and entering a mathematical condition after it:
 
<pre>
deltat = 1
t = 0
 
while t < 2:
    t = t + deltat
</pre>
 
In this example, the loop continues as long as t is less than 2. Each time the loop runs, t increases by deltat, so the condition eventually becomes false and the loop stops.
 
A for loop repeats over a set sequence, such as a range of numbers. Use the range(start, end) function to determine what points we iterate over.
 
<pre>
for i in range(0, 5):
    print(i)
</pre>
 
===Common Mistakes When Writing Loops===
 
There are a lot of small mistakes that can happen when writing loops, and hare are some of the more common ones.
 
The most common mistake is forgetting to indent the lines that should be repeated, if you don't do this, the code will not run. If you don't indent all parts of the loop, the un-indented parts will only run once.
 
Another common mistake one might make is forgetting to update the loop variable within the loop itself. For example, in a while loop where we are using time, the variable t must increase inside the loop. If t is never updated, the loop condition will never be satisfied so the loop will run forever.
 
==Examples==
The following examples cover a range of loops that can be created in VPython from the simplest 'for' loops to more complicated 'for' and 'while' loops.


===Simple===
===Simple===
The simplest example is a basic 'for' loop. The following code will print each integer in a range:
<pre>
for i in range(0,10):
    print(i)
</pre>
The same thing can be accomplished with a 'while' loop as well. See the following:
<pre>
i = 0
while i < 10:
    print(i)
    i += 1
</pre>
When modeling momentum updates, using a 'while' loop allows the code to run until Tfinal has been reached by adding deltat to t each time the loop runs.
===Middling===
===Middling===
To solve more complex problems, we need to create values and objects before the loop that will then be updated within the loop until a certain time, t. In the following example, the final position and final velocity of object ball is updated until t = 10 using a time step of deltat = 1.
<pre>
t = 0
deltat = 1
while t < 10:
    Fgrav = vector(0,-ball.m*g,0)
    Fdrag=(.5)*dragCoeff*airDensity*areaBall*mag(ball.p/ball.m)**2*norm(ball.p)
    Fnet = Fgrav - Fdrag
    ball.p = ball.p + Fnet*deltat
    ball.pos = ball.pos + (ball.p/ball.m)*deltat 
    t += deltat
print(ball.pos)    #prints final ball position
print(ball.p/mball)    #prints final ball velocity
</pre>
===Difficult===
===Difficult===
The following code calculates the final position and velocity of a ball attached to a string mounted to a ceiling. After code is written listing the constants, creating the objects, and setting an initial value of t = 0, the following statements update the position and velocity values until t = 10 seconds.


==Connectedness==
<pre>
#How is this topic connected to something that you are interested in?
t = 0
#How is it connected to your major?
deltat = 1
#Is there an interesting industrial application?


==History==
while t < 10: 
    L = ball.pos - ceiling.pos
    s=mag(L) - L0
    Lhat = L/mag(L)
    Fs = -(ks)*s*Lhat
    Fg = vector(0,-g*mball,0)
    Fdrag = (-1)*b*(ball.p/mball)
    Fnet = Fg + Fs + Fdrag
    ball.p = ball.p + Fnet*deltat
    ball.pos = ball.pos + (ball.p/(mball))*deltat
    spring.axis = ball.pos - ceiling.pos
   
    t += deltat


Put this idea in historical context. Give the reader the Who, What, When, Where, and Why.
print(ball.pos)    #prints final ball position
print(ball.p/mball)    #prints final ball velocity
</pre>


== See also ==
==Connectedness==
Understanding the basics of VPython creates a framework for more easily learning to write in coding languages other than Python. Additionally, understanding the basics of the 'for' loop and the 'while' loop enables one to write more complex code using both 'for' and 'while' loops, even nesting both types of loops in creating complex conditionals. In more advanced Physics modeling, being able to write more complex conditional statements enables these more complex equations and relationships to be solved via computational modeling.


Are there related topics or categories in this wiki resource for the curious reader to explore?  How does this topic fit into that context?
Even for non-computing majors, coding experience is a highly valuable trait employers are increasingly looking for in candidates. In 2016, analytics firm Burning Glass reported that programming jobs were growing 12% faster than the market average. Additionally, half of the projected job openings looking for programming experience are in non-technology fields such as 'finance, manufacturing, and healthcare' (4). In 2017, Forbes ranked Python as the top-ranked in-demand coding language among the top five: 'Python, Java, JavaScript, C#, and PHP' (5).


===Further reading===
==History==
Python is an interpreted language that originated in the 1980s and was released from development in the 1990s. Because it is interpreted, compiling is not required to convert lines of code into machine-understandable instructions (6). In 1998, David Scherer saw a need for a better 2D and 3D graphics programming environment and created the idea for Visual (a.k.a. VPython), a Python module (7).


Books, Articles or other print media on this topic
==See Also==


===External links===
===Further Reading===
[http://www.scientificamerican.com/article/bring-science-home-reaction-time/]
'Why Coding Is Still The Most Important Job Skill Of The Future' (Dishman, 2016)
'The Five Most In-Demand Coding Languages' (Kauflin, 2017)
 
===External Links===
http://vpython.org/contents/docs/VisualIntro.html
http://vpython.org/contents/docs/
https://faculty.math.illinois.edu/~gfrancis/illimath/windows/aszgard_mini/pylibs/visual/docs/visual/VisualIntro.html
https://www.fastcompany.com/3060883/why-coding-is-the-job-skill-of-the-future-for-everyone
https://www.forbes.com/sites/jeffkauflin/2017/05/12/the-five-most-in-demand-coding-languages/#6b86011fb3f5
https://en.wikipedia.org/wiki/Python_(programming_language)
https://en.wikipedia.org/wiki/VPython#History




==References==
==References==
 
1. http://vpython.org/contents/docs/VisualIntro.html
This section contains the the references you used while writing this page
2. http://vpython.org/contents/docs/
 
3. https://faculty.math.illinois.edu/~gfrancis/illimath/windows/aszgard_mini/pylibs/visual/docs/visual/VisualIntro.html
[[Category:Which Category did you place this in?]]
4. https://www.fastcompany.com/3060883/why-coding-is-the-job-skill-of-the-future-for-everyone
5. https://www.forbes.com/sites/jeffkauflin/2017/05/12/the-five-most-in-demand-coding-languages/#6b86011fb3f5
6. https://en.wikipedia.org/wiki/Python_(programming_language)
7. https://en.wikipedia.org/wiki/VPython#History

Latest revision as of 18:53, 27 April 2026

Krish Katariya, Spring 2026 Editing This Page! Please don't remove until wiki resource is graded! For my contribution, I noticed the page didn't really explain why we need to use loops with small time steps for physics, so I explained the importance of loops for motion. I also created a simulation using glowscript+trinket, which highlights the importance of using smaller time steps instead of large ones for the motion of objects. I also added a section explaining how to actually write the loops using syntax, a section on common mistakes one would make when writing loops. I noticed that some of the examples given were using python 2 instead of python 3 syntax (or the syntax was just wrong), so I fixed that and generally improved the other sections as well when I saw fit.

An introduction to creating and using loops in VPython.

The Main Idea

Loops are generally used in VPython in order to repeat a set of specific instructions without writing the same code many times over and over. The two most common loop structures are the 'for' loop and the 'while' loop. A 'for' loop is usually used when the number of times we need to loop is known, while a 'while' loop is used when code is supposed to repeat until a condition is no longer true.

Mathematical Model: Why Loops Work for Motion

In physics, motion is usually described using continuous equations, such as Newton’s Second Law, which will relate force and momentum with:

 dP/dt = Fnet 

This equation tells us how momentum changes continuously over time.

However, in computational modeling, we cannot directly calculate continuous changes easily. To combat this, we instead approximate the process using very tiny time steps (Δt) and updating the values at each step. While this isn't continuous, if our time steps are small enough, we can approximate the process closely enough.

Using the momentum principle in discrete form, we write:

delta P = Fnet * deltat

This equation is saying that, during each small time interval (deltat), the momentum of an object changes based on the net force acting on it. After updating the momentum, we then can update position using the kinematics formulas that we are familiar with.

position = position + velocity * deltat

Now imagine we want to have many tiny steps over a long time period, writing these equations over and over in VPython would take way too long, which is why glowscript has the concept of loops. A loop allows us to repeatedly run the same lines of code many times, meaning we can apply these updates many times. Thus, using loops, we are effectively simulating continuous motion using small time steps.

The smaller the value of deltat, the closer this approximation is to real physical behavior. Large time steps can lead to inaccurate results, while very small time steps produce more realistic simulations.

Interactive Model: Why Time Step Size Matters

Click this link to see the simulation: https://trinket.io/glowscript/030ca409f33d?outputOnly=true

The embedded GlowScript model below compares falling objects simulated with different values of deltat. A larger deltat updates the motion in bigger jumps, which makes the approximation less accurate.

A smaller deltat updates the motion more frequently, so the simulated motion stays closer to the exact solution. This shows why loops are useful in VPython: they approximate continuous motion by repeatedly updating momentum and position over small time intervals. This is also why we want to use relatively small values for delta t!

Computational Model: How to Write Loops

A loop repeats a block of code until a condition is no longer true. In Python/VPython, the loop statement ends with a colon, and the repeated lines must be indented underneath it.

We write while loops by typing 'while' and entering a mathematical condition after it:

deltat = 1
t = 0

while t < 2:
    t = t + deltat

In this example, the loop continues as long as t is less than 2. Each time the loop runs, t increases by deltat, so the condition eventually becomes false and the loop stops.

A for loop repeats over a set sequence, such as a range of numbers. Use the range(start, end) function to determine what points we iterate over.

for i in range(0, 5):
    print(i)

Common Mistakes When Writing Loops

There are a lot of small mistakes that can happen when writing loops, and hare are some of the more common ones.

The most common mistake is forgetting to indent the lines that should be repeated, if you don't do this, the code will not run. If you don't indent all parts of the loop, the un-indented parts will only run once.

Another common mistake one might make is forgetting to update the loop variable within the loop itself. For example, in a while loop where we are using time, the variable t must increase inside the loop. If t is never updated, the loop condition will never be satisfied so the loop will run forever.

Examples

The following examples cover a range of loops that can be created in VPython from the simplest 'for' loops to more complicated 'for' and 'while' loops.

Simple

The simplest example is a basic 'for' loop. The following code will print each integer in a range:

for i in range(0,10):
    print(i)

The same thing can be accomplished with a 'while' loop as well. See the following:

i = 0
while i < 10:
    print(i)
    i += 1

When modeling momentum updates, using a 'while' loop allows the code to run until Tfinal has been reached by adding deltat to t each time the loop runs.

Middling

To solve more complex problems, we need to create values and objects before the loop that will then be updated within the loop until a certain time, t. In the following example, the final position and final velocity of object ball is updated until t = 10 using a time step of deltat = 1.

t = 0
deltat = 1

while t < 10:
    Fgrav = vector(0,-ball.m*g,0)
    Fdrag=(.5)*dragCoeff*airDensity*areaBall*mag(ball.p/ball.m)**2*norm(ball.p)
    Fnet = Fgrav - Fdrag

    ball.p = ball.p + Fnet*deltat
    ball.pos = ball.pos + (ball.p/ball.m)*deltat  

    t += deltat

print(ball.pos)    #prints final ball position
print(ball.p/mball)    #prints final ball velocity

Difficult

The following code calculates the final position and velocity of a ball attached to a string mounted to a ceiling. After code is written listing the constants, creating the objects, and setting an initial value of t = 0, the following statements update the position and velocity values until t = 10 seconds.

t = 0
deltat = 1

while t < 10:   
    L = ball.pos - ceiling.pos
    s=mag(L) - L0
    Lhat = L/mag(L)
    Fs = -(ks)*s*Lhat
    Fg = vector(0,-g*mball,0)
    Fdrag = (-1)*b*(ball.p/mball)
    Fnet = Fg + Fs + Fdrag
    ball.p = ball.p + Fnet*deltat
    ball.pos = ball.pos + (ball.p/(mball))*deltat
    spring.axis = ball.pos - ceiling.pos 
    
    t += deltat

print(ball.pos)    #prints final ball position
print(ball.p/mball)    #prints final ball velocity
 

Connectedness

Understanding the basics of VPython creates a framework for more easily learning to write in coding languages other than Python. Additionally, understanding the basics of the 'for' loop and the 'while' loop enables one to write more complex code using both 'for' and 'while' loops, even nesting both types of loops in creating complex conditionals. In more advanced Physics modeling, being able to write more complex conditional statements enables these more complex equations and relationships to be solved via computational modeling.

Even for non-computing majors, coding experience is a highly valuable trait employers are increasingly looking for in candidates. In 2016, analytics firm Burning Glass reported that programming jobs were growing 12% faster than the market average. Additionally, half of the projected job openings looking for programming experience are in non-technology fields such as 'finance, manufacturing, and healthcare' (4). In 2017, Forbes ranked Python as the top-ranked in-demand coding language among the top five: 'Python, Java, JavaScript, C#, and PHP' (5).

History

Python is an interpreted language that originated in the 1980s and was released from development in the 1990s. Because it is interpreted, compiling is not required to convert lines of code into machine-understandable instructions (6). In 1998, David Scherer saw a need for a better 2D and 3D graphics programming environment and created the idea for Visual (a.k.a. VPython), a Python module (7).

See Also

Further Reading

'Why Coding Is Still The Most Important Job Skill Of The Future' (Dishman, 2016) 'The Five Most In-Demand Coding Languages' (Kauflin, 2017)

External Links

http://vpython.org/contents/docs/VisualIntro.html http://vpython.org/contents/docs/ https://faculty.math.illinois.edu/~gfrancis/illimath/windows/aszgard_mini/pylibs/visual/docs/visual/VisualIntro.html https://www.fastcompany.com/3060883/why-coding-is-the-job-skill-of-the-future-for-everyone https://www.forbes.com/sites/jeffkauflin/2017/05/12/the-five-most-in-demand-coding-languages/#6b86011fb3f5 https://en.wikipedia.org/wiki/Python_(programming_language) https://en.wikipedia.org/wiki/VPython#History


References

1. http://vpython.org/contents/docs/VisualIntro.html 2. http://vpython.org/contents/docs/ 3. https://faculty.math.illinois.edu/~gfrancis/illimath/windows/aszgard_mini/pylibs/visual/docs/visual/VisualIntro.html 4. https://www.fastcompany.com/3060883/why-coding-is-the-job-skill-of-the-future-for-everyone 5. https://www.forbes.com/sites/jeffkauflin/2017/05/12/the-five-most-in-demand-coding-languages/#6b86011fb3f5 6. https://en.wikipedia.org/wiki/Python_(programming_language) 7. https://en.wikipedia.org/wiki/VPython#History