Documentos de Académico
Documentos de Profesional
Documentos de Cultura
else:
y=0
-while loop: needs colons
-while x > 1:
x = x - 1
-can use break, continue statement
-for loop: allows iteration over any variable type, such as list
-item_list = [1,"two"]
for x in item_list:
print(x)
-function: defined using def statement
-return statement returns value
-exceptions can be caught and handled using try-except-finally-else compound sta
tement
-any exception tht isn't caught will cause program to exit
Part 2: The essentials
Chapter 4: The absolute basics:
-python uses indentation to determine block structure
-'#' character used to start a comment i.e. # comment
-neither variable type declaration nor end-of-line delimiter necessary
-variables created automatically when first assigned
-python variables can be set to any type of object
i.e. x = 5
x = "sup"
-del statement deletes variable i.e. del x
-division of two ints with / returns float, // returns int
-\ can be used to escape characters: \t, \n, \" , \', \\
-integers have unlimited range in python, i.e. 4
-float can be written with decimal point or using scientific notation, i.e. 3.14
-2E-8
-booleans are either True of False and behave identically to 1 and 0
-int(200.3) converts float to int, float(1) converts int to float
-built in numeric functions: abs, float, int, long, max, min, oct, hex, pow, rou
nd
-functions in math module include: acos, asin, atan, atan2, ceil, cos, cosh, e,
exp, fabs, floor, fmod, hypot, log, log10, mod, pi pow, sin, sinh, sqrt, tan
-None represents empty value
-can use input() function to get input from user, i.e. name = input("Enter Name:
")
-input always returns string
-python code conventions, only classes CapatalizeEachWord, all other identifiers
all lowercase, underscores_for_readability
Chapter 5: Lists, Tuples, Sets
-list is an ordered collection of objects i.e. x = [1, 2, 3]
-list automatically grows and shrinks as needed
-python lists can contain different types of elements
-len built-in function returns number of elements in list, i.e. len(x)
-list can be indexed from front using positive integer (starting with 0 as first
element) x[0]
-list can be indexed from back using negative indices (with -1 as last element)
x[-2]
-obtain a slice from list using [m:n], when m is inclusive starting point and n
is EXclusive end point
-[m:] slice goes to lists end, [:n] slice starts at beginning
-can use this notation to add, remove, or replace elements in list
-size of list increases or decreases if new slice is bigger or smaller t
han slice replacing
x[len(x):] = [5 , 6, 7] # appends list to end of list
post-code
-break statement while loop terminates while loop and does not execute post-code
in else clause
-continue causes remained of body to be skipped in current iteration
-syntax of if-elif-else construct:
if condition:
body
elif condition:
body
else:
body
-can use pass statement as placeholder where statement is needed (i.e. body of i
f), i.e. pass
-for loop iterates over values returned by any iterable object
-list, tuple, string, or special function called range, or special type
of function called generator
-for syntax (note else is optional)
for item in sequence:
body
else:
post-code
-body executed once for each element of sequence and 'item' variable set
to be each element in sequence
-range(n) returns a sequence 0,1,2,...,n-1 that can be used for iteration on
x = [1, 3, -7, 4, 9, -5, 4]
for i in range(len(x)):
if x[i] < 0:
print("Found a negative number at index ", i)
-range(n,m) returns a sequence n, n+1, ...,m-2,m-1
-if m>=n, returns empty sequence
-range(n,m,z) returns a sequence: n, n+z, n+2z,...,m-2z,m-z
i.e. range(5,0,-1) returns 5, 4, 3, 2, 1
-can iterate through tuples instead of usual single variable using for loop with
tuple unpacking
somelist = [(1, 2), (3, 7), (9, 5)]
result = 0
for x, y in somelist:
result = result + (x * y)
-enumerate function returns tuples (index, item) to loop through both items and
index
x = [1, 3, -7, 4, 9, -5, 4]
for i, n in enumerate(x):
if n < 0:
print("Found a negative number at index ", i)
-zip function takes corresponding elements from one or more iterables and combin
es them into tuples until it reaches end of shortest iterable
>>> x = [1, 2, 3, 4]
>>> y = ['a', 'b', 'c']
>>> z = zip(x, y)
>>> list(z)
[(1, 'a'), (2, 'b'), (3, 'c')]
-list or dictionary comprehension is one-line for loop that creates a new list o
r dictionary from another list
new_list = [expression for variable in old_list if expression]
new_dict = {expression:expression for variable in list if expression}
in variable
-positional parameter: specify definition variable names for each parameter, and
when function is called parameters used in calling code matched to parameter ba
sed on order
-i.e. example shown in fact(n)
-requires number of parameters used in calling code matches number of pa
rameters in function definition
-function parameters can have default values, which are declared by assigning de
fault value in first line of function definition
-i.e. def fun(arg1, arg2=default2, arg3=default3, . . .)
-any number of params can have default values, but must be defined as la
st params in param list
>>> def power(x, y=2):
...
r = 1
...
while y > 0:
...
r = r * x
...
y = y - 1
...
return r
>>> power(3,3) ; power(3)
-can pass arguments into function using name of corresponding function parameter
rather than its position
>>> power(y=2, x=3)
9
-called keyword passing
-useful when defining function with large number of possible arguments,
that mostly have common defaults
-prefixing final parameter name of function a * causes all excess nonkeyword arg
uments in a call of function to be assigned as a tuple to given parameter
>>> def maximum(*numbers):
...
if len(numbers) == 0:
...
return None
...
else:
...
maxnum = numbers[0]
...
for n in numbers[1:]:
...
if n > maxnum:
...
maxnum = n
...
return maxnum
-arguments passed by object reference and parameter becomes new reference to obj
ect
-so changes to immutable objects (i.e. strings, tuples, numbers) has no
effect outside function
-changes to mutable objects (i.e. list, dictionary, class) persist outsi
de function
-but reassigning parameter has no effect outside function
-can explicitly access global variable existing outside function using global st
atement
a="one"
def changeGlobal():
global a
a = 1
changeGlobal() <- a is now 1
-nonlocal statement is similar to global, but causes identifier to rever to prev
iously bound variable in closest enclosing scope
-global only acesses top level variable
-generator function can be used to define own iterators
-returns each iterations value using yield keyword
-when no more iterations, empty return statement or flowing of end of fu
generator, x = 0
generator, x = 1
generator, x = 2
generator, x = 3
-can use generator with in clause to see if value is in series generator produce
s
>>> 2 in four()
example:
>>> from mymath import pi
>>> pi
3.1415899999999999
-import statement takes three different forms:
-import modulename
-search for ptyhon module of given name, parses contents, makes
it available
-importing code to names within module must still be prepended w
ith module name
-from modulename import name1, name2, name3, ...
-each name1, name2, ... from within module name made available t
o importing code
-name1, name2,.. can be used without prepending modulename
-from module import *
-imports all public names from module name (all that dont begin
with an underscore )
-if two modules imported this way define same name, then second
module will replace name from first
-python looks for modules in variable called path, which can be accessed through
module named sys
>>> import sys
>>> sys.path
_list of directories in the search path_
-python searches each directory in list when attempting to execute impor
t, and first module that satisfies import request used
-if no module found, ImportError exception raised
-sys.path variable initalized from value of environment variable PYTHONPATH, if
it exists
-wherever script is run, sys.path variable for script has directory cont
aining scrip inserted as first element
-in order to ensure programs can use your python modules, must do one of followi
ng:
-place module in one of directories python normally searches for modules
-place all modules used by python program into same directory as program
-create a directory that will hold moduels, and modify sys.path variable
so includes new directory
-prepend name of variable or function in module with _ if you want name to be pr
ivate to within module (i.e. will not be imported with from ... import *)
namespace in python is a mapping from identifiers to objects usually represented
as dictionary
-when block of code is executed in python it has three namespaces, local, global
, and built-in
-variable encountered in execution first searched for in local name-spac
e, if doesn't exist, checks global namespace, if doesn't exist checks built-in n
amespace
-if variable not present in all three namespaces, NameError exception oc
curs
-built-in functions include len, min, max, int, float, long, list, tuple
, cmp, range, str,and repr
python script.py arg1 arg2
Ch 11. Python Programs 129-146
import sys
def main():
print("this is our second test script file")
print(sys.argv)
main()
If we call this with the line
python script2.py arg1 arg2 3
we get
this is our second test script file
['script2.py', 'arg1', 'arg2', '3']
You can see that the command-line arguments have been stored in sys.argv as a li
st of
strings.
Ch 12. Using the filesystem 147 - 158
Ch 13. Reading and writing files: 159 - 171
Ch 14. Exceptions 172 but skip to 176 - 185
Ch 15. Classes and OO programming 186 - 209
-class in python is effectively a data type
-define class with class statement
class MyClass:
body
-body is list of python statements, typically variable assignements and function
definitions
-once class is defined, new instance of class can be created by calling class na
me as function
instance = MyClass()
-class can be used as structures or records
-fields of instance don't need to be declared ahead of time, but can be
created on the fly
>>> class Circle:
...
pass
...
>>> my_circle = Circle()
>>> my_circle.radius = 5
>>> print(2 * 3.14 * my_circle.radius)
31.4
-fields of an instance can be accessed using dot notation as shown above
-can initialize fields of instance automatically by including an _init_ initiali
zation method in class body
-function is run every time instance of class is created, with new insta
nce as first argument
-_init_ method similar to constructor, initializing fields of class
-note self is always the name of the first argument in _init_
class Circle:
def __init__(self):
self.radius = 1
my_circle = Circle()
print(2 * 3.14 * my_circle.radius)
my_circle.radius = 5
print(2 * 3.14 * my_circle.radius)
-in above case, radius is instance variable of Circle instance (each instance of
Circle class has own copy of radius)
-can create instance variables as necessary by assigning them to field of class
instance
instance.variable = value
-method is function associated with particular class
-note all use of instance variables - both assignment and access - requi
re expliction metioning of containing instance in form instance.variable
-so methods in class must take self as argument as well
-first argument of any method is instance was invoked by/on named 'self'
by convention
-invoked with dot notation
>>> class Circle:
... def __init__(self):
...
self.radius = 1
... def area(self):
...
return self.radius * self.radius * 3.14159
>>> c = Circle()
>>> c.radius = 3
>>> print(c.area())
28.27431
-methods can be invoked with arguments, if method definitions accept those argum
ents
class Circle:
def __init__(self, radius = 1):
self.radius = radius
def area(self):
return self.radius * self.radius * 3.14159
c = Circle(5)
-class variable is variable associated with class, rather than instance of class
-can be accessed by all instances of class
-class variable created by assignment in class body, rather than _init_
function
class Circle:
pi = 3.14159
def __init__(self, radius):
self.radius = radius
def area(self):
return self.radius * self.radius * Circle.pi
>>> Circle.pi
3.1415899999999999
-python allows invokation of static methods even when no instance of class has b
een created
-must use @staticmethod decorator
"""circle module: contains the Circle class."""
class Circle:
"""Circle class"""
all_circles = []
pi = 3.14159
def __init__(self, r=1):
"""Create a Circle with the given radius"""
self.radius = r
Circle.all_circles.append(self)
def area(self):
"""determine the area of the Circle"""
return Circle.pi * self.radius * self.radius
@staticmethod
def total_area():
total = 0
for c in Circle.all_circles:
total = total + c.area()
return total
>>> import circle
>>> c1 = circle.Circle(1)
>>> c2 = circle.Circle(2)
>>> circle.Circle.total_area()
15.70795
>>> c2.radius = 3
>>> circle.Circle.total_area()
31.415899999999997
-classmethod also does not need instance of class before being invoked
-but method implicitly passed name of class as parameter so no need to h
ardcode name of class into function
-can also just avoid problem by using self._class_ in place of ClassName
-must place @classmethod decorator before method def
"""circle module: contains the Circle class in circe_cm.py."""
class Circle:
"""Circle class"""
all_circles = []
pi = 3.14159
def __init__(self, r=1):
"""Create a Circle with the given radius"""
self.radius = r
self.__class__.all_circles.append(self)
def area(self):
"""determine the area of the Circle"""
return self.__class__.pi * self.radius * self.radius
@classmethod
def total_area(cls):
total = 0
for c in cls.all_circles:
total = total + c.area()
return total
>>>
>>>
>>>
>>>
import circle_cm
c1 = circle_cm.Circle(1)
c2 = circle_cm.Circle(2)
circle_cm.Circle.total_area()
class Shape:
def __init__(self, x, y):
self.x = x
self.y = y
def move(self, delta_x, delta_y):
self.x = self.x + delta_x
self.y = self.y + delta_y
class Square(Shape): <--- note shape
def __init__(self, side=1, x=0, y=0):
super().__init__(x, y) <- must call _init_ of superclass using s
uper() function
self.side = side
class Circle(Shape):
def __init__(self, r=1, x=0, y=0):
super().__init__(x, y)
self.radius = r
-two requirements for inheritance in python
-must define inheritance hierarchy by typing name of superclass in brack
ets immediately after name of class being defined with class keyword
-must call _init_ method of superclass by using super function
-could also call superclasses method by naming inherited class u
sing Shape._init_(self,x,y)
-subclasses inherit instance variables, class variables, and methods of supercla
ss
c = Circle(1)
c.move(3,4)
-private variable and private methods cannot be seen outside of methods of class
in which its defined
-any method or instance variable whose name begins and doesn't end with
a double underscore __ is private
class Mine:
def __init__(self):
self.x = 2
self.__y = 3
def print_y(self):
print(self.__y)
>>> m = Mine()
>>> print(m.x)
2
>>> print(m.__y) <-- __y private
Traceback (innermost last):
File "<stdin>", line 1, in ?
AttributeError: 'Mine' object has no attribute '__y'
-when in method of class, have direct access, in order, to:
-local namespace: parameters and variables declared in the method
-global namespace: functions and variales declared at module level
-built-in namespace: built-in functions and built-in exceptions
E:
F:
G:
D(G):
C:
B(E, F):
A(B, C, D):