Python Syntax: Difference between revisions

From Physics Book
Jump to navigation Jump to search
No edit summary
 
(69 intermediate revisions by 3 users not shown)
Line 1: Line 1:
'''Eddy Wang - Spring 2021'''
'''Berk Tunctan - Spring 2024'''


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


===Python===
===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 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 on 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:
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 on a server to create web applications.
* Be used along software to create workflow.
* Be used alongside software to create a workflow.
* Connect to database systems to read and modify files.
* Connect to database systems to read and modify files.
* Handle big data and perform complex math operations.
* Handle big data and perform complex math operations.
Line 16: Line 16:


===VPython===
===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.
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 the 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.
 
===Glowscript===
GlowScript is a programming environment for making 3D models and simulations using VPython. Unlike traditional desktop applications, GlowScript runs in the web browser, allowing you to write and run your VPython scripts online without needing to install any software on your computer.
 
===Python in Physics===
Python helps with people's understanding of physics concepts and systems through modeling. Python makes it easier for physicists to do calculations with vectors, matrices, and graphs. It is also an easy language that has a fast compiling speed. Creating these computational models help students visualize what is going on in the system. In higher-level physics classes, we will often use python to build computation models for labs and use it to calculate and show concepts such as electric fields, magnetic fields, magnetic forces, and magnet dropping.


==Downloading/Installation==
==Downloading/Installation==
Line 23: Line 29:
Python has two major versions: Python 2 and 3
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.
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 has already migrated away from the dying version. In any case, Python 2.x has significant syntactical differences that Python 3.x is not backward-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 is Python 3.11.3, which was released on October 24, 2022.


