Python Syntax

From Physics Book
Jump to navigation Jump to search

Eddy Wang - Spring 2021

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. Python has a unique design through its emphasis of code readability by having a notable use of significant indentation.

Python is primarily used for web development, software development, mathematics, and system scripting. Some more things python can do are:

  • Be used on a server to create web applications.
  • Be used along software to create workflow.
  • Connect to database systems to read and modify files.
  • Handle big data and perform complex math operations.
  • Be used for rapid prototyping, otherwise known as production-ready software development.

Python is used over other languages for many various reasons. Its simple syntax allows developers to write programs with fewer lines than some other programming languages. It also runs on an interpreter system, allowing for code to be executed as soon as it is written.

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. It allows its users to create objects such as spheres and cones and displays these objects in another window. 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. The most current version of Python found is Python 3.9.2, which was released on February 19, 2021.

Downloading

The latest stable version of Python 3 available is 3.9.1 (as of February 2021).

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

Syntax

One of the most important components of Python syntax is indentation. Indentation refers to the spaces at the beginning of a line of code, which can also be achieved by using the tab button. While in some programming languages indentation is only used for aesthetic purposes, indentation is necessary for the functionality for code in Python. The number of spaces needed is up to you as the programmer, but it must be at least one. If the indentation is skipped, Python will give the user an error message, and the code will not be able to run. Indentation will come up later in loops such as if-loops and for-loops.

Variables

Variables in Python are named items/containers that allow data to be stored. The variables are only stored during the execution of the program; after the program finishes, the variables are no longer retained. Python is an Object-Oriented Programming (OOP) language, which means that variables can be thought of as "objects" or abstract data types representing various forms of information.

Declaring a Variable

Python has no specific command for declaring a variable. Instead, a variable is created the moment a user assigns a value to it. Variables are assigned with an = (equals) operator. Unlike other programming languages, Python does not require explicit types to be defined when declaring variables. The types are inferred during runtime, as it is an interpreted language. Hence, the only information needed for assignment is the variable name and data to assign. Python variables can have any name, but it must start with a letter or underscore. It's important to note that the underscore is generally reserved for library variables, so it is best to stick with letters. It also can only contain alphanumeric characters and underscores (A-z, 0-9, and _). Here are a few examples of variable assignment:

x = 7
long_variable_name = [0, 1, 2, 3, 4]
CAPITAL_VARIABLE_NAME = {'apple', 'orange', 'banana'}
_starts_with_underscore = {'yes': 1.0, 'no': 0.0}  # Try to avoid this type of naming if possible!

It is possible to assign a new variable to a variable that has already been assigned as well. The new variable will store the information that the original variable was already assigned.

x = 7
reassigned_variable = x  # Final value is 7, because x is 7

Operators

Operators are symbols used to perform mathematical manipulations and operations to data. Some of the simplest mathematical operations include:

# 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 are more complex than these, such as:

# Exponentiation: 
2 ** 2  # This will equal 4

# Remainder: 
5 % 4  # This will equal 1

# Absolute value:
abs(-3)  # This will equal 3

# Square root: 
sqrt(4)  # This will equal 2

# Euler's number:
exp(1)  # This will equal e^1

Another useful category of operators are known as assignment operators, which can be used to perform the specified mathematical operation on a variable, and then store the resulting value back into the variable. In order to use assignment operators, you must specify the variable name, followed by the operator symbol with an = (equals sign), and finally the value. For instance, it is possible to add 3 to the value of x and store it in x again like so:

x = x + 3

However, this statement could be simplified into:

x += 3

This will be frequently used in physics simulation models, as variables often needed to be updated in this format.

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

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.

Another common use case for the print statement is to display a hard-coded string along with a variable. This can be done by casting the variable to a string and "adding" it to the hardcoded string:

s = 'Hello, world #'
number = 3
print(s + str(number) + '!')  # Hello, world #3!

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 only used after if statements, and cannot be used independently. There can be any number of elif statements, but only one if statement. 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. There can also be only one else statement, though it is not required.

Another important issue regarding if and other statements is the code block formatting. Other programming languages tend to use braces for code blocks like this, but in Python it is designated by indentation. This is why it is critical to ensure your program is formatted correctly.

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)

Examples

This is an example of using Python to implement a mathematical model. For the gravitational principle, it is known that the force of gravity is:

[math]\displaystyle{ |F_{G}| = G \frac{M_{1} M_{2}}{R^{2}} }[/math]

We can use this knowledge to create a variable called gravitational_force, and assign it the magnitude of the gravitational force between objects [math]\displaystyle{ M_{1} }[/math] and [math]\displaystyle{ M_{2} }[/math]. Given variables m1, m2, and r, the Python code would be:

gravitational_force = 6.67 * 10 ** -11 * m1 * m2 / (r ** 2)

Normally, in a Python physics model, we would have an outer loop that updates the variables and values for each iteration, which is where an update statement such as this would go. This could be used to determine the variable gravitational force on a skydiver jumping from a great height, as the force would not remain constant. In a finalized GlowScript model, this would look like:

GlowScript Simulation

Connectedness

As a high-level and syntactically simple language, Python is an excellent choice for the development of complex algorithms. Proficient knowledge of Python is critical to implementing machine learning algorithms, an emerging field that many computer science majors are interested in. Python could be used to efficiently employ these algorithms in industries such as stock market analysis, helping to understand trends in the way assets rise and fall.

History

The concept of the Python programming language was developed in the late 1980s. In 1991, Guido van Rossum created the first version of the Python programming language, releasing it with the original intent of code readability (thanks to its use of whitespace and indentation).

In 2000, Python 2 was released which contained several new backwards-incompatible features, such as list comprehension and a garbage collection system.

The first version of Python 3 was released in 2008, while Python 2 was still in use, creating a rift between Python developers on version usage.

Finally, on January 1st, 2020, Python 2 reached its end-of-life date, no longer officially supported by the Python Software Foundation.

See also

  • VPython describes the basics of VPython and using it to create 3D models
  • The GlowScript wiki page provides detailed instructions for how to use VPython on the GlowScript website

Further reading

External links

References