Python Foundation Flashcards

1
Q

Return - string
Args - none
___________
returns a string with first letter capitalized and all other characters lowercased. It doesn’t modify the original string

A

string.capitalize()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Return - int
Args - (substring, start, end)
___________
searches the substring in the given string and returns how many times the substring is present in it. It also takes optional parameters start and end to specify the starting and ending positions in the string respectively.

A

string.count()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Return - True/False
Args - (suffix, start, end)
___________
returns True if a string ends with the specified suffix. If not, it returns False.

A

string.endswith()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Return - byte string
Args - (encoding=’UTF-8’,errors=’strict’)
___________
By default, encode() method doesn’t require any parameters.

It returns utf-8 encoded version of the string. In case of failure, it raises a UnicodeDecodeError exception.

However, it takes two parameters:

1) encoding - the encoding type a string has to be encoded to
2) errors - response when encoding fails.
There are six types of error response:

strict - default response which raises a UnicodeDecodeError exception on failure

ignore - ignores the unencodable unicode from the result

replace - replaces the unencodable unicode to a question mark ?

xmlcharrefreplace - inserts XML character reference instead of unencodable unicode

backslashreplace - inserts a \uNNNN espace sequence instead of unencodable unicode

namereplace - inserts a \N{…} escape sequence instead of unencodable unicode

A

string.encode()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Return - index
Args - (substring, start, end)
___________
returns the index of first occurrence of the substring (if found). If not found, it returns -1. Start and End args are optional.

A

string.find()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Return - formatted string with inputs
Args - (first input, second input, …)
___________
reads the type of arguments passed to it and formats it according to the format codes defined in the string. First value in given string is the argument it references and will substitute for in the given parameters, first number after colon is the number of total spaces allocated to the entire inputted argument, number after decimal with the f is the number of decimal places after the input number

A

“blah blah {0} blah blah {1:5.3f}”.format(‘input0’, ‘input2’)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Return - index
Args - (substring, start, end)
___________
returns the index of a substring inside the string (if found). If the substring is not found, it raises an exception

A

string.index()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Return - True/False
Args - none
___________
returns True if all characters in a string are digits. If not, it returns False

A

string.isdigit()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Return - concatenated string
Args - (iterable)
___________
provides a flexible way to concatenate string. It concatenates each element of an iterable (such as list, string and tuple) to the string and returns the concatenated string

A

separator = ‘, ‘

separator.join(someIterable)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Return - string
Args - (width, ‘optional fill char’)
___________
returns a left or right-justified string of a given minimum width.

A

string.ljust() and rjust()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Return - lowercased version of string
Args - none
___________
converts all uppercase characters in a string into lowercase characters and returns it.

A

string.lower()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Return - stripped string
Args - (‘char’) or ([char1, char2, …])
___________
removes characters from the leading left or right based on the argument (a string specifying the set of characters to be removed).

A

string.lstrip() and rstrip()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Return - stripped string
Args - (‘char’) or ([char1, char2, …])
___________
removes characters from both left and right based on the argument (a string specifying the set of characters to be removed).

The strip() returns a copy of the string with both leading and trailing characters stripped.

When the combination of characters in the chars argument mismatches the character of the string in the left, it stops removing the leading characters.
Similarly, when the combination of characters in the chars argument mismatches the character of the string in the right, it stops removing the trailing characters.

A

string.strip()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Return - 3-tuple
Args - (separator)
___________
splits the string at the first occurrence of the argument string and returns a tuple containing the part the before separator, argument string and the part after the separator.

The partition method returns a 3-tuple containing:

the part before the separator, separator parameter, and the part after the separator if the separator parameter is found in the string
string itself and two empty strings if the separator parameter is not found

A

string.partition()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Return - string
Args - (old substring, new substring, number of times you want it replaced with)
___________
returns a copy of the string where all occurrences of a substring is replaced with another substring.

A

string.replace()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Return - index
Args - (substring, start, end)
___________
returns the highest index of the substring (if found). If not found, it returns -1.

