Files:

Report 4 Downloads 226 Views
Files: Our data files are text files which are filled with characters. In Python, we must open files before we can use them and close them when we are done with them. Once a file is opened, it becomes a Python object just like all other data. Newline Character (\n): A line of a file is defined to be a sequence of characters up to and including a special character called the newline character (\n). #information about my test file F:\Academic\CSCA08\Weekly Reading Notes\test.txt Cinny My examples nothing more to say

open(filename, ‘r’): Open a file called filename and use it for reading. open(filename, ‘w’): Open a file called filename and use it for writing. open() will return a reference to a file object. #If the file and the Python program are in the same directory open(‘test.txt’, ‘r’) #If not open(‘F:\Academic\CSCA08\Weekly Reading Notes\test.txt’, ‘r’) #Create a variable name for later referencing my_file = open(‘test.txt’, ‘r’) >>> my_file = open(‘test.txt’, ‘r’) >>> my_file

filevariable.read(n): Reads and returns a string of n characters, or the entire file as a single string if n is not provided. >>> x = open('test.txt', 'r') >>> y = x.read() >>> y ‘Cinny\nMy examples\nnothing more to say’ >>> print(y) Cinny

My examples nothing more to say >>> z = x.read() >>> z ‘’ #Be careful about this one!!! #restart the Python shell >>> x = open(‘test.txt’, ‘r’) >>> y = x.read(2) >>> print(y) Ci

filevariable.readline(n): Returns the next line of the file with all text up to and including the newline character If the line is longer than n characters, only n characters will be returned. >>> x = open(‘test.txt’, ‘r’) >>> y = x.readline() >>> y ‘Cinny\n’ >>> Y = y.strip(‘\n’) >>> Y ‘Cinny’ >>> print(y) Cinny #If you evaluate it, the new line will be represented as ‘\n’ #If you print it, you will not see the ‘\n’, the new line will just be shown >>> z = x.readline() >>> z ‘My examples\n’ #If you apply readline to the same file the second times #the next line will be shown >>> m = x.readline(2) >>> m ‘no’ #If I didn’t input n, ‘nothing more to say’ will be returned

filevariable.readlines(n): Returns a list of strings, each representing a single line of the file. If n is provided, then n characters are read but n is rounded up so that an entire line is returned. >>> x = open(‘test.txt’, ‘r’) >>> y = x.readlines()

>>> y ['Cinny\n', 'My examples\n', 'nothing more to say'] >>> print(y) ['Cinny\n', 'My examples\n', 'nothing more to say'] #This one will not hide the ‘\n’ >>> x = open(‘test.txt’, ‘r’) >>> y = x.readlines(2) >>> y ['Cinny\n'] #n is rounded up so the entire line is returned >>> x = open(‘test.txt’, ‘r’) >>> y = x.readlines(10) >>> y ['Cinny\n', 'My examples\n']

filevariable.write(astring): Add astring to the end of the file. Note: Text files contain sequences of characters and we usually think of these character sequences as being lines of the file where each line ends with the newline ‘\n’ character. So you don’t need to write like filevar.write(‘\nanewline\n’). You only need filevar.write(‘anewline\n’) or filevar.write(‘anewline’ + ‘\n’)

filevariable.close(): File use is complete. Note: You have to close your file when you finish editing it, or else what you have written will not be saved. my_file.close()

Dictionaries: Dictionaries are Python’s built-in mapping type. They are unordered, associative collection of key-value pairs. The association is from a key to a value. The empty dictionary is denoted {}. Dictionaries are also mutable. Creating a dictionary: #Creating an empty dictionary my_dict = {} #Add key-value pairs my_dic*‘key_name’+ = ‘value_name’ my_dic*‘my_name’+ = ‘Cinny’ >>> my_dict ,‘key_name’: ’value_name’, ‘my_name’: ‘Cinny’ #the order of pairs are random

Note: The values are accessed with keys, not indices (in a list or a str, the values are accessed with

indices)

Dictionary Operations: The del Statement: Remove a key-value pair from a dict Item Assignments: roommates = {1: 'Cinny', 2: 'Chan', 3: 'Fairy', 4: 'Yeye'} roommates[4] = 'Michelle' #If the key is not exist, it will be created roommates*0+ = ‘’ >>> roomates {0: '' , 1: 'Cinny', 2: 'Chan', 3: 'Fairy', 4: 'Michelle'}

len(): Return the number of key-value pairs in and not in: Test if a key is in the dict Dictionary Methods: keys(): Return a view of the keys in the dict values(): Return a view of the values in the dict items(): Return a view of the key-value pairs in the dict >>> boxes = {'red': 'heart', 'black': '', 'white': 'paper'} >>> boxes.keys() dict_keys(['red', 'white', 'black']) >>> boxes.values() dict_values(['heart', 'paper', '']) >>> boxes.items() dict_items([('red', 'heart'), ('white', 'paper'), ('black', '')])