===Downloading===
===Downloading===
The latest stable version of Python 3 available is [https://www.python.org/downloads/release/python-390/ 3.9.1] (as of February 2021).
The latest stable version of Python 3 available is [https://www.python.org/downloads/ 3.11.3] (as of April 2023).


Older versions of Python 3 can be found at [https://www.python.org/downloads/ https://www.python.org/downloads/].
Older versions of Python 3 can be found at [https://www.python.org/downloads/ https://www.python.org/downloads/].
Line 48: Line 54:


==Syntax==
==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.
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 of 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. The indentation will be necessary for your if-conditions, for-loops, while-loops, and more.
 
==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 comment 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 quotation marks (single or double), like so:
 
""" this
    is
    a
    multi-line
    comment """
 
""" this is also an example, but on only one line"""
 
'''
this
is also
a
multi-line
comment!
'''
 
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


==Variables==
==Variables==
Line 55: Line 112:


===Declaring a Variable===
===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 <code>=</code> (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 (<code>A-z</code>, <code>0-9</code>, and <code>_</code>). Here are a few examples of variable assignment:
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 <code>=</code> (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 the assignment is the variable name and data to assign. Python variables can have any name, but they 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 (<code>A-z</code>, <code>0-9</code>, and <code>_</code>). Here are a few examples of variable assignments:


  x = 7
  x = 7
Line 65: Line 122:


  x = 7
  x = 7
  reassigned_variable = x  # Final value is 7, because x is 7
  reassigned_variable = x  # Final value of reassigned_variable is 7, because x is 7
 
==Data Types==
Variables can be of different types that determine their behavior.
 
===Numerical Data Types===
Numerical data types represent numbers and can be to perform mathematical calculations.


===Data Types===
'''Integer'''
'''Integer'''


Line 79: Line 141:
'''Float'''
'''Float'''


A float, also known as a "floating point number," is a number that contains one more decimals. A float can be either positive or negative.
A float, also known as a "floating point number," is a number that contains one or more decimal. A float can be either positive or negative.


Examples of floats are:
Examples of floats are:
Line 91: Line 153:
'''Complex'''
'''Complex'''


Complex numbers are numbers that be expressed in the form a + bi, where a and b are real numbers, and i is a symbol representing the imaginary unit. The imaginary unit satisfies the equation <math>i^2=-1</math>. In python, complex numbers are written with a "j" as the imaginary part.
Complex numbers are numbers that be expressed in the form a + bi, where a and b are real numbers, and i is a symbol representing the imaginary unit. The imaginary unit satisfies the equation <math>i^2=-1</math>. In python, complex numbers are written with a "j" to represent the imaginary part.


Examples of complex numbers are:
Examples of complex numbers are:
Line 97: Line 159:
  y = 5j
  y = 5j
  z = -8j
  z = -8j
'''Strings'''
Strings are sequences of characters, including alphabetical characters and numerical ones. They are surrounded by either single quotation marks are double quotation marks. Strings are immutable, meaning that once they are defined, they cannot be changed. Only certain Python methods such as <code>replace()</code>, <code>join()</code>, or <code>split()</code> can modify strings.
Examples of strings are:
a = "hello"
b = 'c'
c = '934'
Note that while the variable c is made up of numbers, it is still a string because of the quotation marks. Because of this, it cannot be used in mathematical operations until it is converted to a numeric type.


'''Boolean'''
'''Boolean'''


Booleans represent one of two values: <code>True</code> or <code>False</code>. In programming, the user often needs to know if a certain expression is True or False. Comparisons are often evaluated to return a Boolean answer. Some examples of comparisons are:
Booleans represent one of two values: <code>True</code> or <code>False</code>. They are a powerful tool to allow the user to control the flow of their code. Comparisons are often evaluated to return a Boolean answer. Some examples of comparisons are:


  10 > 9 # True
  10 > 9 # True
Line 119: Line 170:
Note that <code>==</code> is used when seeing if two integers are the same or not. This is because <code>=</code> is reserved for declaring variables. Be careful to not use <code>=</code> in a comparison.
Note that <code>==</code> is used when seeing if two integers are the same or not. This is because <code>=</code> is reserved for declaring variables. Be careful to not use <code>=</code> in a comparison.


Two types are also never equal to each other, even if they seem to contain the same information within them.
Equivalence in Python is dependent on the value and type of the compared items. The types must correlate for the equivalence to hold true, (i.e., numerical data types must correlate to other numerical data types even if the values appear to be the same).
 
4 == 4 # True
18 == 18.0 # True
 
Comparing elements of different types results in false:
  a = "9"
  a = "9"
  b = 9
  b = 9
   
   
  a == b # False
  a == b # False
Booleans in Python are numerical data types, meaning that they represent numbers. They are special type of integer value and can be used to perform arithmetic operations. <code>True == 1</code> and <code>False == 0</code>.
True + True # 2
True + False # 1
Note that in Python, any data type can be interpreted as a boolean. For example, numerical data types are interpreted as <code>False</code> if they are equivalent to <code>0</code> and true otherwise.
31234 == True # True
0 == True # False
0 == False # True
Collections of data are interpreted as <code>False</code> if they are empty and <code>True</code> otherwise.
[0,1,3,4,5] == True # True
[] == False # True
===Iterable Data Types===
'''String'''
Strings are sequences of characters, including alphabetical characters and numerical ones. They are surrounded by either single, double, or triple quotation marks. Strings are immutable, meaning that once they are defined, they cannot be changed. Only certain Python methods such as <code>replace()</code>, <code>join()</code>, or <code>split()</code> can modify strings.
Examples of strings are:
a = "hello"
b = 'c'
c = '934'
Note that while the variable c appears to be made up of numbers, it is still a string because of the quotation marks. Because of this, it is treated as purely text and does not contain any numerical or mathematical data. Therefore, it cannot be used in mathematical operations until it is converted to a numeric type.
Strings can be indexed <em>see List</em>.


'''List'''
'''List'''


Lists in Python can be used to store multiple items in a single variable. They are created using square brackets and can contain different data types. Lists are mutable, meaning that the user can change, add, and remove items in the list even after it has been created.
Lists in Python can be used to store multiple items in a single variable. They are created using square brackets and can contain different data types. Lists are mutable, meaning that the user can change, add, and remove items in the list even after it has been created. They may contain any data type, including other lists.


Examples of lists are:
Examples of lists are:
  mylist = ["dog", "cat", "bird"]
  my_list = ["dog", "cat", "bird"]
  numberlist = [9, 0, 3, 4]
  number_list = [9, 0, 3, 4]
  mixedlist = ["tree", 2, 0, "frog"]
  mixed_list = ["tree", 2, 0, "frog"]
list_list = [[1,2,3],[4,5,6],[7,8,9]]
 
To access specific elements of the list, Python uses indexing. By indexing into a list, the user can get the data at a specific spot. Note that indexing starts at the number 0, meaning that the first item in the list can only be accessed by using the number 0.
 
my_list[0] # "dog"
number_list[1] # 0
mixed_list[3] # "frog"
list_list[0] # [1,2,3]
 
To access the last element of a list, use <code>-1</code> when indexing.
my_list[-1] # "bird"
number_list[-1] # 4
 
In lists containing lists, you may double index, treating the list as a 2d array. Treat the first index as the row and the second index as the column.
list_list[0][0] # 1
list_list[2][2] # 9
 
Since lists are mutable, they can be updated without having to reassign the list.
 
num_list = []
num_list.append(1)
num_list.append(2)
num_list.append(3)
print(num_list) # [1, 2, 3]


Lists can also be indexed into. By indexing into a list, the user can get the data at a specific spot. Note that indexing starts at the number 0, meaning that the first item in the list can only be accessed by using the number 0.
mylist[0] # "dog"
mylist[1] # "cat"
mylist[2] # "bird"


'''Tuple'''
'''Tuple'''


Like lists, tuples are also used to store multiple items in a single variable. However, unlike lists, tuples are immutable, meaning that they cannot be changed once being created. Tuples are created using curly brackets. A comma is necessary in the creation of a tuple. Therefore, to create one item, you have to add a comma after the item, otherwise Python will not recognize it as a tuple.
Like lists, tuples are also used to store multiple items in a single variable. However, unlike lists, tuples are immutable, meaning that they cannot be changed once created. Tuples are created using parentheses. A comma is necessary in the creation of a tuple. Therefore, to create one item, you have to add a comma after the item, otherwise, Python will not recognize it as a tuple.


Examples of tuples are:
Examples of tuples are:
  thistuple = {"cookies", "cake"}
  my_tuple = ("cookies", "cake", 1912)
  booleantuple = {True, False, True}
  boolean_tuple = (True, False, True)
single_tuple = (5,)


Tuples can also be indexed into like lists.
Tuples can also be indexed into like lists.
===Misc. Data Types===
'''Dictionaries'''
Dictionairies are collections of key-value pairs. Keys are used to access elements, but instead of using numbers, the user may use any value. Each key must be unique and is used to store and retrieve the corresponding value. Dictionaries are mutable, which means that you can add, remove, or modify entries after the dictionary has been created. Dictionaries in Python are written with curly braces, with keys and values separated by a colon.
Examples of dictionaries are:
my_dict = {"name": "Alice", "age": 25}
book_info = {"title": "1984", "author": "George Orwell", "published": 1949}
ball = {"mass": 10, "speed": 40}
You can access the value associated with a specific key using the key name inside square brackets:
my_dict["name"]  # Alice


===Type Conversion===
===Type Conversion===
Line 165: Line 289:
  # convert from string to int:
  # convert from string to int:
  c = int(z)
  c = int(z)
Note that you can only convert strings if they only contain numerical digits.
my_string = "four"
my_num = int(my_string) # ERROR


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


  # Addition:  
  # Addition:  
Line 179: Line 308:
  2 * 1  # This will equal 2
  2 * 1  # This will equal 2
   
   
  # Division:  
  # Division:
  2 / 1  # This will equal 2
  2 / 1  # This will equal 2
 
There are other operations that are more complex than these, such as:
 
  # Exponentiation:  
  # Exponentiation:  
  2 ** 2  # This will equal 4
  2 ** 2  # This will equal 4
Line 189: Line 316:
  # Remainder:  
  # Remainder:  
  5 % 4  # This will equal 1
  5 % 4  # This will equal 1
Methods
   
   
  # Absolute value:
  # Absolute value:
  abs(-3)  # This will equal 3
  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 <code>=</code> (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:
===Assignment Operators===
The equal sign <code>=</code> is used to assign a value to a variable and allows it to be reused. The value on the left is the variable, and one on the right is the value to be assigned to the variable. Operation may be used in the assignment of variables.


  x = x + 3
  x = 3
y = 4
z = y + x # z is 7


However, this statement could be simplified into:
To update a variable, the variable must be reassigned with the <code>=</code> operator. However, the variable itself may be used in the reassignment. This 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 <code>=</code> (equals sign), and finally the value.


  x += 3
  x = x + 3 # adding 3 to x


This will be frequently used in physics simulation models, as variables often needed to be updated in this format.
When using arithmetic operators, for for ease of convience, this statement could be simplified into:


==Comments==
x += 3 # equivalent to x = x + 3


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.
This will be frequently used in physics simulation models, as variables often needed to be updated in this format.


'''Single Line Comments'''
===String Concatenation===
Strings of text can be combined using the <code>+</code> operator.
a = "hello "
b = "world"
c = a + b # combines to "hello world"


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.
Note that text containing numbers will not be added together. Instead, they will be attached.
a = "5"
b = "1"
c = a + b # combines to "51", not "6"


# This is a comment.
===Comparison===
   
Comparing elements in Python uses the <code>==</code> operator.
  a = 4 # and so is this
  x = 1
   
  y = 1
  # b = 4 # and so is this entire line, be careful!
  x == y # outputs True because x equals y
  y == 5 # outputs False because y does not equal 5


Here is an example of comment use that you might see in a lab:
CAUTION: <code>==</code> and <code>=</code> are not interchangeable and using them as such will lead to errors. <code>==</code> is used only for comparison and checking equivalence while <code>=</code> is used only for assignment.


myTemp = 4 #This is the temperature in Celsius.
===Boolean Operators===
Booleans are a data type that represent truth values. Boolean logic is the chaining of truth values can be represented in Python using the <code>and</code> and <code>or</code> operators.


'''Multi-line Comments'''
====and====
The <code>and</code> operator is used to check if all inputted values are <code>True</code>.


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:
True and True # outputs True because both values are true


""" this
If a single input is <code>False</code>, then the entire statement will be <code>False</code>:
    is
    a
    multi-line
    comment
    example """


  """ this is also an example, but on only one line"""
  True and False # False
False and False # False


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).
====or====
The <code>or</code> operator is used to check any inputted value is <code>True</code>.
True or True # True
True or False # True
False or False or False or False or False or True # True


If there is not a single input is <code>True</code>, then the entire statement will be <code>False</code>:
False or False # False


'''Main Uses'''
Boolean Operators can also be used inconditional expressions.


- Longer variable explanation (units, where the data comes from, etc)
x = 1
 
y = 2
- Comment out code (to save for later, instead of deleting it)
(x == 1) and (y == 2) # outputs True because both conditions are true
 
- Instructions
x = 2
 
y = 3
- Notes to self
(x == 1) or (y == 2) # outputs False because neither condition is true


==Print Function==
==Print Function==
Line 257: Line 395:
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.
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
  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.
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 embed the code in your print statement.
  print(1 + 1)
  print(1 + 1)
Or, you can create the variable and then print the variable.
Or, you can create the variable and then print the variable.
Line 265: Line 403:
If you would like to print something other than a variable, include quotations around it. For example, if you wanted to print the typical <code>'Hello, world!'</code>, you would code:
If you would like to print something other than a variable, include quotations around it. For example, if you wanted to print the typical <code>'Hello, world!'</code>, you would code:
  print('Hello, world!')
  print('Hello, world!')
The quotations are the important takeaway here.
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:
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:
Line 272: Line 410:
  number = 3
  number = 3
  print(s + str(number) + '!')  # Hello, world #3!
  print(s + str(number) + '!')  # Hello, world #3!
===Uses===
Printing is incredibly useful in debugging code. If you are getting an unexpected result, it can be quite difficult to tell what is going on as your code is running. With `print()`, it becomes easier to track what the code is doing and what variables equal at various points in the code's execution.


==Conditional==
==Conditional==
===if statement===
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.
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")
===else statement===
If the if condition is <code>False</code>, we can use an <code>else</code> keyword to run code if and only if the if conditional fails.
  if x > 1:
  if x > 1:
  print(“x is greater than 1”)
  print("x is greater than 1")
elif x = 1:
print(“x is equal to 1”)
  else:
  else:
print(“x is less than 1”)
    print("x is NOT greater than 1")
Above is the typical syntax you would see for a conditional. Notice the conditional starts with an <code>if</code> statement, followed by a colon. The next line is indented, and then tells that <code>if</code> statement what to do if the <code>if</code> statement is <code>True</code>. If it is not <code>True</code>, it moves on to the <code>elif</code> statement. <code>elif</code> statements are only used after <code>if</code> statements, and cannot be used independently. There can be any number of <code>elif</code> statements, but only one <code>if</code> statement. Notice this uses the same syntax as the regular if statement. Lastly, if neither the <code>if</code> nor the <code>elif</code> statement(s) are <code>True</code>, there is an <code>else</code> statement. There can also be only one <code>else</code> statement, though it is not required.
 
===elif statement===
To chain multiple conditionals, we can use the <code>elif</code> keyword, (i.e., <em>else if</em>).


Another important issue regarding <code>if</code> 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.
if x > 2:
print("x is greater than 2")
elif x == 1:
    print("x is equal to 1")
elif x == 0:
    print("x is equal to 0")
else:
    print("x is less than 2 and not equal to 1 or 0")
 
Notice the conditional starts with an <code>if</code> statement, followed by a colon. The code inside of the <code>if</code> statement tells the code what to do if the <code>if</code> statement is <code>True</code> and must be indented. If the condition is not met and the if does not equal <code>True</code>, it moves on to the <code>elif</code> statement. <code>elif</code> statements should only used after <code>if</code> statements, and cannot be used independently. There can be any number of <code>elif</code> statements, but only one <code>if</code> statement. Notice this uses the same syntax as the regular if statement. Lastly, if neither the <code>if</code> nor the <code>elif</code> statement(s) are <code>True</code>, there is an <code>else</code> statement. There can also be only one <code>else</code> statement, though it is not required.
 
Another important issue regarding <code>if</code> and other statements is the code block formatting. Code within the conditional block must be indented.


==Loop==
==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. Note that the block of code under a loop must be indented.
Loops are powerful tools that are used to repeated run a block of code without having to rewrite it.  


'''While Loops'''
===While Loops===


A <code>while</code> loop will often be used in physics to update time. With a <code>while</code> loop, a set of statements can be executed as long as the condition is true. For physics, this is often used when time is below a certain point. Within the while loop, time is incremented to mock the passing of time until the while loop is no longer true.
A <code>while</code> loop is similar to a repeated <code>if</code> statement. It repeatedly executes a piece of code until a certain condition no longer holds true. In physics, they are most often used to update an object over a certain amount of time.  


ball.pos.x = 5 # ball's x position
  t = 0
  t = 0
  deltat = 0.1
  deltat = 0.1
x = 1
  while t < 1:
  while t < 1:
     x += 1
     ball.pos.x += 1 # ball's x position increases by 1 every 0.1 seconds
     t += 1
     t += deltat


After this is executed, x will equal 10.
===For Loops===


'''For Loops'''
A <code>for</code> loop is used when iterating over an iterable sequence, such as a list, tuple, or string. When using <code>for</code>, the program iterates through each element of the sequence
 
A <code>for</code> loop is used when iterating over a sequence, such as a list, tuple, or string. When using <code>for</code>, the program iterates through each component of whatever is specified.


To print each component of a list of animals:
To print each component of a list of animals:
  animals = ["dog", "cat", "bird"]
  animals = ["dog", "cat", "bird"]
  for x in animals:
  for animal in animals:
     print(x)
     print(animal)


To print each letter in the word "yellowjackets":
To print each letter in the word "yellowjackets":
  for x in "yellowjackets":
  for character in "yellowjackets":
     print(x)
     print(character)


==Equal Signs==
To print each number in a range from [0, 5):
for i in range(5):
    print(i)


=” and “==” mean two different things in Python. When assigning a variable to a value, you use one equal sign:
===Nested Loops===
  x = 2
A loop may contain loops within them. A loop that contains another loop inside it is called a nested loop. Here is an example of a nested loop:
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:
  students = ["Sam","Joe","Fred"]
  if x == 2:
snacks = ["cookies","chips","candy"]
print(“x equals 2)
for student in students:
    for snack in snacks:
        print(student + " got " + snack)
 
This nested for-loop goes through every element of both of the lists and gives each snack to each student.
 
==Functions==
 
Functions are code blocks that take in an input and execute some code. They help you organize your code and reduce repetition.
 
A simple example of a function is:
  def currentYear():
    print("2022")
currentYear() # This line calls the function to be executed


==Examples==
Functions always start with the <code>def</code> keyword. Once the function is created, it can be reused over and over again. A function must be created before it can be used. An example of that is the print function.
This is an example of using Python to implement a mathematical model.
The example below is a function that takes in the parameters x and y.
For the gravitational principle, it is known that the force of gravity is:
def add(x, y):
    sum = x + y
    print(sum)
This example contains two functions: <code>mult(x, y)</code> and <code>print()</code>


<math>|F_{G}| = G \frac{M_{1} M_{2}}{R^{2}}</math>
====Return Variables====
Functions can be used to output a value using the <code>return</code> keyword. This is the output of the function. This value can then be used elsewhere. One common application is to use the <code>print()</code> function to show what is returned.
def mult(x, y):
    return x * y
product = mult(5, 5)
print(product) # will print 25


We can use this knowledge to create a variable called <code>gravitational_force</code>, and assign it the magnitude of the gravitational force between objects <math>M_{1}</math> and <math>M_{2}</math>. Given variables <code>m1</code>, <code>m2</code>, and <code>r</code>, the Python code would be:
In this example, <code>product</code> stores the return value of the function mult(x, y).


gravitational_force = 6.67 * 10 ** -11 * m1 * m2 / (r ** 2)
==Error Handling==
"Ask for forgiveness, not permission". The try and except statement handles exceptions. Exceptions are errors that happen when you run a program. Sometimes, we want to execute code when an error occurs, and for this, we can use a try and except statement to solve the problems.


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:
===Exceptions===
Python has built-in exceptions such as the <code>FileNotFoundError</code>, <code>ImportError</code>, and <code>ZeroDivisionError</code>, If an exception occurs, one of the exceptions will be thrown. Developers will need to deal with the exceptions thrown or the program will crash. This is when the <code>try-catch</code> block is used.
Here is a sample structure of the <code>try-except</code> block:
try:
    <do something>
except Exception:
    <handle the exception>
<code>try</code>: the code that may have an exceptions. If an exception is raised, this block of code immediately terminates and jumps straight into the except block


[https://trinket.io/embed/glowscript/7615a48c5f?start=result GlowScript Simulation]
<code>except</code>: this block of code executes only if the try block raises an exception. It cannot be on its own and requires a try block before it.
<!--=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.
<code>else</code>: this block is only executed if no exceptions are raised in the try block.


==Starting Your VPython Program==
<code>finally</code>: the code in this block is always executed at the end whether the try block raises an exception or not.
To begin with, note that every VPython program must begin with these two lines of code:
Here is some example 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


==Vectors==
def fail():
You can access each component of the vector with pos.x, pos.y, or pos.z, depending on which component you want. You access an object's field with a period following the variable name.
    1 / 0 # this raises an exception because a number cannot divide by 0
try:
    fail()
except ZeroDivisionError:
    print("cannout divide by 0")
finally:
    print("continue")
The output of this code is as follows:
exception occurred
continue


pos = vector(1, 2, 3)
==Import==
xComponent = pos.x  #This value would be 1
Import is a special keyword in Python that allows us to external libraries into our code. A library is a collection of functions and other components that can be used to extend the functionality of Python. VPython is an example of such external library.  
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. Keep in mind you cannot add a vector and a scalar.
===<code>math</code> module===
The <code>math</code> module is the one of the most commonly used modules in Python development as it allows you to use more complex math equations. Importing the math module is as follows:


  #Adding
  import math
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)


To get the magnitude of or to normalize a vector, use the appropriate function.
Once imported, you can access all of its functions by prefixing them with <code>math.</code>.
Here are some of the most commonly used functions provided by the math module:


  initialPos = vector(10, 3, 0)
  math.sqrt(x): Returns the square root of x.
  finalPos = vector(30, 15, 0)
  math.pow(x, y): Returns x raised to the power of y.
  deltaR = finalPos - initialPos # -> vector(20, 12, 0)
  math.sin(x): Returns the sine of x (x in radians).
  rMag = mag(finalPos)
  math.cos(x): Returns the cosine of x (x in radians).
  rHat = norm(finalPos)
  math.factorial(x): Returns the factorial of x.
  errorDemo = magR + finalPos # -> error; causes your program to crash
  math.log(x, base]): Returns the logarithm of x to the given base, uses the natural logarithm if no base is specified.
math.pi: The mathematical constant π.
math.e: The mathematical constant e, which is the base of natural logarithms.


==Shapes==
Here’s a simple example demonstrating how to use some functions from the math module:


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.
import math
  ball = sphere(pos = vector(10, 10, 10), radius = 9e2, color = color.red)
  ballColor = ball.color
# Calculate the square root
  ballPos = ball.pos
print("Square root of 16 is:", math.sqrt(16))
  ballRadius = ball.radius
# Calculate power
print("3 raised to the power of 4 is:", math.pow(3, 4))
# Trigonometric functions
angle = math.pi / 4  # 45 degrees in radians
print("Cosine of 45 degrees is:", math.cos(angle))
print("Sine of 45 degrees is:", math.sin(angle))
# Logarithm
print("Natural logarithm of 10 is:", math.log(10))
  print("Logarithm base 10 of 100 is:", math.log(100, 10))
   
  # Constants
print("Mathematical constant pi:", math.pi)
  print("Mathematical constant e:", math.e)


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.
==Examples==
myBox = box(pos = vector(50, 50, 50), size = vector(20, 15, 12))
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:


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.
<math>|F_{G}| = G \frac{M_{1} M_{2}}{R^{2}}</math>
spring = helix(pos=ceiling.pos, color=color.cyan, thickness=.003, coils=40, radius=0.015)


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


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.
  gravitational_force = 6.67 * 10 ** -11 * m1 * m2 / (r ** 2)
  posTrace = curve(color = color.yellow)
trail.append(ball.pos)


==Graphs==
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 this:


You also have the option of making graphs as your program progresses; this is particularly useful for potential vs kinetic energy.
[https://trinket.io/embed/glowscript/7615a48c5f?start=result GlowScript Simulation]
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.-->


==Connectedness==
=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.
As a high-level and syntactically simple language, Python is an excellent choice for the development of complex systems. Proficient knowledge of Python is critical to implementing scientific models, machine learning algorithms, and much more.


==History==
=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).
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).


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


==See also==
=See also=
* [http://www.physicsbook.gatech.edu/VPython VPython] describes the basics of VPython and using it to create 3D models
* [http://www.physicsbook.gatech.edu/VPython VPython] describes the basics of VPython and using it to create 3D models
* The [http://www.physicsbook.gatech.edu/GlowScript GlowScript] wiki page provides detailed instructions for how to use VPython on the GlowScript website
* The [http://www.physicsbook.gatech.edu/GlowScript GlowScript] wiki page provides detailed instructions for how to use VPython on the GlowScript website


===Further reading===
==Further reading==
* These [https://wiki.python.org/moin/IntroductoryBooks Introductory Books] are a great resource for beginners looking to learn Python
* These [https://wiki.python.org/moin/IntroductoryBooks Introductory Books] are a great resource for beginners looking to learn Python
* [https://www.freecodecamp.org/news/what-can-you-do-with-python-the-3-main-applications-518db9a68a78/ What exactly can you do with Python? Here are Python's 3 main applications]: This article provides several examples of industry applications of Python
* [https://www.freecodecamp.org/news/what-can-you-do-with-python-the-3-main-applications-518db9a68a78/ What exactly can you do with Python? Here are Python's 3 main applications]: This article provides several examples of industry applications of Python
* [https://towardsdatascience.com/how-to-build-your-own-neural-network-from-scratch-in-python-68998a08e4f6 How to build your own Neural Network from scratch in Python] gives a comprehensive guide on applying Python to machine learning
* [https://towardsdatascience.com/how-to-build-your-own-neural-network-from-scratch-in-python-68998a08e4f6 How to build your own Neural Network from scratch in Python] gives a comprehensive guide on applying Python to machine learning


===External links===
==External links==
* For a more comprehensive guide with getting Python set up, go to [https://www.python.org/about/gettingstarted/ https://www.python.org/about/gettingstarted/]
* For a more comprehensive guide with getting Python set up, go to [https://www.python.org/about/gettingstarted/ https://www.python.org/about/gettingstarted/]
* The [https://pypi.org/ Python Package Index] (PyPI) is a repository of community-created Python software packages that can be easily installed and used with Python code
* The [https://pypi.org/ Python Package Index] (PyPI) is a repository of community-created Python software packages that can be easily installed and used with Python code
Line 441: Line 632:
* [https://www.geeksforgeeks.org/history-of-python/ https://www.geeksforgeeks.org/history-of-python/]
* [https://www.geeksforgeeks.org/history-of-python/ https://www.geeksforgeeks.org/history-of-python/]
* [https://docs.python.org/3/tutorial/ https://docs.python.org/3/tutorial/]
* [https://docs.python.org/3/tutorial/ https://docs.python.org/3/tutorial/]
*[https://pythonbasics.org/ https://pythonbasics.org/]
*[http://websites.umich.edu/~mejn/cp/chapters/programming.pdf http://websites.umich.edu/~mejn/cp/chapters/programming.pdf]

Latest revision as of 13:06, 20 April 2024

Berk Tunctan - Spring 2024

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 on 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 alongside software to create a 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 the 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.

Glowscript

GlowScript is a programming environment for making 3D models and simulations using VPython. Unlike traditional desktop applications, GlowScript runs in the web browser, allowing you to write and run your VPython scripts online without needing to install any software on your computer.

Python in Physics

Python helps with people's understanding of physics concepts and systems through modeling. Python makes it easier for physicists to do calculations with vectors, matrices, and graphs. It is also an easy language that has a fast compiling speed. Creating these computational models help students visualize what is going on in the system. In higher-level physics classes, we will often use python to build computation models for labs and use it to calculate and show concepts such as electric fields, magnetic fields, magnetic forces, and magnet dropping.

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 has already migrated away from the dying version. In any case, Python 2.x has significant syntactical differences that Python 3.x is not backward-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 is Python 3.11.3, which was released on October 24, 2022.

Downloading

The latest stable version of Python 3 available is 3.11.3 (as of April 2023).

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 of 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. The indentation will be necessary for your if-conditions, for-loops, while-loops, and more.

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 comment 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 quotation marks (single or double), like so:

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

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

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 the assignment is the variable name and data to assign. Python variables can have any name, but they 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 assignments:

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 of reassigned_variable is 7, because x is 7

Data Types

Variables can be of different types that determine their behavior.

Numerical Data Types

Numerical data types represent numbers and can be to perform mathematical calculations.

Integer

An integer is a whole number. It can be positive or negative but cannot contain any decimals. Integers have unlimited length.

Examples of integers are:

x = 1
y = 3452374791834
z = -289

Float

A float, also known as a "floating point number," is a number that contains one or more decimal. A float can be either positive or negative.

Examples of floats are:

w = 24e4
x = 10.2
y = 1.0
z = -23.9

Note that a whole number can be made a float by adding a .0 at the end of the number. Floats can also be scientific numbers with an "e" to indicate a power of 10.

Complex

Complex numbers are numbers that be expressed in the form a + bi, where a and b are real numbers, and i is a symbol representing the imaginary unit. The imaginary unit satisfies the equation [math]\displaystyle{ i^2=-1 }[/math]. In python, complex numbers are written with a "j" to represent the imaginary part.

Examples of complex numbers are:

x = 3+5j
y = 5j
z = -8j

Boolean

Booleans represent one of two values: True or False. They are a powerful tool to allow the user to control the flow of their code. Comparisons are often evaluated to return a Boolean answer. Some examples of comparisons are:

10 > 9 # True
10 == 9 # False
10 < 9 # False

Note that == is used when seeing if two integers are the same or not. This is because = is reserved for declaring variables. Be careful to not use = in a comparison.

Equivalence in Python is dependent on the value and type of the compared items. The types must correlate for the equivalence to hold true, (i.e., numerical data types must correlate to other numerical data types even if the values appear to be the same).

4 == 4 # True
18 == 18.0 # True 

Comparing elements of different types results in false:

a = "9"
b = 9

a == b # False

Booleans in Python are numerical data types, meaning that they represent numbers. They are special type of integer value and can be used to perform arithmetic operations. True == 1 and False == 0.

True + True # 2
True + False # 1

Note that in Python, any data type can be interpreted as a boolean. For example, numerical data types are interpreted as False if they are equivalent to 0 and true otherwise.

31234 == True # True
0 == True # False
0 == False # True

Collections of data are interpreted as False if they are empty and True otherwise.

[0,1,3,4,5] == True # True
[] == False # True

Iterable Data Types

String

Strings are sequences of characters, including alphabetical characters and numerical ones. They are surrounded by either single, double, or triple quotation marks. Strings are immutable, meaning that once they are defined, they cannot be changed. Only certain Python methods such as replace(), join(), or split() can modify strings.

Examples of strings are:

a = "hello"
b = 'c'
c = '934'

Note that while the variable c appears to be made up of numbers, it is still a string because of the quotation marks. Because of this, it is treated as purely text and does not contain any numerical or mathematical data. Therefore, it cannot be used in mathematical operations until it is converted to a numeric type.

Strings can be indexed see List.

List

Lists in Python can be used to store multiple items in a single variable. They are created using square brackets and can contain different data types. Lists are mutable, meaning that the user can change, add, and remove items in the list even after it has been created. They may contain any data type, including other lists.

Examples of lists are:

my_list = ["dog", "cat", "bird"]
number_list = [9, 0, 3, 4]
mixed_list = ["tree", 2, 0, "frog"]
list_list = [[1,2,3],[4,5,6],[7,8,9]]

To access specific elements of the list, Python uses indexing. By indexing into a list, the user can get the data at a specific spot. Note that indexing starts at the number 0, meaning that the first item in the list can only be accessed by using the number 0.

my_list[0] # "dog"
number_list[1] # 0
mixed_list[3] # "frog"
list_list[0] # [1,2,3]

To access the last element of a list, use -1 when indexing.

my_list[-1] # "bird"
number_list[-1] # 4

In lists containing lists, you may double index, treating the list as a 2d array. Treat the first index as the row and the second index as the column.

list_list[0][0] # 1
list_list[2][2] # 9

Since lists are mutable, they can be updated without having to reassign the list.

num_list = []
num_list.append(1)
num_list.append(2)
num_list.append(3)
print(num_list) # [1, 2, 3]


Tuple

Like lists, tuples are also used to store multiple items in a single variable. However, unlike lists, tuples are immutable, meaning that they cannot be changed once created. Tuples are created using parentheses. A comma is necessary in the creation of a tuple. Therefore, to create one item, you have to add a comma after the item, otherwise, Python will not recognize it as a tuple.

Examples of tuples are:

my_tuple = ("cookies", "cake", 1912)
boolean_tuple = (True, False, True)
single_tuple = (5,)

Tuples can also be indexed into like lists.

Misc. Data Types

Dictionaries

Dictionairies are collections of key-value pairs. Keys are used to access elements, but instead of using numbers, the user may use any value. Each key must be unique and is used to store and retrieve the corresponding value. Dictionaries are mutable, which means that you can add, remove, or modify entries after the dictionary has been created. Dictionaries in Python are written with curly braces, with keys and values separated by a colon.

Examples of dictionaries are:

my_dict = {"name": "Alice", "age": 25}
book_info = {"title": "1984", "author": "George Orwell", "published": 1949}
ball = {"mass": 10, "speed": 40}

You can access the value associated with a specific key using the key name inside square brackets:

my_dict["name"]  # Alice

Type Conversion

Some data types in Python can be converted from one type into another with certain methods. It's important to use the same type when using operations in Python. Only numeric data types can be used in mathematical operations. It is possible to convert a string into a number data type with type conversion.

To convert from one type into another, use int() or float() methods.

x = 3 # int
y = 2.9 # float
z = "4" # string

# convert from int to float:
a = float(x)

# convert from float to int:
b = int(y)

# convert from string to int:
c = int(z)

Note that you can only convert strings if they only contain numerical digits.

my_string = "four"
my_num = int(my_string) # ERROR

Operators

Operators are symbols used to transform data.

Arithmetic Operators

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

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

# Remainder: 
5 % 4  # This will equal 1

Methods

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

Assignment Operators

The equal sign = is used to assign a value to a variable and allows it to be reused. The value on the left is the variable, and one on the right is the value to be assigned to the variable. Operation may be used in the assignment of variables.

x = 3
y = 4
z = y + x # z is 7

To update a variable, the variable must be reassigned with the = operator. However, the variable itself may be used in the reassignment. This 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.

x = x + 3 # adding 3 to x

When using arithmetic operators, for for ease of convience, this statement could be simplified into:

x += 3 # equivalent to x = x + 3

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

String Concatenation

Strings of text can be combined using the + operator. a = "hello " b = "world" c = a + b # combines to "hello world"

Note that text containing numbers will not be added together. Instead, they will be attached. a = "5" b = "1" c = a + b # combines to "51", not "6"

Comparison

Comparing elements in Python uses the == operator.

x = 1
y = 1
x == y # outputs True because x equals y
y == 5 # outputs False because y does not equal 5

CAUTION: == and = are not interchangeable and using them as such will lead to errors. == is used only for comparison and checking equivalence while = is used only for assignment.

Boolean Operators

Booleans are a data type that represent truth values. Boolean logic is the chaining of truth values can be represented in Python using the and and or operators.

and

The and operator is used to check if all inputted values are True.

True and True # outputs True because both values are true

If a single input is False, then the entire statement will be False:

True and False # False
False and False # False

or

The or operator is used to check any inputted value is True.

True or True # True
True or False # True
False or False or False or False or False or True # True

If there is not a single input is True, then the entire statement will be False:

False or False # False

Boolean Operators can also be used inconditional expressions.

x = 1
y = 2
(x == 1) and (y == 2) # outputs True because both conditions are true

x = 2
y = 3
(x == 1) or (y == 2) # outputs False because neither condition is true

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 embed 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!

Uses

Printing is incredibly useful in debugging code. If you are getting an unexpected result, it can be quite difficult to tell what is going on as your code is running. With `print()`, it becomes easier to track what the code is doing and what variables equal at various points in the code's execution.

Conditional

if statement

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")

else statement

If the if condition is False, we can use an else keyword to run code if and only if the if conditional fails.

if x > 1:
	print("x is greater than 1")
else:
   print("x is NOT greater than 1")

elif statement

To chain multiple conditionals, we can use the elif keyword, (i.e., else if).

if x > 2:
	print("x is greater than 2")
elif x == 1:
   print("x is equal to 1")
elif x == 0:
   print("x is equal to 0")
else:
   print("x is less than 2 and not equal to 1 or 0")

Notice the conditional starts with an if statement, followed by a colon. The code inside of the if statement tells the code what to do if the if statement is True and must be indented. If the condition is not met and the if does not equal True, it moves on to the elif statement. elif statements should 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. Code within the conditional block must be indented.

Loop

Loops are powerful tools that are used to repeated run a block of code without having to rewrite it.

While Loops

A while loop is similar to a repeated if statement. It repeatedly executes a piece of code until a certain condition no longer holds true. In physics, they are most often used to update an object over a certain amount of time.

ball.pos.x = 5 # ball's x position
t = 0
deltat = 0.1
while t < 1:
    ball.pos.x += 1 # ball's x position increases by 1 every 0.1 seconds
    t += deltat

For Loops

A for loop is used when iterating over an iterable sequence, such as a list, tuple, or string. When using for, the program iterates through each element of the sequence

To print each component of a list of animals:

animals = ["dog", "cat", "bird"]
for animal in animals:
    print(animal)

To print each letter in the word "yellowjackets":

for character in "yellowjackets":
    print(character)

To print each number in a range from [0, 5):

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

Nested Loops

A loop may contain loops within them. A loop that contains another loop inside it is called a nested loop. Here is an example of a nested loop:

students = ["Sam","Joe","Fred"]
snacks = ["cookies","chips","candy"]

for student in students:
    for snack in snacks:
        print(student + " got " + snack)

This nested for-loop goes through every element of both of the lists and gives each snack to each student.

Functions

Functions are code blocks that take in an input and execute some code. They help you organize your code and reduce repetition.

A simple example of a function is:

def currentYear():
    print("2022")
currentYear() # This line calls the function to be executed

Functions always start with the def keyword. Once the function is created, it can be reused over and over again. A function must be created before it can be used. An example of that is the print function. The example below is a function that takes in the parameters x and y.

def add(x, y):
   sum = x + y
   print(sum)

This example contains two functions: mult(x, y) and print()

Return Variables

Functions can be used to output a value using the return keyword. This is the output of the function. This value can then be used elsewhere. One common application is to use the print() function to show what is returned.

def mult(x, y):
   return x * y
product = mult(5, 5)
print(product) # will print 25

In this example, product stores the return value of the function mult(x, y).

Error Handling

"Ask for forgiveness, not permission". The try and except statement handles exceptions. Exceptions are errors that happen when you run a program. Sometimes, we want to execute code when an error occurs, and for this, we can use a try and except statement to solve the problems.

Exceptions

Python has built-in exceptions such as the FileNotFoundError, ImportError, and ZeroDivisionError, If an exception occurs, one of the exceptions will be thrown. Developers will need to deal with the exceptions thrown or the program will crash. This is when the try-catch block is used. Here is a sample structure of the try-except block:

try:
    <do something>
except Exception:
    <handle the exception>

try: the code that may have an exceptions. If an exception is raised, this block of code immediately terminates and jumps straight into the except block

except: this block of code executes only if the try block raises an exception. It cannot be on its own and requires a try block before it.

else: this block is only executed if no exceptions are raised in the try block.

finally: the code in this block is always executed at the end whether the try block raises an exception or not. Here is some example code:

def fail():
    1 / 0 # this raises an exception because a number cannot divide by 0
try:
    fail()
except ZeroDivisionError:
    print("cannout divide by 0")
finally:
    print("continue")

The output of this code is as follows:

exception occurred
continue

Import

Import is a special keyword in Python that allows us to external libraries into our code. A library is a collection of functions and other components that can be used to extend the functionality of Python. VPython is an example of such external library.

math module

The math module is the one of the most commonly used modules in Python development as it allows you to use more complex math equations. Importing the math module is as follows:

import math

Once imported, you can access all of its functions by prefixing them with math.. Here are some of the most commonly used functions provided by the math module:

math.sqrt(x): Returns the square root of x.
math.pow(x, y): Returns x raised to the power of y. 
math.sin(x): Returns the sine of x (x in radians).
math.cos(x): Returns the cosine of x (x in radians).
math.factorial(x): Returns the factorial of x.
math.log(x, base]): Returns the logarithm of x to the given base, uses the natural logarithm if no base is specified.
math.pi: The mathematical constant π.
math.e: The mathematical constant e, which is the base of natural logarithms.

Here’s a simple example demonstrating how to use some functions from the math module:

import math

# Calculate the square root
print("Square root of 16 is:", math.sqrt(16))

# Calculate power
print("3 raised to the power of 4 is:", math.pow(3, 4))

# Trigonometric functions
angle = math.pi / 4  # 45 degrees in radians
print("Cosine of 45 degrees is:", math.cos(angle))
print("Sine of 45 degrees is:", math.sin(angle))

# Logarithm
print("Natural logarithm of 10 is:", math.log(10))
print("Logarithm base 10 of 100 is:", math.log(100, 10))

# Constants
print("Mathematical constant pi:", math.pi)
print("Mathematical constant e:", math.e)


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 this:

GlowScript Simulation


Connectedness

As a high-level and syntactically simple language, Python is an excellent choice for the development of complex systems. Proficient knowledge of Python is critical to implementing scientific models, machine learning algorithms, and much more.

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