MITx: 6.00.x Introduction to Computer Science and Programming Using Python HarvardX Course Notes
Last Updated: December 31, 2018 by Pepe Sandoval
If you find the information in this page useful and want to show your support, you can make a donation
Use PayPal
This will help me create more stuff and fix the existent content...
Primitive constructs: numbers, strings, simple operators
Expression: legal combinations of one or more primitives
Syntax: Which sequence of characters and symbols constitute a well-formed expression (sentence), it doesn't care about meaning or if it states a logical idea
2.7182 + 3.1416
; incorrect: 3.1416"abc"
Static semantics: Which well-formed expression (syntactically correct) have a meaning, make sense
var = 2.7182 + 3.1416
; Static semantics error: var = 3.1416/"abc"
Semantics: What is the meaning of an expression
int
, float
, bool
NoneType
.py
file containing a collection of Python definitions (functions, classes, etc.) and statements (declared objects, variables, etc.)import <module_name>
reads an execute all statements of that module file and creates a namespace for that module so you can access the variables and objects of the module using <module_name>.<object_name>
from <module_name> import *
reads an execute all statements of that module file and binds the current scope to all the objects defined in the module, this means
it places the object names defined in the module name
directly into the caller's symbol table (the file that has the from <module_name> import *
),
any objects that already exist with the same name will be overwrittenstatements in a module are executed only the first time a module is imported
statements in a module will only be executed the first time a module is imported in other words when interpreter reaches the import <module_name>
line
When the interpreter executes an import <module_name>
statement it searches for a module_name.py
in the following directories the all the search directories end up in the Python variable sys.path
:
PYTHONPATH
environment variablebuilt-in function dir()
returns a sorted list of names in the current local symbol table
When a .py
file is imported as a module Python sets the special __name__
to the name of the module. However, if a file is run as a standalone script, __name__
is set to __main__
map
applies a function to a collection of suitable elementslist(map(abs, [1, -2, -3, 4, 5]))
list(map(min, [1, -2, -3, 4, 5], [2, 12, 4, 1, 6]))
Collections: Group of variables that can be of the same or different type.
Types of collections:
()
for tuples[]
for lists{}
for dictionaries+
creates a new tuple), Indexing ([n]
), Slicing ([s:e:i]
), Repeats (*
)("one",)
is a tuple, meanwhile ("one")
is not, it evaluates to a string+
creates a new list[n]
[s:e:i]
*
mylist.append(element)
mutates/modifies the list by adding only one element to the list, does not create a new listmylist.extend(olist)
mutates/modifies the list by adding all the elements of another list, does not create a new listmylist.remove(element)
, del(mylist[index])
or mylist.pop()
mutates/modifies the list by removing the specified elementmylist.sort()
mutates/modifies the list or sorted(mylist)
does not mutate list, it return a new sorted listmylist.reverse()
mutates/modifies the listlist(mystr)
''.join(mylist)
or 'charToJoin'.join(mylist)
mystr.split(' ')
Avoid mutate during iteration on the same list due to loop iterators that cant be aware of changes on the fly
<key, value>
pairs, entries are unordered and can only be accessed by key not an index, because it is unordered it may or may not stay in the order in which you added themint
, float
, tuple
, bool
) and hashablemydict[newkey] = newvalue
mutates/modifies the dictionarydel(mydict[key])
mutates/modifies the dictionarymydict.keys()
gets an iterator to the keys (commonly converted to a list for convenience list(mydict.keys())
)mydict.values()
gets an iterator to the values (commonly converted to a list for convenience list(mydict.values())
)Test suite: collection of inputs that has a high likelihood of reveling bugs
Black-Box Testing:
Glass-Box Testing:
Unit testing checks that a module or function works, that it produces the expected output
Integration testing checks that the system as a whole works
Drivers: (in a testing context) is a piece of code that does the testing for use. So it sets up an environment or things that are need to run test, invoke the test with predefined inputs, save results and report them
Stub: Simulates parts of program used for testing
Regression testing: Go back and re-run tests that passed before
Bug Qualifiers
try
, except
, else
(executed if try completes with no exceptions) finally
(always executed after try, else and except) and raise Exception("message")
to raise exceptionsSyntaxError
: Python can't parse programIndexError
: Trying to access beyond list limitsNameError
: local or global name not found, referencing non-existent variableAttributeError
: attribute reference failsTypeError
: operand doesn't have correct type, mixing data types inappropriatelyValueError
: operand type okay, but value is illegalIOError
: IO system reports malfunctionself
)__init__
method of an object is the constructor of the classisinstance()
to check for defined class types__add__(self, other)
-> self + other
__sub__(self, other)
-> self - other
__eq__(self, other)
-> self == other
__lt__(self, other)
-> self < other
__gt__(self, other)
-> self > other
__len__(self)
-> len(self)
__str__(self)
-> print(self)
or str(self)
class Point(object):
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return "("+str(self.x)+" , "+str(self.y)+")"
def __add__(self, o):
return Point(self.x+o.x, self.y+o.y)
A = Point(1, 2)
B = Point(7, 7)
C = A+B
print(A, B, C)
yield
statement.yield
statements is called through a reference to that method and using the next
method to execute the code of the methodyield
suspends the execution and returns a value, returning from a generator raises a StopIteration
exceptiondef gen_fib():
fibn_1 = 1
fibn_2 = 0
while True:
next = fibn_1 + fibn_2
yield next
fibn_2 = fibn_1
fibn_1 = next
gen_ins = gen_fib()
print(gen_ins.__next__())
for n in gen_ins:
print(n)
pylab
: pip install -U matplotlib
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
x = []
y = []
for i in range(0,30):
x.append(i)
y.append(x[i]**2)
plt.plot(x, y)
plt.plot(x, y, 'ro')
plt.axis([min(x), max(x), min(y), max(y)])
plt.savefig('fig.png')
plt.show()
plt.close()
None
is frequently used to represent the absence of a value. None
is the only value in Python of type NoneType
in
and not in
test for collection membership <element> in <collection>
evaluates to True
if element is a member of the collection when used in a for loop the element is assigned to the members of the collectionrange
is a built-in function that generates a sequence of integersIf you find the information in this page useful and want to show your support, you can make a donation
Use PayPal
This will help me create more stuff and fix the existent content...