The rfind() method takes maximum of three parameters:

sub - It’s the substring to be searched in the str string.
start and end (optional) - substring is searched within str[start:end]

A

string.rfind()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Return - list of strings
Args - (separator, max # of splits desired)
___________
breaks up a string at the specified separator and returns a list of strings.

The split() method takes maximum of 2 parameters:

separator (optional)- The is a delimiter. The string splits at the specified separator.

If the separator is not specified, any whitespace (space, newline etc.) string is a separator.

maxsplit (optional) - The maxsplit defines the maximum number of splits.

The default value of maxsplit is -1, meaning, no limit on the number of splits.

A

string.split()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

Return - list of strings
Args - (separator, max # of splits desired)
___________
splits string from the right at the specified separator and returns a list of strings.

The rsplit() method takes maximum of 2 parameters:

separator (optional)- The is a delimiter. The rsplit() method splits string starting from the right at the specified separator.

If the separator is not specified, any whitespace (space, newline etc.) string is a separator.

maxsplit (optional) - The maxsplit defines the maximum number of splits.

The default value of maxsplit is -1, meaning, no limit on the number of splits.

A

string.rsplit()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

Return - boolean
Args - ( iterable )
___________
returns True if any element of an iterable is True. If not, any() returns False. If empty, returns returns False.

A

string.any()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

Return - tuples of (counter, iterable)
Args - ( iterable, optional start value )
___________
adds counter to an iterable and returns it (the enumerate object).

The enumerate() method takes two parameters:

iterable - a sequence, an iterator, or objects that supports iteration
start (optional) - enumerate() starts counting from this number. If start is omitted, 0 is taken as start.

A

enumerate( iterable, start=0 )

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

Return - an iteratOR
Args - ( function, iterable )
___________
constructs an iterator from elements of an iterable for which a function returns true.

filters the given iterable with the help of a function that tests each element in the iterable to be true or not.

A

filter()

The filter() function in Python is a built-in function that allows you to process an iterable and extract those items that satisfy a given condition

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

Return - map object
Args - ( function, iterable )
___________
applies a given function to each item of an iterable (list, tuple etc.) and returns a map of the results.

this map can then be wrapped by the list() method to create a list of the results, or wrapped by a set() method, etc

A

map()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

Return - slice object
Args - ( optional start, stop, optional step )
___________
creates a slice object representing the set of indices specified by range(start, stop, step).

The slice object is used to slice a given sequence (string, bytes, tuple, list or range) or any object which supports sequence protocol (implements __getitem__() and __len__() method).

A

slice()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

Return - sorted list
Args - ( iterable, optional reverse=True, optional function that serves as a key to the sort comparison )
___________
returns a sorted list from the given iterable.

A

sorted()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

Return - iterator of tuples
Args - ( 1st iterable, 2nd iterable, etc)
___________
take iterables (can be zero or more), makes iterator that aggregates elements based on the iterables passed, and returns an iterator of tuples.

A

zip()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

Return - none
Args - ( some list to add to end )
___________
extends the list by adding all items of a list (passed as an argument) to the end.

A

list1.extend(list2)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

Return - none
Args - ( index, value to insert )
___________
inserts an element to the list at a given index.

A

list.insert(index, element)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

Return - none
Args - ( value to insert )
___________
searches for the given element in the list and removes the first matching element.

A

list.remove(element)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
29
Q

Return - none
Args - ( value to find )
___________
finds the given element in a list and returns its position.

However, if the same element is present more than once, index() method returns its smallest/first position.

If not found, it raises a ValueError exception indicating the element is not in the list.

A

list.index(element)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
30
Q

Return - none
Args - ( value to count )
___________
counts how many times an element has occurred in a list and returns it.

A

list.count(element)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
31
Q

Return - none
Args - ( optional index to remove from the list )
___________
takes a single argument (index) and removes the item present at that index.

If the index passed to the pop() method is not in range, it throws IndexError: pop index out of range exception.

The parameter passed to the pop() method is optional. If no parameter is passed, the default index -1 is passed as an argument which returns the last item.

A

list.pop(index)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
32
Q

Return - none
Args - none
___________
reverses the elements of a given list.

A

list.reverse()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
33
Q

Return - none
Args - ( optional function that acts as key for the sort comparison, reverse = True/False )
___________
sorts the elements of a given list in a specific order - Ascending or Descending.

A

list.sort( key= … , reverse= … )

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
34
Q

Return - the new sorted list
Args - ( list, optional function that acts as key for the sort comparison, reverse = True/False )
___________
sorts the elements of a given list in a specific order - Ascending or Descending.

A

sorted( list, key= … , reverse= … )

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
35
Q

Return - returns an entirely new list (not a reference!)
Args - none
___________
if you need the original list unchanged when the new list is modified, you can use copy() method. This is called shallow copy.

A

new_list = list.copy()

~ same as ~

new_list = list[ : ]

~ same as ~

new_list = list( old_list )

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
36
Q

Return - none
Args - none
___________
removes all items from the list.

A

list.clear()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
37
Q

Return - boolean
Args - ( iterable )
___________
returns:
True if at least one element of an iterable is true
False if all elements are false or if an iterable is empty

A

any(iterable)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
38
Q

Return - boolean
Args - ( iterable )
___________
returns:
True - If all elements in an iterable are true
False - If any element in an iterable is false

A

all( iterable )

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
39
Q

Return - string
Args - ( object like a string, list, etc )
___________
returns a string containing printable representation of an object.

A

ascii( object )

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
40
Q

Return - a new iterable that passes the function
Args - ( function, iterable )
___________
filters the given iterable with the help of a function that tests each element in the iterable to be true or not.

A

filter( function, iterable )

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
41
Q

Return - iterator
Args - ( sets / tuples to turn into iterator, optional value that is the end of the sequence )
___________
creates an object which can be iterated one element at a time.

These objects are useful when coupled with loops like for loop, while loop.

A

iter( object, sentinel )

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
42
Q

Return - list
Args - ( opttional set / tuple / list / dict / etc )
___________
constructor creates a list in Python.

The list() constructor returns a mutable sequence list of elements.

If no parameters are passed, it creates an empty list
If iterable is passed as parameter, it creates a list of elements in the iterable

A

new_list = list( some optional iterable )

~ same as ~

new_list = [ ]

~ same as ~

new_list = list.copy( old list )

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
43
Q

Return - list of mapped results
Args - ( mapping function, iterable to be mapped )
___________
applies a given function to each item of an iterable (list, tuple etc.) and returns a list of the results.

A

map( function, iterable, … )

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
44
Q

Return - reversed list
Args - ( some sequence )
___________
returns the reversed iterator of the given sequence.

*if you don’t want anything returned, just do list.reverse()

A

reversed( sequence )

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
45
Q

sort() vs sorted() difference

A

sort() method sorts the list in-place, mutating the list indices, and returns None (like all in-place operations)

The sorted() function returns a new sorted list, leaving the original list unaffected

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
46
Q

reverse() vs reversed() difference

A

reverse() method reverses the list in-place, mutating the list indices, and returns None (like all in-place operations)

The reversed() function returns a new reversed list, leaving the original list unaffected

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
47
Q

a = [1,2,3,4,5,6,7,8]

a[1:4]

A

a = [1,2,3,4,5,6,7,8]
a[1:4]

returns [2,3,4]

indexes at 0 and does NOT include the last index

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
48
Q

a = [1,2,3,4,5,6,7,8]

a[1:4:2]

A

a = [1,2,3,4,5,6,7,8]

a[1:4:2]

returns [2, 4]

slices along increments of 2 starting at your first index listed

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
49
Q

a = [1,2,3,4,5,6,7,8]

a[ : : -1]

A

a = [1,2,3,4,5,6,7,8]

a[ : : -1]

returns [8, 7, 6, 5, 4, 3, 2, 1]

slices the list in reverse

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
50
Q

a = [1, 2, 3, 4, 5]

sliceObj = slice(1, 3)

a[sliceObj]

A

a = [1, 2, 3, 4, 5]

sliceObj = slice(1, 3)

a[sliceObj]

return [2, 3]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
51
Q

lst = [x ** 2 for x in range (1, 11) if x % 2 == 1]

meaning of parts

A

x ** 2 is output expression,
range (1, 11) is input sequence,
x is variable and
if x % 2 == 1 is predicate part.

52
Q

odd_square = [x ** 2 for x in range(1, 11) if x % 2 == 1]

A

odd_square = [x ** 2 for x in range(1, 11) if x % 2 == 1]
print odd_square

list contains square of all odd numbers from range 1 to 10

53
Q

output = [2 ** x for x in range(1, 9)]

A

list contains power of 2 from 1 to 8

54
Q

noprimes = [j for i in range(2, 8) for j in range(i*2, 50, i)]

primes = [x for x in range(2, 50) if x not in noprimes]

res = [10 * x + y for x in range(4) for y in range(3)]

A

list contains prime and non-prime in range 1 to 50

55
Q

print [x.lower() for x in [“A”, “B”, “C”]]

A

list for lowering the characters

56
Q

string = “my phone number is : 11122 !!”

extracted digits

A

numbers = [x for x in string if x.isdigit()]

list which extracts number

57
Q
a = 5
table = [[a, b, a * b] for b in range(1, 11)]

print(“\nMultiplication Table”)
for i in table:
print i

A
a = 5
table = [[a, b, a * b] for b in range(1, 11)]

print(“\nMultiplication Table”)
for i in table:
print i

A list of list for multiplication table

58
Q

lst = filter(lambda x : x % 2 == 1, range(1, 20))

print lst

A
#  filtering odd numbers
lst = filter(lambda x : x % 2 == 1, range(1, 20))
print lst
59
Q

We can use FILTER function to filter a list based on some condition provided as a ___________ as first argument and list as second argument.

A

lambda expression

60
Q

lst = filter(lambda x : x % 5 == 0,
[x ** 2 for x in range(1, 11) if x % 2 == 1])
print lst

A
#  filtering odd square which are divisble by 5
lst = filter(lambda x : x % 5 == 0, 
      [x ** 2 for x in range(1, 11) if x % 2 == 1])
print lst
61
Q

lst = filter((lambda x: x < 0), range(-5,5))

print lst

A
#   filtering negative numbers
lst = filter((lambda x: x < 0), range(-5,5))
print lst
62
Q

print reduce(lambda a,b: a if (a > b) else b, [7, 12, 45, 100, 15])

A
#  implementing max() function, using
print reduce(lambda a,b: a if (a > b) else b, [7, 12, 45, 100, 15])
63
Q

“in” operator

A

“in” operator: This operator is used to check if an element is present in the list or not. Returns true if element is present in list else returns false.

ex) lis = [1, 4, 3, 2, 5]
if 4 in lis:
print ….

64
Q

“not in” operator

A

“not in” operator : This operator is used to check if an element is not present in the list or not. Returns true if element is not present in list else returns false.

ex) lis = [1, 4, 3, 2, 5]
if 4 not in lis:
print ….

