Python Syntax: Difference between revisions

From Physics Book
Jump to navigation Jump to search
(Added description of the Python programming language, and updated the description of VPython. Also deleted the downloading section for VPython and replaced it with instructions for Python 3 installation.)
(Hid VPython Basics, as it has been migrated to another article)
Line 170: Line 170:
  print(“x equals 2)
  print(“x equals 2)


=VPython Basics=
<!--=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.
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.
Line 244: Line 244:
  KplusUgraph.plot(pos = (t, Kenergy + 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.
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.-->

Revision as of 18:29, 14 November 2020

Claimed by Ashish D'Souza for Fall 2020

The Main Idea

Python

Python is an interpreted, high-level programming language. As a general-purpose language, it is used for a variety of applications, which makes it an obvious choice for computational physics models, considering its shallow learning curve and syntactically simplistic features. It is also OS-independent, allowing it to be run on virtually any machine.

VPython

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 VPython slightly differs from the actual Python programming language, the majority of functionality remains the same, including all syntax. For the sole purpose of this class, however, it is functionally equivalent to Python, which is why it is imperative to understand the underlying Python language. Most of the labs done this year (which includes any labs requiring the construction of a physics simulation model) will be done using the VPython.

Downloading/Installation

Versions

Python has two major versions: Python 2 and 3

However, on January 1st, 2020, version 2.x was officially deprecated and no longer officially supported by the Python Foundation. As a result, the majority of the Python community have already migrated away from the dying version. In any case, Python 2.x has significant syntactical differences that Python 3.x is not backwards-compatible with (hence, the major version change), which is why this course will be attempting to adhere to the guidelines set by Python 3.

Downloading

The latest stable version of Python 3 available is 3.9.0 (as of November 2020).

Older versions of Python 3 can be found at https://www.python.org/downloads/.

For the purposes of this class, it is not necessary to download and install VPython, as we will be working with VPython through the virtual GlowScript environment.


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 want to include a note or a quick explanation in your code that will make it easier to understand later. Comments are sections of code that the computer will skip in execution, so it will not actually be executed when your program runs. There are two types of comments that Python uses, single line comments and multi-line comments.

Single Line Comments

To create a single line comment (the most common comments in Python) type a hash character (#) at the beginning of anything you would like to comment out. Note, when "#" is in a line of code, the rest of the code following the # will be ignored by the computer when your code runs.

# This is a comment.

a = 4 # and so is this

# b = 4 # and so is this entire line, be careful!

Here is an example of comment use that you might see in a lab:

myTemp = 4 #This is the temperature in Celsius.

Multi-line Comments

To create a multi-line comment (usually reserved for longer explanations or instructions that cannot fit on one line) type three opening and closing quotation marks, like so:

""" this 
    is
    a
    multi-line
    comment 
    example """
""" this is also an example, but on only one line"""

Be careful! Unlike the single line comments, multi-line comments require a start and a stop (if you forget to close your comment or forget the third quotation mark then that will cause an error in your code).


Main Uses

- Longer variable explanation (units, where the data comes from, etc)

- Comment out code (to save for later, instead of deleting it)

- Instructions

- Notes to self

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 it is 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 assigning a variable to a value, you use one equal sign:

x = 2

However, when you are using it to check if something is equal to another thing (i.e. in an if statement), you use two equal signs:

if x == 2:
	print(“x equals 2)