Interpreters and Compilers
Interpreters and Compilers
A language is high-level if the program must be processed before it can run, and
low-level if the computer can execute it without additional processing. Python is
a high-level language that must be interpreted into machine code (binary) before
it can be executed.
A compiler reads the program and translates it completely before the program
starts running. In this case, the high-level program is called the source code, and
the translated program is called the object code or the executable. Once a
program is compiled, you can execute it repeatedly without further translation.
Compilers take the entire source code and produce object code or the executable
and interpreters execute the code line by line.
Many modern languages use both processes. They are first compiled into a lower
level language, called byte code, and then interpreted by a program called a
virtual machine.
There are two ways to use the Python interpreter: shell mode and program mode.
In shell mode, you type Python expressions into the Python shell, and the
interpreter immediately shows the result. Alternatively, you can write an entire
program by placing lines of Python instructions in a file and then use the
interpreter to execute the contents of the file as a whole. Such a file is often
referred to as source code.
Runtime errors = error that does not appear until you run the program. E.g.,
attempting to divide by 0. Python cannot reliably tell if you are trying to divide
by 0 until it is executing your program.
Variables
String = a sequence of characters. Triple quoted strings can even span multiple
lines
Type conversion functions = the functions int, float and str will (attempt to)
convert their arguments into types int, float and str respectively.
Int function will ALWAYS round down. E.g., int(3.9999) = 3.
Assignment token = create variables. E.g., n = 17 means that n is a reference to
the object 17.
division / = always evaluates to a floating point
division // = integer division. It always truncates its result down to the next
smallest integer.
Exponentiation = 2 ** 3 ** 2 = 2 ** 9 = 512. The right-most ** operator gets
done first.
Exponentiation has the next highest precedence. Operators with the same
precedence (except for **) are evaluated from left-to-right.
If a function has no return statement, then by default it returns None. E.g., this
function
If structure:
if BOOLEAN EXPRESSION:
STATEMENTS_1 # executed if condition evaluates to True
else:
STATEMENTS_2 # executed if condition evaluates to False
Strings
Strings are also objects. Each string instance has its own attributes
and methods which can be accessed by the dot notation.
Method Parameters Description
capitalize none Returns a string with first character capitalized, the rest lower
strip none Returns a string with the leading and trailing whitespace removed
replace old, new Replaces all occurrences of old substring with new
find item Returns the leftmost index where the substring item is found, or -1 if not found
rfind item Returns the rightmost index where the substring item is found, or -1 if not
found
index item Like find except causes a runtime error if item is not found
rindex item Like rfind except causes a runtime error if item is not found
string.split(separator)
glue.join(list)
Other methods from import string:
string.ascii_lowercase
string.ascii_uppercase
string.digits
string.punctuation
String.format() = the arguments of format are inserted in order. If you don’t want
to display all decimal, use {:.1f}, {:.2f}, and so on. This rounds the number to a
certain number of digits.
Lists
A list is a sequential collection of data values, where each value is identified by
an index. The values that make up a list are called its elements. Lists are similar
to strings, which are ordered collections of characters, except that the elements
of a list can have any type and for any one list, the items can be of different
types.
id function = every object has a unique identification tag. The function returns
an object’s id. An id is usually a very large integer value (corresponding to an
address in memory).
Unlike strings, lists are MUTABLE.
You can remove elements from a list by assigning the empty list to them.
alist = ['a', 'b', 'c', 'd', 'e', 'f']
alist[1:3] = []
print(alist)
>>> ['a', 'd', 'e', 'f']
You can also use del to remove items.
Slice is used to clone a list. A slice of a list creates a new list.
List[:] creates a copy of a list. The copy will be pointing at something different,
so changes on one do not affect changes on the other and the is operator will
return False.
List methods
Method Parameters Result Description
insert position, item mutator Inserts a new item at the position given
index item return idx Returns the position of first occurrence of item
List comprehension
General syntax:
list() function = Python has a built-in type conversion function called list that
tries to turn whatever you give it into a list.
Tuples
Tuples are IMMUTABLE.
Syntactically, a tuple is a comma-separated sequence of values.
Files
Open file and then close it.
Method
Name Use Explanation
open open(filename,'r') Open a file called filename and use it for reading. This will return
a reference to a file object.
open open(filename,'w') Open a file called filename and use it for writing. This will also
return a reference to a file object.
Method
Name Use Explanation
If your file and your Python program are in the same directory you can simply
use the filename like this: open('myfile.txt', 'r'). If your file and your Python
program are in different directories then you must refer to one or more directories,
either in a relative file path to the file like this: open('../myData/data3.txt', 'r'), or
in an absolute file path like
open('/users/bmiller/myFiles/allProjects/myData/data3.txt', 'r').
Because text files are sequences of lines of text, we can use the for loop to
iterate through each line of the file.
Methods to read files:
Method
Name Use Explanation
write filevar.write(astring) Add astring to the end of the file. filevar must refer to a file
that has been opened for writing.
read(n) filevar.read() Reads and returns a string of n characters, or the entire file
as a single string if n is not provided.
readline(n) filevar.readline() Returns the next line of the file with all text up to and
including the newline character. If n is provided as a
parameter than only n characters will be returned if the line is
longer than n.
readlines(n) filevar.readlines() Returns a list of strings, each representing a single line of the
file. If n is not provided then all lines of the file are returned. If
n is provided then n characters are read but n is rounded up
so that an entire line is returned.
Dictionaries
Strings, lists, and tuples — are sequential collections. Dictionaries are an
unordered, associative collection.
The del statement removes a key-value pair from a dictionary.
Dictionaries are MUTABLE.
The len function also works on dictionaries. It returns the number of key-value
pairs.
Dictionary methods:
Method Parameters Description
get key Returns the value associated with key; None otherwise
get key,alt Returns the value associated with key; alt otherwise
Numpy
%timeit = applies to one statement. It runs the statement multiple
times and gets average times of 3 best.
%%timeit = applies to entire cell.
Basic functions:
a = np.array([]) = create array
a.ndim
a.shape
len(a)
np.arange()
np.linspace(start, end, number of points)
np.ones(tuple), np.zeros(tuple)
np.eye() = ones on diagonal
np.diag
np.random.rand(shape) = Create an array of the given shape and
populate it with random samples from a uniform distribution
over [0, 1)
np.random.randint()
np.tile
np.triu
array.sum = sum all elements in array. Axis = 0, columns, axis = 1,
rows.