65
Q

+ operator

A

“+” operator :- This operator is used to concatenate two lists into a single list.

66
Q
  • operator
A

“*” operator :- This operator is used to multiply the list “n” times and return the single list.

67
Q

del[a : b]

A

a inclusive, b exclusive

del[a : b] :- This method deletes all the elements in range starting from index ‘a’ till ‘b’ mentioned in arguments.

68
Q

Return - none
Args - none
___________
Clears the dictionary

A

dict.clear()

69
Q

Return - shallow copy of dictionary
Args - none
___________
returns a shallow copy of the dictionary.

A

dict.copy()

70
Q

Return - dictionary (with keys but no values)
Args - iterable
___________
returns a new dictionary with the given sequence of elements as the keys of the dictionary.

If the value argument is set, each element of the newly created dictionary is set to the provided value.

A

dict.fromkeys(keys)

keys = (‘a’, ‘b’, ‘c’, ‘d’, ‘e’)
custom_dict = dict.fromkeys(keys, 1)
# Result: {‘a’: 1, ‘b’: 1, ‘c’: 1, ‘d’: 1, ‘e’: 1}

71
Q

Return - dictionary value
Args - ( key, optional value to return if key not found)
___________
returns the value for the specified key if key is in dictionary.

A

dict.get( ‘key name’ )

