Python Syntax: Difference between revisions

From Physics Book
Jump to navigation Jump to search
No edit summary
Line 17: Line 17:
Alternatively, you can use GlowScript, a virtual environment that allows you to execute VPython code in your browser. You can create an account at [http://www.glowscript.org/ http://www.glowscript.org/]. Although this is useful, keep in mind that not all labs can be completed through GlowScript.
Alternatively, you can use GlowScript, a virtual environment that allows you to execute VPython code in your browser. You can create an account at [http://www.glowscript.org/ http://www.glowscript.org/]. Although this is useful, keep in mind that not all labs can be completed through GlowScript.


==Python Basics==
='''Python Basics'''=
It's always helpful to have a basic background knowledge of Python before proceeding with the applications more relevant to this course. A useful website for Python syntax is www.stackoverflow.com.


    # Comments start with a number symbol. A comment is writing that does not impact the code in any way. These are essential so that both you, or anyone else doesn't get lost in the code and can 
==Variables==
    #easily locate where a bug may be happening. It is encouraged to use these often.


A variable is an item within your code that has information stored in it. This information can be a number, a string of letters, or anything really.
Variables are identified by a name. The names of your variables should be simple, but logical. Avoid names that include spaces or dots, because Python does not like this syntax. Rather, it is best to separate two words in a variable name by capitalizing the second word, such as “myVariable”, or an underscore, such as “my_variable”.
Storing items as a variable allows for easy access when they are needed later in your program.
One last thing that is important to note is that you can reassign variables. For example, the code below is completely valid.
x = 5
x = x + 2
When this code is finished running, x will equal 7. Although this is counterintuitive at first, it’s easy to get used to.


    # Math operations are calculated as follows.
==Comments==
    1 + 1  # -> 2
    2 - 1  # -> 1
    3 * 2  # -> 6
    8 / 4  # -> 4
    (1 + 3) * 2  # -> 8
    1 + (3 * 2)  # -> 7


    # When using an exponent, rather than using the normal "^", be sure to use "**" instead.
Comments are useful when you would like to include something in your code that makes it easier to understand, but it not an actual part of your code. To do this, you include a # sign before anything you would like to comment out. When # is in a line of code, the rest of the code in that line will be ignored when your code is running.
    2 ** 3  # -> 8
myTemp = 4 #This is the temperature in Celsius.


    # There's also various math functions you can use, such as the square root function.
==Math Operations==
    sqrt(4) # -> 2


    # However, these math operations are useless if we don't store the values anywhere. A variable can be any combination of letters or numbers. Try to avoid complicated names, and avoid names include periods or spaces. Storing values to a variable allows for said value to be   
Math operations are simple in Python. The simple operations, as you might expect, are as follows:
    # accessed again in the future easily.
Addition: 1+2 #This will equal 3.
    x = 1 + 1
Subtraction: 2-1 #This will equal 1.
    # Now if you try to access x in the future, it will have the value of '2'.
Multiplication: 2*1 #This will equal 2.
Division: 2/1 #This will equal 2.
There are other operations, that you may want to pay closer attention to.
Exponentiation: 2**2 #This will equal 4.
Square root: sqrt(4) #This will equal 2.
Remainder: 5%4 #This will equal 1.


    # Printing something writes the input in the shell, so that you can see the results of the output. You can print your variables like this:
==Print Function==
    print(x)
    # If you would like to print a collection of letters rather than a variable, put them in quotation marks. Use a comma to separate the information in the quotations from the variable.
    print("The value of x is ", x)


    # Sometimes we only want to execute something based on a certain condition.
In order to see any of the information we’ve listed above, you have to actually print it. For example, the code below will run but will not provide you with an output.
    if x == 2:
x = 1 + 1
        y = 3
Instead, you have to print this information in order to see the answer when the code is finished running. You can do this in two ways. First, you can directly imbed the code in your print statement.
    # The '==' means that you're directly comparing two values. If they're equal, whatever is on the inside of the if-statement will be executed.
print(1 + 1)
    # Now is a good time to note that whitespace is very important in Python.
Or, you can create the variable and then print the variable.
    # 'y = 3' will always execute if it isn't tabbed, so even if x is equal to 7, y will still become 3.
x = 1 + 1
    # If you ever see me use whitespace in this tutorial, make sure you do as well.
print(x)
    # Some other useful comparators: != (not equal), >, >= (greater than or equal to), <, <= (less than or equal to), 'and', 'or', 'not'
Either one is valid!
    # You can add onto the above if-statement by tacking on:
If you would like to print something other than a variable, include quotations around it. For example, if you wanted to print the typical “Hello, world!”, you would code:
    elif x == 3:
print(“Hello, world!”)
        y = 4
The quotations are the important takeaway here.
    else:
        y = 5
    # With elif meaning "else if" for a second possible condition, and "else" for something that you want to execute if none of the earlier conditions are met.


    # You can also have a loop that executes code for a certain amount of time or based on a certain condition. There are two kinds of loops. The first is a while loop that keeps looping
==Conditional==
    # until the terminating condition is met.
A conditional involves an “if” statement. “If this thing is true, do this”, for example. Conditionals are useful in physics if you want to perform different things on a variable, depending on certain conditions.
    while x < 5:
if x > 1:
        print("x is ", x)
print(“x is greater than 1”)
        x = x + 1
elif x = 1:
    # This will output the value of x up until it reaches 4.
print(“x is equal to 1”)
else:
print(“x is less than 1”)
Above is the typical syntax you would see for a conditional. Notice the conditional starts with an if statement, followed by a colon. The next line is indented, and then tells that if statement what to do if the if statement is true. If it is not true, it moves on to the elif statement. Elif statements are used after if statements, but when there is still an if statement involved. There can be endless elif statements. Notice this uses the same syntax as the regular if statement. Lastly, if neither the if nor the elif statement(s) are true, there is an else statement. This will print if nothing above was true.


    # The second type of loop is a for loop. This type of loop sets the amount of loops the program will run before hand.  
==Loop==
   
A loop iterates through each item in a list or range. Loops can be useful in physics because they are vital to update equations. Loops will automatically update the information for you, rather than having to write out the long iterative process yourself. Below are examples of for loops and while loops.
for i in range(1,11):
print(i)
The statement above will print:
1
2
3
4
5
6
7
8
9
10
Notice it does not print 11. When inputting a range in Python, the last number is not included. Notice how the for loop states “for”, and then a variable, and then a range, and then a colon. This is then followed by a statement that tells what to do for each iteration in the loop. Notice is it indented!
while i > 1:
print(i)
This is an example of a while loop. While i is greater than 1, the code will print i. The syntax is similar to the for loop.


Thus concludes our very, very brief foray into Python. That was simply the bare minimum required to understand what will be needed for this class. More concepts will be introduced as needed, whether that be in this tutorial or in a lab. For a more complete understanding of Python, you can look up other Python tutorials elsewhere on the Internet.
==Equal Signs==
 
“=” and “==” mean two different things in Python. When setting a variable equal to something, you use one equal sign:
x = 2
However, when you are using it in something like an if statement, use two equal signs:
if x == 2:
print(“x equals 2)


==VPython Basics==
==VPython Basics==

Revision as of 11:55, 1 November 2018

Claimed by Morgan Powers for Fall 2018

The Main Idea

VPython is an extension of the Python programming language that contains a 3D graphics module called Visual, which allows users to create simple simulations of physics problems. Its primary use is for educational purposes, although it has been used in research before in the past. Although it is slightly different from the actual Python program, it is similar enough for the purpose of this class. Most of the labs done this year will be done using the vPython program.

Downloading vPython

In all cases you will need to have Python 2.7.9 installed. Future versions may also work, but be warned that it may cause VPython to behave erratically.

For Windows

For Mac

For Linux

Note for Linux: You can only install Classic VPython, which is no longer supported and may be missing some features and bug fixes that are present in the current version of VPython.

Alternatively, you can use GlowScript, a virtual environment that allows you to execute VPython code in your browser. You can create an account at http://www.glowscript.org/. Although this is useful, keep in mind that not all labs can be completed through GlowScript.

Python Basics

Variables

A variable is an item within your code that has information stored in it. This information can be a number, a string of letters, or anything really. Variables are identified by a name. The names of your variables should be simple, but logical. Avoid names that include spaces or dots, because Python does not like this syntax. Rather, it is best to separate two words in a variable name by capitalizing the second word, such as “myVariable”, or an underscore, such as “my_variable”. Storing items as a variable allows for easy access when they are needed later in your program. One last thing that is important to note is that you can reassign variables. For example, the code below is completely valid. x = 5 x = x + 2 When this code is finished running, x will equal 7. Although this is counterintuitive at first, it’s easy to get used to.

Comments

Comments are useful when you would like to include something in your code that makes it easier to understand, but it not an actual part of your code. To do this, you include a # sign before anything you would like to comment out. When # is in a line of code, the rest of the code in that line will be ignored when your code is running. myTemp = 4 #This is the temperature in Celsius.

Math Operations

Math operations are simple in Python. The simple operations, as you might expect, are as follows: Addition: 1+2 #This will equal 3. Subtraction: 2-1 #This will equal 1. Multiplication: 2*1 #This will equal 2. Division: 2/1 #This will equal 2. There are other operations, that you may want to pay closer attention to. Exponentiation: 2**2 #This will equal 4. Square root: sqrt(4) #This will equal 2. Remainder: 5%4 #This will equal 1.

Print Function

In order to see any of the information we’ve listed above, you have to actually print it. For example, the code below will run but will not provide you with an output. x = 1 + 1 Instead, you have to print this information in order to see the answer when the code is finished running. You can do this in two ways. First, you can directly imbed the code in your print statement. print(1 + 1) Or, you can create the variable and then print the variable. x = 1 + 1 print(x) Either one is valid! If you would like to print something other than a variable, include quotations around it. For example, if you wanted to print the typical “Hello, world!”, you would code: print(“Hello, world!”) The quotations are the important takeaway here.

Conditional

A conditional involves an “if” statement. “If this thing is true, do this”, for example. Conditionals are useful in physics if you want to perform different things on a variable, depending on certain conditions. if x > 1: print(“x is greater than 1”) elif x = 1: print(“x is equal to 1”) else: print(“x is less than 1”) Above is the typical syntax you would see for a conditional. Notice the conditional starts with an if statement, followed by a colon. The next line is indented, and then tells that if statement what to do if the if statement is true. If it is not true, it moves on to the elif statement. Elif statements are used after if statements, but when there is still an if statement involved. There can be endless elif statements. Notice this uses the same syntax as the regular if statement. Lastly, if neither the if nor the elif statement(s) are true, there is an else statement. This will print if nothing above was true.

Loop

A loop iterates through each item in a list or range. Loops can be useful in physics because they are vital to update equations. Loops will automatically update the information for you, rather than having to write out the long iterative process yourself. Below are examples of for loops and while loops. for i in range(1,11): print(i) The statement above will print: 1 2 3 4 5 6 7 8 9 10 Notice it does not print 11. When inputting a range in Python, the last number is not included. Notice how the for loop states “for”, and then a variable, and then a range, and then a colon. This is then followed by a statement that tells what to do for each iteration in the loop. Notice is it indented! while i > 1: print(i) This is an example of a while loop. While i is greater than 1, the code will print i. The syntax is similar to the for loop.

Equal Signs

“=” and “==” mean two different things in Python. When setting a variable equal to something, you use one equal sign: x = 2 However, when you are using it in something like an if statement, use two equal signs: if x == 2: print(“x equals 2)

VPython Basics

In this section we will analyze some of the objects utilized by VPython. Each object is more or less self-explanatory with equally clear fields within.

    # To begin with, note that every VPython program must begin with these two lines of code:
   from__future__ import division
   from visual import*
   
   # The scene, or visual where you see your code occur, has a width and a height. You can alter them, as seen below.
   scene.width = 1024
   scene.height = 760
   # Beyond that, we have vectors.
   # You can access each component with pos.x, pos.y, or pos.z depending on which component you want.
   # Now would be a good time to mention that you access an object's field with a period following the variable name.
   pos = vector(1, 2, 3)
   xComponent = pos.x  #This value would be 1
   yComponent = pos.y  #This value would be 2
   zComponent = pos.z. #This value would be 3
   # You can add two or more vectors together and you can multiply a vector by a scalar,
   # Adding
   A = vector(1, 2, 3)
   B = vector(4, 5, 6)
   C = A + B  # The value of C is now (5, 7, 9)
   # Multiplying
   D = 5 * C. # The value of D is now (25, 35, 45)
   # but you can't add a scalar to a vector.
   # To get the magnitude of or to normalize a vector, use the appropriate function.
   initialPos = vector(10, 3, 0)
   finalPos = vector(30, 15, 0)
   deltaR = finalPos - initialPos # -> vector(20, 12, 0)
   rMag = mag(finalPos)
   rHat = norm(finalPos)
   errorDemo = magR + finalPos # -> error; causes your program to crash
   # There are a number of different shapes you can create for visual reference in the vPython program. These will be used quite frequently in lab to observe things like momentum, force, etc.
   # If you were to make, say, a ball, you would want to draw a sphere.
   # It has a position field, a radius field, and a color field.
   # When creating a new instance of an object, each field is comma separated.
   # You access each field the same way as we did with the position vector.
   ball = sphere(pos = vector(10, 10, 10), radius = 9e2, color = color.red)
   ballColor = ball.color
   ballPos = ball.pos
   ballRadius = ball.radius
   # You can draw arrows.
   # These also have a color and position field, but instead of a radius, they have an axis that determines their length.
   # These arrows can be used to represent the magnitude of the force or the momentum or anything else the lab asks you to make. 
   velocityArrow = arrow(color = color.blue, pos = vector(-10, -10, -10), axis = velocity * vScale)
   # There are also boxes.
   # They have a position vector and a size vector.
   myBox = box(pos = vector(50, 50, 50), size = vector(20, 15, 12))
   # You can draw helixes, which are useful for depicting springs.
   # They have a position field, a color field, a thickness field, a radius field, and a field for the number of coils.
   spring = helix(pos=ceiling.pos, color=color.cyan, thickness=.003, coils=40, radius=0.015)
   # If you want to trace a moving object, you can have a curve follow it by adding to it every time step. This will show the entire path the object has traveled during the simulation.
   posTrace = curve(color = color.yellow)
   trail.append(ball.pos)
   # You also have the option of making graphs as your program progresses; this is particularly useful for potential vs kinetic energy.
   Kgraph = gcurve(color = color.cyan)
   Ugraph = gcurve(color = color.yellow)
   KplusUgraph = gcurve(color = color.red)
   # For each time step...
   Kgraph.plot(pos = (t, Kenergy))
   Ugraph.plot(pos = (t, Uenergy))
   KplusUgraph.plot(pos = (t, Kenergy + Uenergy))

By updating the fields of whatever objects you decide to use and by using any intermediate variables necessary, you're able to draw and compute what you'll need for this course.