PART I: Basic Python Programming Flashcards
What are the different types of basic operations we can do?
Addition
Subtraction
Multiplication
Division
Raising x to the power of y (**)
Integer division rounded down to the nearest integer (//)
Modulo (remainder after x is divided by y) (%)
What are modifiers?
Useful tricks that allow you to make changes to a variable
What are some examples of modifiers?
x += 1, x -=1, etc
We can also assign multiple variables with values in a single statement
x,y,z = 1,2,3 gives x=1, y=2, z=3
x,y = 2*8-14, 5/(3**2)
What are the common functions in the math package?
Exponential and logarithmic (log, log10, exp)
Trig (sin, cos, tan, asin, sinh, etc)
Other functions (sqrt)
What is a module?
A sub-package
What’s an example of a module and how do you call it?
Linalg
from numpy.linalg import fncname
What should pseudo code look like?
Keep the same structure as code
Lists
- stores comma separated values enclosed by square brackets
- elements can be of any variable type
- we can append/delete values as required
Arrays
- stores a fixed number of elements, so we can’t append/delete elements
- elements must be of the same variable type
- can be multi-dimensional
- we can do arithmetic with them
What special operations can we do with lists?
Sum: returns sum of elements if same type
Max: returns max value
Min: returns min value
Len: returns # of elements
List(map(operation,r)): applies arithmetic operation to all elements of list
Loadtxt(“file_name.txt”,float): loads values from text file to list
How do we create an array?
- numpy package
- use sin, esp, etc from numpy bc it works on arrays rather than scalars
- zeros: array of all zeros
- ones: array of all ones
- empty: arbitrary initial values
- array: converts list into array
- array([[],[]],type) to create an array
What special operations can we do with arrays?
Size: gives number of elements in array
Shape: gives rows x columns
Slicing
R is list
R[m:n] gives list of values from m inclusive to n exclusive
A is array
A[2:4,3:6] gives 2D array of size 2x3 of values from A[2,3] up to and not including A[4,6]
: refers to whole row or column
R[:] gives whole list
A[:,1] gives values in 2nd column
What’s the syntax required to create a user defined function?
def function_name(p1, p2, ...): (Indent all the below lines) Need to return a value Don't need to return if it has that built in (like print or smth)
What is a local variable?
A variable that exists only within a user defined function
It won’t affect values on the outside