Unlike direct indexing (e.g., car[“model”]), using get() won’t raise a KeyError if the key is missing.

72
Q

Return - view object of key-val pairs
Args - none
___________
returns a view object that displays a list of dictionary’s (key, value) tuple pairs.

A

dict.items()

73
Q

Return - view object of list of keys
Args - none
___________
returns a view object that displays a list of all the keys in the dictionary

A

dict.keys()

74
Q

Return - value at specified key
Args - key
___________
removes and returns an element from a dictionary having the given key.

A

dict.pop( ‘key’ )

75
Q

Return - view object of list of values
Args - none
___________
method returns a view object that displays a list of all the values in the dictionary.

A

dict.values()

76
Q

Return - none
Args - another dict or some other iterable of key-val pairs (like an iterable of tuples)
___________
adds element(s) to the dictionary if the key is not in the dictionary. If the key is in the dictionary, it updates the key with the new value.

A

dict.update( dict or iterable ]

77
Q

Return - bool
Args - iterable
___________
returns True if any element of an iterable is True. If not, returns False.

A

dict.any( iterable )

78
Q

Return - bool
Args - iterable
___________
method returns True when all elements in the given iterable are true. If not, it returns False.

A

dict.all( iterable )

79
Q

Return - none
Args - iterable of tuples
___________
constructor creates a dictionary in Python.