Note: These return dict_***(***, **, …+), we can loop through these values as well as apply list() to them to convert them into a list

get(key): Return the value associated with key; if key doesn’t exist, return None get(key, alt): Return the value associated with key; alt otherwise >>> boxes = {'red': 'heart', 'black': '', 'white': 'paper'} >>> boxes.get('red') 'heart' >>> boxes.get('yellow') >>> boxes.get('red', 'not_here') 'heart' >>> boxes.get('yellow', 'not_here') 'not_here'

Looping Through dict

inventory = {'apples': 430, 'bananas': 312, 'oranges': 525, 'pears': 217} print(list(inventory.values())) print(list(inventory.items())) for (k,v) in inventory.items(): print("Got",k,"that maps to",v) for k in inventory: print("Got",k,"that maps to",inventory[k]) [430, 312, 525, 217] [('apples', 430), ('bananas', 312), ('oranges', 525), ('pears', 217)] Got apples that maps to 430 Got bananas that maps to 312 Got oranges that maps to 525 Got pears that maps to 217 Got apples that maps to 430 Got bananas that maps to 312 Got oranges that maps to 525 Got pears that maps to 217

Matrix: A matrix is a two dimensional collection, typically thought of as having rows and columns of data. We can represent matrix using a list of lists representation.

#representing this matrix

matrix = [[0, 0, 0, 1, 0], [0, 0, 0, 0, 0], [0, 2, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 3, 0]]

This example matrix only has 3 data values that are nonzero. This kind of matrix is called a sparse matrix. Since there’s no need to store all the zeros, the list of lists representation is inefficient. An alternative representation is to use a dictionary. Keys are tuples that contain the row and column numbers.

#representing this matrix

matrix = {(0, 3): 1, (2, 1): 2, (4, 3): 3} #since there are only 3 nonzero values, we only need 3 key-value pairs

Doctest: Docstrings: The triple-quoted string after the function header used as documentation of functions. It is retrievable at runtime with the expression .__doc__ def my_function(parameters): '''(xx) -> xx This is my docstring!! ''' body >>> my_function.__doc__ '(xx) -> xx\n This is my docstring!!\n

'

Design Recipe: (Acronym: ECHDBT - Every Computer Has Download Bad Things) Steps to write a function definition: 1. Example: write some representative examples Note: examples can be either simple function calls or a small program ‘>>>’ follows one space and one statement if the statement has multiple lines, use ‘...’ for the lines except the first line the expected output will be None if nothing was written Note: You don’t need to write examples for functions that involve randomness or I/O. ''' >>> is_even(2) True >>> is_even(17) False ''' ''' >>> i = 0 >>> for i in range(5): ... print(is_even(i)) True False True False True '''

2. Type Contract: describe the types of the parameters and any return values

#some examples: (str) -> int (str, bool) -> NoneType (list of int, tuple of (str, int)) -> list #collection of different data types: str, int, float, bool, list, tuple list of int, list of str, tuple of (str), tuple of (int, float, list, str) NoneType, object file open for reading, io.TextIOWrapper

Header: write the function header >>> my_function.__doc__ '(xx) -> xx\n This is my docstring!!\n

'

Description: write description of what the function does and mention each parameter by name >>> my_function.__doc__ '(xx) -> xx\n This is my docstring!!\n

'

Code the Body: write the actual code body >>> my_function.__doc__ '(xx) -> xx\n This is my docstring!!\n

'

Test Your Function: test your function

testmod(): Write the following block at the end of each module It will examine the docstring in the module or you can just input the code in Python shell if(__main__ == ‘__name__’): import doctest doctest.testmod()

testfile(): If you’ve write a unittest for your module, you can use testfile() to use the test file you write import doctest doctest.testfile(‘filename’)

Classes and Objects: Python is an object-oriented programming (OOP) language. OOP: Object-oriented programming is a way to handle the rapidly increasing size and complexity of software systems and to make it easier to modify these large and complex systems over time. Procedural Programming & OOP: In procedural programming, the focus is on writing functions or procedures which operate on date. In object-oriented programming, the focus is on the creation of objects which contain both data and functionality together.

Active Agents:

#If we want to write a name on a paper. #In function definitions def writing_a_name(para): writing_a_name(paper) #Here, writing_a_name is the active agent #You pass paper to it for it to execute #However, in object-oriented programming, the objects are the active agents paper.writing_a_name() #Here, paper is the active agents. #You let the paper to use its writing_a_name method #The second way fits our mental chunking and real-life experience more accurately. #Because you get a paper first, and then you decide to write a name on it. #We don’t have a writing_a_name function in hand and then pass the paper to it in real life

