Shared Flashcard Set

Details

CS 0008
Intro to Python
130
Other
Undergraduate 3
12/09/2018

Additional Other Flashcards

 


 

Cards

Term
“Writing data to”
Definition
The process of saving data in a file; it is copied from a variable in RAM to the file.
Term
Output file
Definition
A file that data is written to
Term
“Reading data from”
Definition
The process of retrieving data from a file; data is copied from the file to RAM, referenced by variables.
Term
Input file
Definition
A file from which the data is read
Term
Three steps when a program uses a file
Definition
1. Open the file 2. Process the file 3. Close the file
Term
Text file
Definition
Contains data that has been encoded as text; can be opened and viewed in Notepad
Term
Binary file
Definition
Contains data that has not been converted to text; intended only for a program to read
Term
Sequential access file
Definition
File is read sequentially from beginning to end; can't skip to desired data
Term
Direct access file aka Random access file
Definition
Can jump directly to any piece of data in the file without having to read data that comes before it
Term
Filename extensions
Definition
Short sequences of characters that appear at the end of a filename preceded by a period; extension indicates type of data stored in the file
Term
File object
Definition
Object associated with a specific file
Provides a way for a program to work with the file; file object referenced by a variable
Term
Open function
Definition
Used to open a file; creates a file object and associates it with a file on the disk
General format:
file_object = open(filename, mode)
Term
Mode
Definition
String specifying how the file will be opened: reading only ('r'), writing ('w')- writes over file if already exists, and appending ('a’) - appends data to the end of the file if it already exists
Term
Specifying location of file
Definition
Open function assumes file is in the same directory as the program; can specify alternative path using the letter 'r' before the filename
Term
Method
Definition
A function that belongs to an object and performs some operation using that object; file object’s write method used to write data to the file: file_variable.write(string)
Term
Read method
Definition
File object method that reads entire file contents into memory; ignores \n when printing
Term
Readline method
Definition
File object method that reads a line from the file, one at a time; terminated with \n and line is returned as a string, including '\n', printing an extra line between each read line
Term
Read position
Definition
Marks the location of the next item to be read from a file; the read position of the file updates after every call to readline()
Term
Concatenating newline to a string
Definition
Most data items written to a file are values referenced by variables; usually necessary to concatenate a '\n' to data before writing it using a + operator
Term
Rstrip method
Definition
In many cases need to remove '\n' from string after it is read from a file; string method that strips specific characters from end of the string:
line1 = infile.rstrip('\n')
Term
str function
Definition
Numbers must be converted to a string before written to a file; must be converted back to int or float when reading file in order to perform operations
Term
While loop to process files
Definition
Often the number of items stored in file is unknown; the readline method uses an empty string as a sentinel when end of file is reached: while line != ''
Term
For loop to process files
Definition
A priming read is not necessary and automatically stops when end of file is reached: for line in file_object:
statements
Term
Record
Definition
A complete set of data that describes one item; used with sequential access file
Term
Field
Definition
A single piece of data within a record
Term
Exception
Definition
An error that occurs while a program is running, causing the program to abruptly halt
Term
Traceback
Definition
Error message that gives information regarding line numbers that caused the exception; indicates the type of exception and brief description of the error that caused exception to be raised
Term
Exception handler
Definition
code that responds when exceptions are raised and prevents program from crashing:
try:
statements
except exceptionName:
statements
An except clause that doesn't specify the exception will handle any exception raised or else need to write except clause for each type of exception that needs to be handled
Term
Try suite
Definition
Statements that can potentially raise an exception
Term
Handler
Definition
statements contained in except block
Term
Exception object
Definition
Created in memory when an exception is thrown; contains a default message pertaining to the exception
Ex: except ValueError as err:
Can pass exception object variable (err- which is not a special name) to print function to display the default error message
Term
Else clause
Definition
Try/except statement may include an optional else clause, which appears after all the except clauses
Term
Else suite
Definition
Block of statements executed after statements in try suite, only if no exceptions were raised; if exception was raised, the else suite is skipped
Term
Finally suite
Definition
Block of statements after the finally clause; execute whether an exception occurs or not; purpose is to perform cleanup before exiting
Term
Sequence
Definition
An object that holds multiple items of data, stored one after the other; two main types: lists and tuples
Term
List
Definition
An object that contains multiple data items; they are mutable, meaning their contents can be changed during a program's execution; and they're dynamic, meaning that items can be added or removed:
list = [item1, item2, etc.]
Term
Element
Definition
An item in a list; can be different data types
Term
Repetition operator
Definition
Makes multiple copies of a list and joins them together; the * symbol is a repetition operator when applied to a sequence and an integer:
list * n
applies to strings as well
Term
Index
Definition
A number specifying the position of an element in a list; enables access to individual element in list;
index of first element in the list is 0, second element is 1, and n’th element is n-1
Term
IndexError exception
Definition
Raised if an invalid index is used
Term
Len function
Definition
Returns the length of a sequence such as a list
Term
Concatenating lists
Definition
The + operator can be used to concatenate two lists; can only concatenate a list with another list
Term
Slice
Definition
A span of items that are taken from a sequence; list slicing format: list[start : end]; span is a list containing copies of elements from start up to, but not including, end; if start not specified, 0 is used for start index and if end not specified, len(list) is used for end index
Term
In and Not In operator
Definition
Format: item in (or not in) list; returns either True or False
Term
Append(item)
Definition
Used to add items to a list – item is appended to the end of the existing list: list.append(item)
Term
Index(item)
Definition
Used to determine where an item is located in a list; returns the index of the first element in the list containing item; raises ValueError exception if item not in the list
Term
Insert(index, item):
Definition
Used to insert item at position index in the list
Term
Sort
Definition
Used to sort the elements of the list in ascending order; can be used for letters and words; list.sort()
Term
Remove(item)
Definition
Removes the first occurrence of item in the list
Term
Reverse()
Definition
Reverses the order of the elements in the list
Term
Del statement
Definition
Removes an element from a specific index in a list: del list[i]; different from remove() because remove requires you to tell it the specific element to remove if it exists in the list (ex: remove(‘Pizza’)) but del will delete the item at index i regardless of what that item is
Term
Min and max functions
Definition
Built-in functions that returns the item that has the lowest or highest value in a sequence
Term
Copying lists
Definition
To make a copy of a list you must copy each element of the list; two methods to do this:
creating a new empty list and using a for loop to add a copy of each element from the original list to the new list or
creating a new empty list and concatenating the old list to the new empty list
Term
Writelines method
Definition
Writes a list to a file; does not automatically write \n at then end of each item; use a for loop to write each element and \n
Term
Readlines method
Definition
Returns a file's contents as a list of strings
Term
Two-dimensional lists
Definition
A list that contains other lists as its elements; also known as nested list; common to think of two-dimensional lists as having rows and columns; useful for working with multiple sets of data; to process data in a two-dimensional list need to use two indexes
Term
Tuple
Definition
An immutable sequence that is very similar to a list
but once it is created it cannot be changed; do not support the methods:
append
remove
insert
reverse
sort
Term
List() and Tuple() functions
Definition
Used to convert a list to tuple and vice versa
Term
Basic string operations
Definition
Strings are also sequences; use a for loop to access individual characters of a string; can also access individual characters using indexing
Term
String concantenation
Definition
Appending one string to the end of another string; done with += or + operator; does not include space
Term
String slicing
Definition
Span of items taken from a sequence, known as substring: string[start : end]
Term
String in and not in operator
Definition
Used to determine if a string is (or not) contained in another string: string1 in string2,
string1 and string2 can be string literals or variables referencing strings
Term
String testing methods
Definition
Test a string for specific characteristics; generally Boolean methods, that return True if a condition exists, and False otherwise:
string.isalpha()
isalnum()
isdigit()
etc.
Term
Modification methods
Definition
Return modified versions of strings simulating strings as mutable objects; for example, string comparisons are case sensitive; can use:
lower()
upper()
etc.
Term
Searching and replacing methods
Definition
Searches for substrings and/or replaces occurrences of a substring with another string
Term
endswith(substring) method
Definition
Checks if the string ends with substring; returns True or False
Term
startswith(substring) method
Definition
Checks if the string starts with substring; returns True or False
Term
find(substring) method
Definition
Searches for substring within the string; returns lowest index of the substring, or if the substring is not contained in the string, returns -1
Term
replace(substring, new_string) method
Definition
Returns a copy of the string where every occurrence of substring is replaced with new_string
Term
split method
Definition
Returns a list containing the words in the string; by default, uses space as separator but can specify a different separator by passing it as an argument to the split method: string.split('/')
Term
Dictionary
Definition
Object that stores a collection of data; each element consists of a key and a value and is often referred to as mapping of key to value; key must be an immutable object (such as a string):
dictionary = {key1:val1, key2:val2}
Term
Retrieving a value from a dictionary
Definition
General format: dictionary[key]; if key in the dictionary, associated value is returned, otherwise, KeyError exception is raised; can use in or not in operator to prevent KeyError exception
Term
Add a new key-value pair
Definition
dictionary[key] = value; will replace old value if key already exists
Term
Deleting a key-value pair
Definition
del dictionary[key]; if key not in dictionary, KeyError exception raised
Term
Creating an empty dictionary
Definition
dictionary = {} or dictionary = dict()
Term
Dictionary for loop
Definition
Iterates over all the keys of the dictionary
Term
clear method
Definition
Deletes all the elements in a dictionary, leaving it empty: dictionary.clear()
Term
get method
Definition
Gets a value associated with specified key from the dictionary: dictionary.get(key, default); default is returned if key is not found
Term
items method
Definition
Returns all the dictionaries keys and associated values: dictionary.items(); returned as a dictionary view where each element in dictionary view is a tuple which contains a key and its associated value
Term
keys method
Definition
Returns all the dictionaries keys as a sequence
Term
pop method
Definition
Returns value associated with specified key and removes that key-value pair from the dictionary: dictionary.pop(key, default); default is returned if key is not found
Term
popitem method
Definition
Returns a randomly selected key-value pair and removes that key-value pair from the dictionary; can use a multiple assignment where multiple variables are assigned at once: k, v = dictionary.popitem(), which returns a tuple
Term
values method
Definition
Returns all the dictionary's values as a sequence (list)
Term
Set
Definition
Object that stores a collection of data in same way as mathematical set
Term
Set function
Definition
Used to create a set - for empty set, call set()
; for non-empty set, call set(argument) where argument is an object that contains iterable elements i.e. list, tuple, string (if argument is a string, each character becomes a set element)
Term
Add method
Definition
Adds an element to a set: myset = set()
myset.add(1)
Term
Update method
Definition
Adds a group of elements to a set; argument must be a sequence containing iterable elements, and each of the elements is added to the set
Term
Remove and discard methods
Definition
Remove the specified item from the set; the item that should be removed can be passed to either method as an argument, the only difference between remove and discard is how they behave when the specified item is not found in the set:
remove method raises a KeyError exception;
discard method does not raise an exception
Term
Clear method
Definition
Clears all the elements of the set
Term
For loop of set
Definition
Format: for item in set:
-set is an unordered structure so print out may be in different order than the initial set
Term
Union of two sets
Definition
A set that contains all the elements of both sets; to find the union of two sets: set1.union(set2)
or set1 | set2
Term
Intersection of two sets
Definition
A set that contains only the elements found in both sets; to find the intersection of two sets: set1.intersection(set2) or set1 & set2
Term
Difference of two sets
Definition
A set that contains the elements that appear in the first set but do not appear in the second set; to find the difference of two sets: set1.difference(set2) or set1 - set2
Term
Symmetric difference of two sets
Definition
A set that contains the elements that are not shared by the two sets; to find the symmetric difference of two sets: set1.symmetric_difference(set2) or set1 ^ set2
Term
Issubset and issuperset methods
Definition
Subset: setA.issubset(setB) or setA <= setB
superset: setA.issuperset(setB) or setA >= setB
Term
Serialize an object
Definition
Convert an object to a stream of bytes that can easily be stored in a file
Term
Pickling
Definition
Serializing an object:
-Import the pickle module
-Open a file for binary writing:
outfile = open('file.dat', 'wb')
-Call the pickle.dump function
pickle.dump(object, file)
-Close the file
Term
Unpickling
Definition
-Import the pickle module
-Open a file for binary writing:
outfile = open('file.dat', 'rb')
-Call the pickle.load function
pickle.load(object, file)
-Close the file
Term
Procedural programming
Definition
Writing programs made of functions that perform specific tasks; most of the programs we've worked with thus far
Term
Object-oriented programming
Definition
Centered on creating objects
Term
Object
Definition
Entity that contains data and procedures; data contained in the object is known as data attributes (variables that reference data) and procedures that an object performs are known as methods - methods perform operations on the data attributes
Term
Encapsulation
Definition
Combining data and code into a single object
Term
Data hiding
Definition
Object’s data attributes are hidden from code outside the object
Term
Object resusability
Definition
The same object can be used in different programs
Term
Data attributes
Definition
Define the state of an object: clock has seconds, minutes, and hours
Term
Public methods
Definition
Allow external code to manipulate the object: setting an alarm
Term
Private methods
Definition
Used for object’s inner workings: incrementing seconds on clock
Term
Class
Definition
Code that specifies the data attributes and methods of a particular type of object
Term
Instance
Definition
An object created from a class
Term
Class definition
Definition
Set of statements that define a class’s methods and data attributes: class Class_name:
Term
Self parameter
Definition
Required in every method in the class – references the specific object that the method is working on:
Term
Initializer method
Definition
Automatically executed when an instance of the class is created; initializes object’s data attributes and assigns self parameter to the object that was just created:
def __init__ (self):
Term
Object's state
Definition
The values of the object’s attribute at a given moment
Term
__str__ method
Definition
Displays the object’s state; automatically called when the object is passed as an argument to the print function or when the object is passed as an argument to the str function
Term
Instance attribute
Definition
Belongs to a specific instance of a class; created when a method uses the self parameter to create an attribute
Term
Accessor methods
Definition
Return a value from a class’s attribute without changing it; safe way for code outside the class to retrieve the value of attributes; method usually starts with the word Get and are therefore sometimes called getters
Term
Mutator Methods
Definition
Store or change the value of a data attribute; method usually starts with the word Set and are therefore sometimes called setters
Term
UML diagram
Definition
Standard diagrams for graphically depicting object-oriented systems- general layout: box divided into three sections:
Top section: name of the class
Middle section: list of data attributes
Bottom section: list of class methods
Show inheritance by drawing a line with an open arrowhead from subclass to superclass
Term
Identifying classes in a problem
Definition
1) Get written description of the problem domain - domain is the context of the problem
2) Identify all nouns in the description, each of which is a potential class
3)Refine the list to include only classes that are relevant to the problem
Term
"Is a" relationship
Definition
Exists when one object is a specialized version of another object; specialized object has all the characteristics of the general object plus unique characteristics
Term
Inheritance
Definition
Used to create an “is a” relationship between classes; the new class inherits the members of the class it extends
Ex: class Car(Automobile):
The initializer method of a subclass calls the initializer method of the superclass and then initializes the unique data attributes and adds method definitions for unique methods
Term
Superclass (base class)
Definition
A general class
Term
Subclass (derived class)
Definition
A specialized class; essentially an extended version of the superclass; inherits attributes and methods of the superclass while new attributes and methods can be added
Term
Polymorphism
Definition
An object’s ability to take different forms; allows subclasses to have methods with the same names as methods in their superclasses; it gives the ability for a program to call the correct method depending on the type of object that is used to call it
Term
AttributeError exception
Definition
Raised when a method receives an object which is not an instance of the right class
Term
isinstance function
Definition
Determines whether object is an instance of a class
Term
Recursive function
Definition
A function that calls itself
Term
Depth of recursion
Definition
The number of times a function calls itself
Term
Direct recursion
Definition
When a function directly calls itself
Term
Indirect recursion
Definition
When function A calls function B, which in turn calls function A
Supporting users have an ad free experience!