A

dict( [ iterable of tuples ] )

80
Q

Dictionary?

A

In python, dictionary is similar to hash or maps in other languages. It consists of key value pairs. The value can be accessed by unique key in the dictionary.

81
Q

Create a new dictionary

A
# Create a new dictionary 
d = dict() 
# or you can do 
d = {}
82
Q

Add a key - value pairs to dictionary

A
# Add a key - value pairs to dictionary
d['xyz'] = 123
d['abc'] = 345

returns {‘xyz’: 123, ‘abc’: 345}

83
Q

check if key exist

A
# check if key exist
print('xyz' in d)
84
Q

delete the key-value pair

A
# delete the key-value pair
del d['xyz']
85
Q

Dict.fromkeys()

A

Dict.fromkeys(): Create a new dictionary with keys from seq and values set to value.

keys = (‘a’, ‘b’, ‘c’, ‘d’, ‘e’)
custom_dict = dict.fromkeys(keys, 1)
# Result: {‘a’: 1, ‘b’: 1, ‘c’: 1, ‘d’: 1, ‘e’: 1}

86
Q

Dict.get()

A

Dict.get(): For key, returns value or default if key not in dictionary

Dict.get(key, default=None)

Unlike direct indexing (e.g., car[“model”]), using get() won’t raise a KeyError if the key is missing.

87
Q

Dict.has_key()

A

Dict.has_key(): Returns true if key in dictionary dict, false otherwise

88
Q

Dict.items()

A

Dict.items(): Returns a list of dict’s (key, value) tuple pairs

89
Q

Dict.setdefault()

A

Dict.setdefault(): Set dict[key]=default if key is not already in dict

90
Q

Dict.update()

A

Dict.update(): Adds dictionary dict2’s key-values pairs to dict

The update() method takes either a dictionary or an iterable object of key-value pairs (usually tuples) as its parameter.

91
Q

dic = {“A”:1, “B”:2}

How would we access the above values?

A

dic = {“A”:1, “B”:2}
print(dic.get(“A”))
print(dic.get(“C”))
print(dic.get(“C”,”Not Found ! “))

92
Q

How to merge two dictionaries using update() ?

A

Using the method update()

By using the method update() in Python, one list can be merged into another. But in this, the second list is merged into the first list and no new list is created. It returns None.
Example:
# Python code to merge dict using update() method
def Merge(dict1, dict2):
    return(dict2.update(dict1))
# Driver code
dict1 = {'a': 10, 'b': 8}
dict2 = {'d': 6, 'c': 4}
# This return None
print(Merge(dict1, dict2))
# changes made in dict2
print(dict2)
93
Q

How to merge two dictionaries using ** ?

A

Using ** in Python

# Python code to merge dict using a single 
# expression
dict1 = {'a':1, 'b':2}
dict2 = {'c':3, 'd':4}

dict3 = {**dict1, **dict2}
_________________

This is generally considered a trick in Python where a single expression is used to merge two dictionaries and stored in a third dictionary. The single expression is **. This does not affect the other two dictionaries. ** implies that the argument is a dictionary. Using ** [double star] is a shortcut that allows you to pass multiple arguments to a function directly using a dictionary. For more information refer **kwargs in Python. Using this we first pass all the elements of the first dictionary into the third one and then pass the second dictionary into the third. This will replace the duplicate keys of the first dictionary.

94
Q

Define a child class Shuttle that inherits from the parent class Rocket

A
class Shuttle( Rocket ):
        def \_\_init\_\_(self, x=0, y=0, flights_completed=0):
            super().\_\_init\_\_(x, y) 
            self.flights_completed = flights_completed
95
Q

General template for a child class inheriting from parent class

A

class NewClass(ParentClass):

    def \_\_init\_\_(self, arguments_new_class, 
                         arguments_parent_class):
        super().\_\_init\_\_(arguments_parent_class)
96
Q

Create several shuttles and rockets, with random positions (instantiate multiple objects at once)

Shuttles have a random number of flights completed.

A
class Shuttle(Rocket):
    # Shuttle simulates a space shuttle, which is really
    #  just a reusable rocket.
    def \_\_init\_\_(self, x=0, y=0, flights_completed=0):
        super().\_\_init\_\_(x, y)
        self.flights_completed = flights_completed

##############

shuttles = []
for x in range(0,3):
    x = randint(0,100)
    y = randint(1,100)
    flights_completed = randint(0,10)
    shuttles.append(Shuttle(x, y, flights_completed))
rockets = []
for x in range(0,3):
    x = randint(0,100)
    y = randint(1,100)
    rockets.append(Rocket(x, y))
97
Q

What’s a module? How does this relate to your knowledge of classes?

A

Now that you are starting to work with classes, your files are going to grow longer. Python allows you to save your classes in another file and then import them into the program you are working on.

When you save a class into a separate file, that file is called a module. You can have any number of classes in a single module.

98
Q

Create a new module based on the class Rocket(). Then create a new file that imports this module. What does this look like?

(The first line tells Python to look for a file called rocket.py. It looks for that file in the same directory as your current program)

(When Python finds the file rocket.py, it looks for a class called Rocket. When it finds that class, it imports that code into the current file, without you ever seeing that code)

A

Save as rocket.py

class Rocket():
    # Rocket simulates a rocket ship for a game,
    #  or a physics simulation.
    def \_\_init\_\_(self, x=0, y=0):
        # Each rocket has an (x,y) position.
        self.x = x
        self.y = y
\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_
# This is a new file:
# Save as rocket_game.py

from rocket import Rocket

rocket = Rocket()
print(“The rocket is at (%d, %d).” % (rocket.x, rocket.y))

99
Q

You can also have multiple classes within the same module file. How would you write this for both the Rocket() and Shuttle() classes?

A

Save as rocket.py

class Rocket():
    # Rocket simulates a rocket ship for a game,
    #  or a physics simulation.
    def \_\_init\_\_(self, x=0, y=0):
        # Each rocket has an (x,y) position.
        self.x = x
        self.y = y
class Shuttle(Rocket):
    # Shuttle simulates a space shuttle, which is really
    #  just a reusable rocket.
    def \_\_init\_\_(self, x=0, y=0, flights_completed=0):
        super().\_\_init\_\_(x, y)
        self.flights_completed = flights_completed
\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_
# Save as rocket_game.py

from rocket import Rocket, Shuttle

rocket = Rocket()
shuttle = Shuttle()
100
Q

List 4 different ways for how you can import modules.

A

from module_name import ClassName/function
________
import module_name
#After this, classes are accessed using dot notation:
#module_name.ClassName
________
import module_name as local_module_name
#You can access this now using the alias given
________
from module_name import *

This is not recommended, for a couple reasons. First of all, you may have no idea what all the names of the classes and functions in a module are. If you accidentally give one of your variables the same name as a name from the module, you will have naming conflicts. Also, you may be importing way more code into your program than you need.

101
Q

You can also store functions in a module. How would you go about writing this module and using it?

A
# Save as multiplying.py
def double(x):
    return 2*x
def triple(x):
    return 3*x
def quadruple(x):
    return 4*x
\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_
# you can import it and use it this way

from multiplying import double, triple, quadruple

print(double(5))
print(triple(5))
print(quadruple(5))

\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_
# or you can import and use it this way:

import multiplying

print(multiplying.double(5))
print(multiplying.triple(5))
print(multiplying.quadruple(5))
\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_
# or you can alsp import and use it this way:

from multiplying import *

print(double(5))
print(triple(5))
print(quadruple(5))

102
Q

What are the PEP8 guidelines for writing names for classes and modules?

A

Modules should have short, lowercase names. If you want to have a space in the module name, use an underscore.

Class names should be written in CamelCase, with an initial capital letter and any new word capitalized. There should be no underscores in your class names.

This convention helps distinguish modules from classes, for example when you are writing import statements.

103
Q

How is the dot . operator overloaded?

A

The dot . operator is overloaded in Python to mean both package member and object member access. You are familiar with this already:

import numpy as np
np.array([1,2,3])

versus

import math
math.log(3000)

This is a common point of confusion when reading code. When we see a.f(), we don’t know whether that function f is a member of the package identified by a or an object referred to by a.

104
Q

How do you do the most basic File Opening, saving to a variable the text file, printing the text, and closing that file?

A
data_file = open('data.txt')
# notice that data_file is an instance of this io class!
# we can access the methods of this class like usual
# with the dot operator
text = data_file.read()
# you need to always do this
data_file.close()
105
Q

What’s another way to open a text file and print each line, line-by-line using for loops?

A

data_file = open(‘data.txt’)

for line in data_file:
print(line)

notice how data_file is an iterable!

106
Q

When saving the text file opened using the open method to a variable, what is the type of that variable?

A

It is an instance of the I/O class. Specifically it is an iterable (from which you can loop over too!)

107
Q

What is the number of characters in our first line if our text file is given below? What is the number of total characters? What characters are unseen? How do we get rid of this first extra unseen character when reading in our text file?:

10 20 30
14 40 70

A

There are a total of 17 characters (numbers, spaces, and new line char). The first line contains 9 characters, the second line contains 8 characters. At the end of the first line there is a new line character. We can use the strip() method to get rid of extra new line character in each line, since each line is of the type string.

108
Q

What does the second argument to the open() function do?

A

It indicates the mode in which the file should be opened.

109
Q

Suppose the file output.txt initially has one line in it containing three letters: “abc”. What is in the file after the program below runs?

with open(‘output.txt’, ‘w’) as f:

f. write('def')
f. write('ghi')
A

defghi

it overwrites the previous stuff in the file, and also no new line characters are inputted

110
Q

The following program tries to print the contents of a file called file.txt. See if you can fix it!

my_file = open(‘file.txt’)
print(my_file)

A

my_file = open(‘file.txt’)
my_file = my_file.read()
print(my_file)