Class: The type of an object Naming a class name, we do CamelCase. CamelCase: CapitalizeEachWord pot_hole_case: add_underscore_between_words

Object: An instance of a class In Python, every value is actually an object. Programs manipulate those objects either by performing computation with them or by asking them to perform methods. That is, an object has a state and a collection of methods that it can perform. Objects State Methods An integer its value, ... various operations A turtle its position, its color, its heading, ... go forward, fo backward, turn right, turn left, ...

Objects are mutable. We can change its state by making an assignment to one of its instance variables.

Instance: An object whose type is of some class Instance and object are used interchangeably.

Shallow equality: Only compares the references, not the contents of the objects. Deep equality: Also compare the values ‘deep’ in the object, not just the reference to the object.

Method: A function that belongs to a class User Defined Classes - class ClassName: : Class definitions can appear anywhere in a program, but they are usually near the beginning (after the import statements).

We’ve already seen classes like str, int, float and Turtle – These were defined by Python. Most of the time, however, we need to define our own classes.

__init__(self) : Every class should have a method with the special name __init__ This is known as an initializer (constructor) method. It’s used to set up the default parameters (set up objects’ states) It’s automatically called whenever a new instance of Class is created #To define a class Point class Point: ‘’’ Point class for representing and manipulating x, y coordinates. ‘’’ #This initializer method (constructor) is automatically called whenever a new instance of Point is created. def __init__(self): ‘’’ Create a new point at the origin ‘’’ self.x = 0 self.y = 0 #To use the class we just defined p = Point() q = Point() #Here we just created two points #Such assignment statement is a combined process of ‘make a new object’ and ‘get it initialized’ is called instantiation. print(p) print(q) print(p is q) False

__init__(self, paras): We can improve our constructor by putting extra parameters into it. class Point: def __init__(self, initX, initY): self.x = initX self.y = initY #self.blabla means the blabla of self #You use the pattern to set the object’s states #Now we can create points at any positions p = Point(7, 6)

Adding other Methods – method(self, paras):

class Point: def __init__(self, initX, initY): self.x = initX self.y = initY def getX(self): return self.x def getY(self): return self.y p = Point(7, 6) print(p.getX()) print(p.getY()) 7 6

The parameter self: The parameter self is used to remember data that belongs to a certain object. We can change objects’ state by self.statename = blabla With self as one of the parameters, all methods of the class can access the objects. They get implicitly passed a copy of the object upon which it was called. When calling a method, we don’t include self in the method call (self.MethodName(paras) ) But we do in the method definition (def MethodName(self,paras): ) You can think of self.MethodName(paras) as an alias of Class.MethodName(self, paras)

__str__(self): Return what you want to output when an object of this class is cast to a string (or printed) When we print an object, by default Python tells you that p is an object of type Point and it doesn’t tell you anything about the specific state of the point. class Point: def __init__(self, initX, initY): self.x = initX self.y = initY p = Point(7, 6) print(p)

By adding a special method call __str__, we can let Python print what we want when we print an object.

class Point: def __init__(self, initX, initY): self.x = initX self.y = initY def __str__(self): return ‘x = ’ + str(self.x) + ‘, y = ’ + str(self.y) p = Point(7, 6) print(p) x = 7, y = 6

Object as Arguments and Parameters: class Point: def __init__(self, initX, initY): self.x = initX self.y = initY def getX(self): return self.x def getY(self): return self.y def distanceFromOrigin(self): return ((self.x ** 2)+ (self.y **2)) ** 0.5 def distance(point1, point2): ‘’’ Return the distance between two points ‘’’ xdiff = point2.getX() – point1.getX() ydiff = point2.getY() – point1.getY() dist = (xdiff ** 2 + ydiff ** 2) ** 0.5 return dist p = Point(4, 3) q = Point(0, 0) print(distance(p, q)) 5.0

Instance as Return Values: class Point:

def __init__(self, initX, initY): self.x = initX self.y = initY def __str__(self): return ‘x = ’ + str(self.x) + ‘, y = ’ + str(self.y) def halfway(self, target): ‘’’ Return the midpoint of two points ‘’’ mx = (self.x + target.x) / 2 my = (self.y + target.y) / 2 return Point(mx, my p = Point(3, 4) q = Point(5, 12) mid = p.halfway(q) print(mid) print(mid.getX()) print(mid.getY()) x = 4.0, y = 8.0 4.0 8.0

Unittest: