Python Reference Guide
Lensyl Urbano, 2021.Variables
Names of the memory locations of specific values. There can be different types. In python, pretty much anything can be a variable.Type | Example | Notes |
---|---|---|
Integer | a = 5 |
Whole number (positive or negative). |
Float | pi = 3.14 |
Number with decimals. |
String | pieType = "apple" |
Letters and text. For special characters (like "α" and "²") search with "utf8" |
List | students = ["Max", "Jace", "Adam", "Thomas"] |
- Start with a letter
- Can have an underscore: e.g.
pie_type
- Often use camel case: e.g.
buildingType
- Not contain spaces or operators like "
+ - / *
" - Avoid weird characters
Comments
If you want to leave a note to yourself that the computer will ignore when running the program, or take out a bit of code temporarily, use a comment.# Comment
A hash-tag at the beginning of a line comments out that line:
# names of students
students = ["Max", "Jace", "Adam", "Thomas"]
# print the name of the first student
print(students[0])
Max
Multi-line
For comments that span multiple lines use three single apostrophies:
''' Make a list of the names of the students
and then print out the first student's name
'''
students = ["Max", "Jace", "Adam", "Thomas"]
print(students[0])
Max
Indentation
Indentation is crucial in python, because the language uses indentation to indicate blocks of code.Indented for
loop
for i in range(5):
print(i)
print("done")
The print(i)
statement on line 2 is in the for loop, while the print("done")
statement is outside the loop, so the result is:
0
1
2
3
4
done
However, if the print("done")
statment was indented, it would be inside the for
loop:
for i in range(5):
print(i)
print("done")
0
done
1
done
2
done
3
done
4
done
Lists
Lists are ways of grouping data. For example:
students = ["Max", "Jace", "Adam", "Thomas"]
Indexing (Finding an item in a List)
Use square brackets and the index (e.g.students[1]
):
students = ["Max", "Jace", "Adam", "Thomas"]
s = students[1]
print("Student 1 is:", s)
to get:
Student 1 is: Jace
because the index starts at zero.
You can index backwards:
students = ["Max", "Jace", "Adam", "Thomas"]
print(students[-2])
gives:
Adam
Slicing Lists
To get a contiguous group of items from a list you can slice:
students = ["Max", "Jace", "Adam", "Thomas"]
print(students[1:3])
gives:
['Jace', 'Adam']
It work like: students[start, stop-1]
For ... in Loop
You can iterate (loop) through a list usingfor ... in ...
:
students = ["Max", "Jace", "Adam", "Thomas"]
for s in students:
print(s)
which gives:
Max
Jace
Adam
Thomas
Strings as Lists
Strings can be treated as lists. So they can be sliced:
t = "This is a string"
print( t[0:10] )
gives:
This is a
They can be looped through using for ... in
loops :
Arrays
Arrays are like lists but only hold one type of data, which allows for more efficient computations. The numpy modules is great for mathematical calculations with arrays.
import numpy as np
a = np.array([2,3,5,3])
print(a*2)
gives:
[ 4 6 10 6]
They can be looped through using for ... in
loops :
Arrays
Arrays are like lists but optimized for efficient mathematically calculations. The cost is that you can only have one type of data (integer, float, logical etc.) in an array.NumPy
numpy is a popular numerical python module. To use it, you have to have it installed on your system, and then import it into your code (numpy is installed with vpython so you may have it already).When we import numpy we give it a shortened name, np to make it easier to type out every time we reference it. This is not required.
import numpy as np
a = np.array([1, 2, 3, 4, 6])
print(2*a)
which generates,
[ 2 4 6 8 12]
Math Operations
Arrays make it easier to do mathematical opperations on the set of values in the array.
Adding 1 to each value in the array.
import numpy as np
a = np.array([1, 2, 3, 4, 6])
print(a + 1)
which generates,
[2 3 4 5 7]
You can add, multiply, divide elementwise with numpy (so multiplication with "*" is not matrix multiplication, you use the dot operator instead).
numpy Functions (uFuncs)
You can also do lot of other functions like sin, cos, exponent (exp), and square roots (sqrt)
Raise each element in the array to the second power (i.e. squaring each number).
import numpy as np
a = np.array([1, 2, 3, 4, 6])
print(np.power(a, 2))
which generates,
[ 1 4 9 16 36]
Loops/Iteration
Use loops to repeat things. You can iterate through a list or string by using afor ... in
loops
for i in range()
To repeat something five times you can use afor
loop with the range
function:
for i in range(5):
print(i)
which generates,
0
1
2
3
4
The numbers generated start at zero by default, and so end at one less than the number specified. For more control you can use the form range(start, stop, step)
:
for i in range(4, 12, 2):
print(i)
to get:
4
6
8
10
i
, you can use any variable name you want in the loop, such as:
for x in range(6, -5, -2):
print(x)
to get:
6
4
2
0
-2
-4
Logic
Useif ... then ... else
statements. In python the "then" is implied.
If/Elif/Then
Choose between options.
x = 5
if x < 10:
print("x is less than 10.")
which generates,
x is less than 10.
Nothing would be printed if x was greater than or equal to 10. So, we can use the else
part of the statement to catch this:
x = 20
if x < 10:
print("x is less than 10.")
else:
print("x is greater than or equal to 10")
to get:
x is greater than or equal to 10
Finally, if we want to catch more than two conditions--say we also want to print when x is equal to 10, we use elif
(short for else if):
x = 10
if x < 10:
print("x is less than 10.")
elif x == 10:
print("x is equal to 10.")
else:
print("x is greater than or equal to 10")
to get:
x is equal to 10
You can have as many elif
statements as you want. Note: for simple choice sets you can also use case
Comparison Operators
Operator | Meaning | Example |
---|---|---|
== |
equal to | x == 10 |
!= |
not equal to | x != 10 |
< |
less than | x < 10 |
<= |
less than or equal to | x <= 10 |
> |
greater than | x >= 10 |
>= |
greater than or equal to | x >= 10 |
Logical Operators (and
/or
/not
)
Use these to combine logical statements.
x = 7
if (x > 0) and (x < 10):
print("x is between 0 and 10.")
to get:
x is between 0 and 10.
Operator | Meaning | Example |
---|---|---|
and |
logical and | if (x > 0) and (x > 10): |
or |
logical or | x != 10 |
not |
less than | if (not (x > 10)): |
Functions
Creating Functions
A function to square a number.
def squared(x):
s = x**2
return s
This function takes x
as a parameter, squares it, and returns the result.
This function is loaded into memory when you run your program. It is not used until you call it in your main program.
Calling a Function
Here we create a function called squared and call it a few times. A function to square a number.
def squared(x):
s = x**2
return s
print( squared(2) )
print( "3 squared is", squared(3))
print( "3² + 4² =", squared(3) + squared(4))
giving:
4
3 squared is 9
3² + 4² = 25
Passing Parameters
You can pass multiple parameters to a function. A function to find the zeros of a quadratic, using the quadratic formula: $$ x = \dfrac{-b \pm \sqrt{b^2-4ac}}{2a} $$
def quadraticFormula(a, b, c):
x1 = (b + (b**2 - (4*a*c))**0.5) / (2*a)
x2 = (b - (b**2 - (4*a*c))**0.5) / (2*a)
return (x1, x2)
print("The zeros for y = x² + 3x - 4 are:", quadraticFormula(1,3,-4))
giving:
The zeros for y = x² + 3x - 4 are: (4.0, -1.0)
Returning Values
You can return multiple values from a function. This can be done as a list, or as a tuple. The function to find the zeros of a quadratic, using the quadratic formula is: $$ x = \dfrac{-b \pm \sqrt{b^2-4ac}}{2a} $$ It returns two values of x (one for the + and one for the -). The values, when returned as a tuple (in parentheses) or list (square brackets) can be unpacked in your main program.
def quadraticFormula(a, b, c):
x1 = (b + (b**2 - (4*a*c))**0.5) / (2*a)
x2 = (b - (b**2 - (4*a*c))**0.5) / (2*a)
return (x1, x2)
# main program
(z1, z2) = quadraticFormula(1, 3, -4)
print("zero 1 =", z1, "and zero 2 = ", z2)
giving:
zero 1 = 4.0 and zero 2 = -1.0
Scope
Variables created within a function only exist within that function. Their scope is local. This way you can have multiple functions reusing the same variable names without causing conflict.
def f1(x):
y = 2 * x + 3
return y
def f2(x):
y = -x + 4
return y
# main program
print(f1(5), f2(3))
Two functions, both recieving values into variables named x, but f1
recieves a 5 while f2
recieves 3.
13 1
Because y
is local to our functions, if we tried to print y
in the main program (line 11 below), we would get an error. So:
def f1(x):
y = 2 * x + 3
return y
def f2(x):
y = -x + 4
return y
# main program
print(f1(5), f2(3))
print(y)
gives the error:
13 1
Traceback (most recent call last):
File "function-examples.py", line 11, in
print(y)
NameError: name 'y' is not defined
Classes
A class to handle straight lines based on the slope-intercept equation: $$ y = m x + b $$
# Create Class: The class' name is "straightLine"
class straightLine:
def __init__(self, m, b): # initialize
self.slope = m # set properties
self.y_intercept = b
self.x_intercept = -b/m
# BEGIN PROGRAM
line_1 = straightLine(2, 3) # create an instance for y = 2x + 3
print("slope =", line_1.slope) # print slope
Defining a Class
Creating the "straightLine" class:
class straightLine:
def __init__(self, m, b): # initialize
self.slope = m # set properties
self.y_intercept = b
self.x_intercept = -b/m
- Line 2: Create class named "straightLine"
- Line 3: An initialization function (always named "__init__").
- The class needs two parameters, a and b, to define the straight line, but functions/methods within a class will almost always require the additional parameter "self", to pass information from one method to the next.
- Line 4-6: Set properties of the class, we'll be able to used these in other methods when we write them (see below).
Using/Instantiating a Class
To use a class you create an instance of it. The term instance is used because you can have multiple instances of a class with different parameters.
# BEGIN PROGRAM
line_1 = straightLine(2, 3) # create an instance for y = 2x + 3
print("slope =", line_1.slope) # print slope
- Line 10: Create an instance of the class. Name the instance "line_1".
- Pass the m and b values.
- Line 11: Use the slope property of this instance of the class (
line_1.slope
) to print the slope.
slope = 2
Adding Methods to a Class
ThestraightLine
class has an initialization method/function (__init__
). Here we add another method called get_y
to get the y value when you pass the program a value for x.
# Create Class: The class' name is "straightLine"
class straightLine:
def __init__(self, m, b): # initialize
self.slope = m # set properties
self.y_intercept = b
self.x_intercept = -b/m
def get_y(self, x):
y = self.slope * x + self.y_intercept
return y
line_1 = straightLine(2, 3) # create an instance for y = 2x + 3
line_2 = straightLine(-1, 4) # create an instance for y = -x + 4
# Get y when x = 5 for line 2
print("For x = 5, y =", line_2.get_y(5))
print()
# get y values for both lines
print("x,y1,y2")
for i in range(5):
print( i, line_1.get_y(i), line_2.get_y(i))
giving:
For x = 5, y = -1
x,y1,y2
0 3 4
1 5 3
2 7 2
3 9 1
4 11 0