111
Q
# This program tries to write the word "hi" to
# a file named file.txt. See if you can fix it!
with open('file.txt', 'w') as output_file:
    output_file.print('hi')
A
# This program tries to write the word "hi" to
# a file named file.txt. See if you can fix it!
with open('file.txt', 'w') as output_file:
    output_file.write('hi')
112
Q

How would you open a file and not rewrite over it, but append new text to it?

A

output_file = open(‘output_file.txt’, ‘a’)

output_file.write(‘\nnew stuff’)

output_file.close()

113
Q

What do these optional set parameters do?

"r" - 
"x" - 
"t" - 
"b" -
"+" - 
"w" - 
"a" -
A

“r” - opens file for reading
“x” - create a new file, don’t create if already exist
“t” - want to treat file as text and not binary
“b” - treat file as binary
“+” - for reading and writing (adds the one that is
missing)
“w” - opens a file for write mode, overwrites it if exists
otherwise if it doesn’t exist it creates one
“a” - opens a file for appending at the end of the file.
Creates a new file if it doesn’t exist.

You can also mix and match and combine them

114
Q

What is pickling?

A

The pickle module implements a fundamental, but powerful algorithm for serializing and de-serializing a Python object structure.

Pickling - is the process whereby a Python object hierarchy is converted into a byte stream, and Unpickling - is the inverse operation, whereby a byte stream is converted back into an object hierarchy.

Pickling (and unpickling) is alternatively known as serialization, marshalling, or flattening.

115
Q

Do we need to use binary ‘b’ mode when pickling?

A

Yes, we always need to use ‘b’ mode when pickling.

116
Q

______ is used for serializing and de-serializing Python object structures, also called marshalling or flattening. Serialization refers to the process of converting an object in memory to a byte stream that can be stored on disk or sent over a network. Later on, this character stream can then be retrieved and de-serialized back to a Python object.

A

Pickle is used for serializing and de-serializing Python object structures, also called marshalling or flattening. Serialization refers to the process of converting an object in memory to a byte stream that can be stored on disk or sent over a network. Later on, this character stream can then be retrieved and de-serialized back to a Python object.

117
Q

What does f.read() do?

A

reads the entire file into memory and returns an individual string

118
Q

What does f.readline() do?

A

reads the current line into memory, and returns a string of that line

119
Q

What does f.readlines() do?

A

reads the whole file into memory, parses it into lines, and returns a list full of strings out of those lines

***very memory intensive!!!

120
Q

What type of object does the open() function return?

A

A file object (which is also an iterable btw)

121
Q

After opening a file and saving it with a variable name, how do we write to that file?

file = open(“testfile.txt”,”w”)

A

Use the write() method:

file = open(“testfile.txt”,”w”)

file.write(“Hello World”)

122
Q

After opening a file and saving it with a variable name, how do we write MULTIPLE LINES of text to that file?

file = open(“testfile.txt”,”w”)

A

Save the text as strings in a list and then use the writelines() method:

fh = open(“hello.txt”,”w”)

lines_of_text = [“One line of text here”, “and another line here”, “and yet another here”, “and so on and so forth”]

fh. writelines(lines_of_text)
fh. close()

123
Q

Name 3 advantages of saving a file in JSON format over pickling it to BINARY format?

A

JSON advantages:

1) Standardized / Language Independent
2) Easily readable by humans (binary file isn’t)
3) More secure + faster

124
Q

What are the 3 main pickle methods?

A

string_of_data = pickle.load(file_name)

string_of_data.append(some_new_string)

pickle.dump(string_of_data, file_name)

125
Q

How can you work with 2 files at the same time?
How would you read from the first file and write the reversed text to the second file?

d_path = ‘dog_breeds.txt’
d_r_path = ‘dog_breeds_reversed.txt’

A
d_path = 'dog_breeds.txt'
d_r_path = 'dog_breeds_reversed.txt'
with open(d_path, 'r') as reader, open(d_r_path, 'w') as writer:
    dog_breeds = reader.readlines()
    writer.writelines(reversed(dog_breeds))