You are on page 1of 22

COP3035 Exam

Study online at quizlet.com/_6fn0vj

1. 1. Which of the following commands will create a list? d) all of the mentioned
a) list1 = list()
b) list1 = [ ]
c) list1 = list([1, 2, 3])
d) all of the mentioned
2. 2. Circle the numeric data types in python? a) int
a) int b) float
b) float
c) string
d) list
3. 2. What is the result when we execute list("hello")? a) ['h', 'e', 'l', 'l', 'o'].
a) ['h', 'e', 'l', 'l', 'o'].
b) ['hello'].
c) ['llo'].
d) ['olleh'].
4. 3. Suppose listExample is ['h','e','l','l','o'], what is len(listExample)? a) 5
a) 5
b) 4
c) None
d) Error
5. 3. What does alex.forward(-100) mean in Turtle Programming when you want the turtle b) alex moves backward by 100 units
"Alex" to
be moved?

a) alex moves forward by 100 units


b) alex moves backward by 100 units
c) alex turn left by 100 degree
d) alex turn right by 100 degree
6. 4. Suppose list1 is [4, 2, 2, 4, 5, 2, 1, 0], Which of the following is correct syntax for d) all of the mentioned
slicing
operation?
a) print(list1[0])
b) print(list1[:2])
c) print(list1[:-2])
d) all of the mentioned
7. 4. Which one of the following numeric data types does not support typical numeric c) complex
operations?
a) int
b) float
c) complex
d) long
8. 5. Circle the sequence data types in python? 5. Circle the sequence data types in
a) string python?
b) list a) string
c) tuple b) list
d) dictionary c) tuple
9. 5. Suppose list1 is [2, 33, 222, 14, 25], What is list1[-1]? c) 25
a) Error
b) None
c) 25
d) 2
10. 6. Suppose list1 is [2, 33, 222, 14, 25], What is list1[:-1] ? a) [2, 33, 222, 14].
a) [2, 33, 222, 14].
b) Error
c) 25
d) [25, 14, 222, 33, 2].
11. 6. Which of the following is immutable? A) string
a) string
b) list
c) dictionary
d) set
12. 7. In turtle programming, turning 30 to the left will leave you facing in the same direction as a) True
turning 330 to the right?

a) True
b) False
13. 7. Which of the following is a Python tuple? b) (1, 2, 3)
a) [1, 2, 3]
b) (1, 2, 3)
c) {1, 2, 3}
d) {}
14. 8. Suppose t = (1, 2, 4, 3), which of the following is incorrect? b) t[3] = 45
a) print(t[3])
b) t[3] = 45
c) print(max(t ))
d) print(len(t ))
15. 8. Which of the following will make alex to go at slowest speed? b) alexa.speed(1)
a) alex.speed(0)
b) alex.speed(1)
c) alex.speed(10)
16. 9. Which of the following turtle methods leaves an impression of the turtle methods? c) stamp
a) left
b) right
c) stamp
d) shape
17. 9. Which of these about a set is not true? d) Immutable data type
a) Mutable data type
b) Allows duplicate values
c) Data type with unordered values
d) Immutable data type
18. 10. In python 3, the statement - print "Hello, World!" - will run without any error? b) False
a) True (HINT: Use print ("Hello,
b) False World!"))
19. 10. What is the output for the following code? c) 4

nums = set([1,1,2,3,3,4,4])

print(len(nums))

a) 7
b) Error, invalid syntax for formation of set
c) 4
d) 8
20. 11. If a={5,6,7,8}, which of the following statements is false? d) a[2]=45
a) print(len(a))
b) print(min(a))
c) a.remove(5)
d) a[2]=45
21. 11. Multi-line comments begin and end with three #s in python? b) False
a) True (HINT: Use """ comments """).
b) False
22. 12. Circle the true statements for python? b) Python supports dynamic
a) Python supports strong typing typing
b) Python supports dynamic typing
c) 2+"six" will not give any error
23. 12. If a={5,6,7}, what happens when a.add(5) is executed? b) a={5,6,7}
a) a={5,5,6,7}
b) a={5,6,7}
c) Error as there is no add function for set data type
d) Error as 5 already exists in the set
24. 13. What would be the output of int(6.3)? b) 6
a) 5
b) 6
c) 7
d) 8
25. 13. Which of the following statements create a dictionary? d) All of the mentioned
a) d = {}
b) d = {"john":40, "peter":45}
c) d = {40:"john", 45:"peter"}
d) All of the mentioned
26. 14. Circle the functions that are used for creating a range of integers? a) range()
a) range() b) xrange()
b) xrange()
c) prange()
d) mrange()
27. 14. Suppose d = {"john":40, "peter":45}, to delete the entry for "john" what command do we c) del d["john"].
use
a) d.delete("john":40)
b) d.delete("john")
c) del d["john"].
d) del d("john":40)
28. 15. If d is a valid dictionary, then circle the valid operations? a) d.keys()
a) d.keys() b) d.values()
b) d.values() c) d.items()
c) d.items()
d) d.reverse()
29. 15. Suppose d = {"john":40, "peter":45}. To obtain the number of entries b) len(d)
in dictionary which
command do we use?
a) d.size()
b) len(d)
c) size(d)
d) d.len()
30. 16. Suppose d = {"john":40, "peter":45}, what happens when we try to c) Since "susan" is not a key in the set, Python raises a
retrieve a value using the KeyError exception
expression d["susan"]?

a) Since "susan" is not a value in the set, Python raises a KeyError


exception
b) It is executed fine and no exception is raised, and it returns None
c) Since "susan" is not a key in the set, Python raises a KeyError
exception
d) Since "susan" is not a key in the set, Python raises a syntax error
31. 17. Both mutable and immutable objects can be changed in the called b) False
function in python?
a) True
b) False
32. 17. Which of the following statements are true? d) All of the mentioned

a) When you open a file for reading, if the file does not exist, an error
occurs
b) When you open a file for writing, if the file does not exist, a new file
is created
c) When you open a file for writing, if the file exists, the existing file is
overwritten with the
new file
d) All of the mentioned
33. 18. If a module is executed directly, the value of the global variable a) True
__name__ will be
"__main__"?
a) True
b) False
34. 18. To open a file c:\scores.txt for reading, we use b) infile = open("c:\\scores.txt", "r")

a) infile = open("c:\scores.txt", "r")


b) infile = open("c:\\scores.txt", "r")
c) infile = open(file = "c:\scores.txt", "r")
d) infile = open(file = "c:\\scores.txt", "r")
35. 19. Arguments with default values can appear at the start of the b) False
arguments list of a function?
a) True
b) False
36. 19. To read the next line of the file from a file object infile, we use c) infile.readline()

a) infile.read(2)
b) infile.read()
c) infile.readline()
d) infile.readlines()
37. 20. Given: a) i = 1
for i in range(1, 10): while (i < 10)
print(i) print(i)
Which one of the following is the correct implementation using "while" loop for the i=i+1
above? Please circle.

a) i = 1
while (i < 10)
print(i)
i=i+1

b) i = 1
while (i <= 10)
print(i)
i=i+1
38. 20. The readlines() method returns b) a list of lines
a) str
b) a list of lines
c) a list of single characters
d) a list of integers
39. 21. What is Instantiation in terms of OOP terminology? d) Creating an instance of class
a) Deleting an instance of class
b) Modifying an instance of class
c) Copying an instance of class
d) Creating an instance of class
40. 21. What will the following produce? b. False
>>> 1.1 * 3.0 == 3.3 (HINT: 3.3000000000000003)
a. True
b. False
41. 22. When will the else part of try-except-else be executed? c) when no exception occurs
a) always
b) when an exception occurs
c) when no exception occurs
d) when an exception occurs in to except block
42. 22. Which one of these provide a set of recommendations about how to write readable b. PEP 8
Python programs?
a. PPP
b. PEP 8
c. Jython
d. None of the above
43. 23. What are the modes in which we can run python code? Circle all that apply. a. Normal mode
a. Normal mode b. Interpreted mode
b. Interpreted mode
c. Infinite mode
d. All of the above
44. 23. When is the "finally" block executed? d) always

a) when there is no exception


b) when there is an exception
c) only if some condition that has been specified is satisfied
d) always
45. 24. What is the output of the following code? b) __main__

class Demo:
def __init__(self):
pass

def test(self):
print(__name__)

obj = Demo()
obj.test()

a) Exception is thrown
b) __main__
c) Demo
d) test
46. 24. Which one of these is a Fibonacci series? b. 1,2,3,5,8,11
a. 1,2,5,6,7,8
b. 1,2,3,5,8,11
c. 1,2,3,4,5,6
d. None of the above
47. 25. What happens when '1' == 1 is executed? b) we get a False
a) we get a True
b) we get a False
c) a TypeError occurs
d) a ValueError occurs
48. Basic Data Types are comprised of: Numeric & Sequence Data Types
49. Built-in constants There are a few built-in constants defined by the standard library:

True: true value of a bool type.

False: false value of a bool type.


50. Class Owned by the class as a whole
Attributes
All class instances share the same value for it

Called "static" variables in some languages

Good for (1) class-wide constants and (2) building counter of how many instances of the class have been made

Because all instances of a class share one copy of a class attribute, when any instance changes it, the value is
changed for all instances

Class attributes are defined within a class definition and outside of any method

Since there is one of these attributes per class and not one per instance, they're accessed via a different notation:

Access class attributes using self.__class__.name notation -- This is just one way to do this & the safest in general.
51. Create an import turtle #turtle librarywn = turtle.Screen() #wn is an instance. Screen is a class for graphic window.alex =
example of a turtle.Turtle() #alex is the turtle's name. An instance of the
turtle class.alex.forward(150)alex.left(90)alex.forward(75)alex.salary = 50000 #alex has an attribute salary whose value is
program 50000.print(alex.salary)turtle.done()
52. Create a wn = turtle.Screen()
window in
turtle
programming
53. Creating an class Circle
instance for
the class Data Fields:
radius is ____

Methods:
getArea

Circle Object 1

Data Fields:
radius is 10

Circle Object 2

Data Fields:
radius is 25
54. Creating a s1 = 'This is a string!'
string
s2 = "Python is so awesome."
55. Data Attributes Variable owned by a particular instance of a class

Each instance has its own value for it

These are the most common kind of attribute

Data attributes are created and initialized by an __init__() method.

Simply assigning to a name creates the attribute


Inside the class, refer to data attributes using self
for example, self.full_name
56. Define a class class car
4 wheels...

subclass volvo
other attributes?

Class
- Special data type which defines how to build a certain kind of object
- Data items are shared by all instances

Instances
- Objects that are created which follow the definition given inside of a class
57. Define a turtle named Tess Tess = turtle.Turtle()
and its pensize Tess.pensize(5)
58. Dict Dict: Hash tables, maps a set of keys to arbitrary objects

Creating a Word Dictionary:

Student = {
"First Name: "John",
"Last Name": "Doe",
"Age": 20
}
59. Difference between input() raw_input()
and raw_input() Asks the user for a string of input, and returns the string.

If you provide an argument, it will be used as a prompt.

input()
Uses raw_input() to grab a string of data, but then tries to evaluate the string as if it were a Python
expression.
Returns the value of the expression.

Dangerous - don't use it.


60. Disadvantage of a Set ...
61. Disadvantages of a List Data is mutable, so you shouldn't use it if you want things stored permanently
62. Disadvantages of (i) Dictionaries are unordered. In cases where the order of the data is important.
Dictionaries
(ii) Take up a lot more space than other data structures. The amount of space occupied increases
drastically when there are many Python Dictionary keys.
63. Disadvantages of using a Tuple * You can't add an element but in a list you can

* You can't sort a tuple but in a list you can

* You can't delete an element but you can in a list

* You can't replace an element but you can in a list


64. Example of providing control flows for num in range(10,20):
if num%2 == 0:
continue
for i in range(3,num):
if num%i == 0:
break
else:
print num, 'is a prime number'
65. Explain function implementation with an example def sumProd(x,y):
answer = x + y
print answer

x = input("enter the first number: ")


y = input("enter the second number: ")

sumProd(x,y)
66. for loop for var in sequence:
statements
67. Formatting with the format method print("Your total Correct is: {} ".format(Correct))

print("Your total Incorrect is: {} ".format(Incorrect))


68. f.read() Returns the entire contents of a file as a string.

Provide an argument to limit the number of characters you pick up.


69. f.readline() One by one, returns each line of a file as a string (ends with a newline).

End-of-file reached when return string is empty.


70. How are format strings constructed? print("Sammy the {} has a pet {}!".format(Variable1, Variable2))
71. How do you change 1 letter in a string? text = 'abcdefg'
new = list(text)
new[6] = 'W'
''.join(new)
72. How do you close a file? f.close()
73. How do you create, access, and modify a Dictionary? Create:

d1 = {}

d2 = dict() # both empty

d3 = {"Name": "Susan", "Age": 19, "Major": "CS"}

d4 = dict(Name="Susan", Age=19, Major="CS")

d5 = dict(zip(['Name', 'Age', 'Major'], ["Susan", 19, "CS"]))

d6 = dict([('Age', 19), ('Name', "Susan"), ('Major', "CS")])

Access:

DictionaryName[KeyValue]

DictName.has_key(KeyValue)
- Returns T / F

DictName.keys()
- Returns a list of keys

DictName.items()
- Returns list of key:value pairs

DictName.values()
- Returns a list of values

Modify:

Dictname[KeyValue] = Value

del Dictname[KeyValue]

Dictname.clear()
74. How do you create, access, and modify a List? Create:

mylist1 = []

mylist2 = [expression1, expression2, ...]

mylist3 = [expression for variable in sequence]

mylist1 = list()

mylist2 = list(sequence)

mylist3 = list(expression for variable in sequence)

Access:

mylist[index]

mylist.index(Value that your looking for the index)

Modify:

mylist.insert(values)

mylist.append(value)
- Add element to existing list

mylist.extend(value)
- Add all of the items from another list

mylist.reverse()

mylist.sort()
75. How do you create, access, and modify a Set? Create:

myset = set(sequence)
myset2 = {expression for variable in sequence}

Access:

s1 = set('abracadabra')
s2 = set('bard')
s1 >= s2
- Returns True
s1 > s2
- Returns True
s1 <= s2
- Returns False

Union:
set | other | ...
- Return a new set with elements from the set and all others.

Intersection:
set & other & ...
- Return a new set with elements common to the set and all others.

Difference:
set - other - ...
- Return a new set with elements in the set that are not in the others.

Symmetric Difference:
set ^ other
- Return a new set with elements in either the set or other but not both.

Modify:

s.copy()
- returns a shallow copy of the set s.
s.isdisjoint(other)
- returns True if set s has no elements in common with set other.
s.issubset(other)
- returns True if set s is a subset of set other.

len, in, and not in are also supported.


76. How do you create, access, and modify a Tuple? Create:
t1 = (1, 2, 3, 4)
t2 = "a", "b", "c", "d"
t3 = ()
t4 = ("red", )

Access:
TupleName[index]

s = "Susan", 19, "CS" # tuple packing >>> name, age,

major = s # tuple unpacking

Modify:

Tuples are immutable


77. How do you define a function? def somefunction ():
..........
..........
..........
78. How do you handle exceptions? while True:
try:
x = int(raw_input("Enter a number: "))

except ValueError:
print("Ooops !! That was not a valid number. Try again.")

except (TypeError, IOError) as e:


print(e)

else:
print("No errors encountered!")

finally:
print("We may or may not have encountered errors...")
79. How do you import a file import somefile
- everything from somefile gets imported

from somefile import *


- everything from somefile gets imported

from somefile import className


className.method("abc")# imported

myFunction(34)# Not imported


80. How do you import a module from __name__ import some_function
81. How do you import Matplotlib? import matplotlib.pyplot as plt
82. How do you import numpy? import numpy as np
83. How do you import scipy? from scipy import special
84. How do you make: 1. #
1. Single-line 2. """ .... """
Comment
2. Multi-line Comment
85. How do you remove ''.join(str.split())
white space in a
string?
86. How do you use the import sys
regular expression? import re

pattern = "Fred"

regexp = re.compile(pattern) # prepares the regular expression

for line in sys.stdin:


(compare line in regEx)

if RegEx matches:
sys.stdout.write(line)
87. How is a program By an interpreter: The interpreter translates Python code into bytecode, and this bytecode is executed by
executed? the Python VM (similar to Java).
88. if statement (include a=1
elif) b=0
c=2
if a > b:
if a > c:
print "a is greatest"
else:
print "c is greatest"
elif b > c:
print "b is greatest"
else:
print "c is greatest"
89. Is a list mutable in a) True
python?
a) True
b) False
90. Lists as Queues Lists can be used as queues natively since insert() and pop() both support indexing. However, while
appending and popping from a list are fast, inserting and popping from the beginning of the list are slow.

Use the special deque object from the collections module.

from collections import deque

queue = deque([35, 19, 67])

queue.append(42) queue.append(23)
queue.popleft() #Returns 35
queue.popleft() #Returns 19 queue #Returns deque([67, 42, 23])
91. Loop over the file for line in f:
object print(line)
92. Matplotlib We're going to continue our discussion of scientific computing with matplotlib.

Matplotlib is an incredibly powerful (and beautiful!) 2-D plotting library. It's easy to use and provides a huge number of
examples for tackling unique problems.
93. Methods Classes have associated methods, which are just a special kind of function. Consider the expression alex.forward(50)
The interpreter first looks up alex and finds that it is an instance of the class Turtle. Then it looks up the attribute forward
and finds that it is a method. Since there is a left parenthesis directly following, the interpreter invokes the method,
passing 50 as a parameter.The only difference between a method invocation and other function calls is that the object
instance itself is also passed as a parameter. Thus alex.forward(50) moves alex, while tess.forward(50) moves tess.
94. Module A module is a file containing Python definitions and statements.

The file name is the module name with the suffix .py appended.

Within a module, the module's name (as a string) is available as the value of the global variable __name__.

Example:

''' Module fib.py '''


from __future__ import print_function

#Note that we can only access the definitions of fib as members of the fib object.
95. Numeric int, long, float, complex
Data
Types
96. Numpy The key to NumPy is the ndarray object, an n-dimensional array of homogeneous data types, with many operations
being performed in compiled code for performance. There are several important differences between NumPy arrays
and the standard Python sequences:

NumPy arrays have a fixed size. Modifying the size means creating a new array.

NumPy arrays must be of the same data type, but this can include Python objects.

More efficient mathematical operations than built-in sequence types.


97. Pyplot At the center of most matplotlib scripts is pyplot. The pyplot module is stateful and tracks changes to a figure. All
pyplot functions revolve around creating or manipulating the state of a figure.

The plot function can actually take any number of arguments. Common usage of plot:

plt.plot(x_values, y_values, format_string [, x, y, format, ])


98. Python $ python
Interactive >>> print "Hello, World!"
Mode Hello, World!
>>> hellostring = "Hello, World!" >>> hellostring 'Hello, World!'
>>> 2*5
10
99. Python print "Hello, World!"
Normal
Mode
100. Python Python is a strongly, dynamically typed language.
Typing
Strong typing:

Explicit conversions are required in order to mix types.

Example: 2 + "four" not going to fly

Dynamic Typing:

All type checking is done at runtime.

No need to declare a variable or give it a type before use.


101. re.compile re.compile(pattern)

Compile a regular expression pattern into a regular expression object, which can be used for matching using its match()
and search() methods, described below.

The expression's behavior can be modified by specifying a flags value. Values can be any of the following variables,
combined using bitwise OR (the | operator).

prog = re.compile(pattern)
result = prog.match(string)
102. re.match If zero or more characters at the beginning of string match the regular expression pattern, return a corresponding match
object. Return None if the string does not match the pattern; note that this is different from a zero-length match.

Note that even in MULTILINE mode, re.match() will only match at the beginning of the string and not at the beginning of
each line.

re.match(pattern, string)
103. re.search() Scan through string looking for the first location where the regular expression pattern produces a match, and return a
corresponding match object. Return None if no position in the string matches the pattern; note that this is different from
finding a zero-length match at some point in the string.

re.search(pattern, string)

re.search("c", "abcdef") # Match


104. Scipy A collection of mathematical algorithms and convenience functions built on the Numpy extension of Python. It adds
significant power to the interactive Python session by providing the user with high-level commands and classes for
manipulating and visualizing data. With SciPy an interactive Python session becomes a data-processing and system-
prototyping environment rivaling systems such as MATLAB, IDL, Octave, R-Lab, and SciLab.
105. Self The first argument of every method is a reference to the current instance of the class

By convention, we name this argument self

Although you must specify self explicitly when defining the method, you don't include it when calling the
method.

Python passes it for you automatically

Defining a method:

def set_age(self, num):


self.age = num

Calling a method:

x.set_age(23)
106. Sequence Data Types strings, list, tuple
107. Set Set: An unordered collection of unique objects

Frozenset: An immutable version of set

Example:

>>> a = set('abracadabra')
>>> b = set('alacazam')
>>> a
set(['a', 'r', 'b', 'c', 'd'])
>>> a - b
set(['r', 'd', 'b'])
>>> a | b
set(['a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'])
108. Significance of Whitespace is significant in Python. Where other languages may use {} or (), Python uses indentation to
whitespace denote code blocks.
109. Slicing mylist[start:end] # items start to end-1

mylist[start:] # items start to end of the array

mylist[:end] # items from beginning to end-1

mylist[:] # a copy of the whole array

mylist[start:end:step] # start to end-1, by step

mylist[-1] # last item in the array

mylist[-2:] # last two items in the array

mylist[:-2] # everything except the last two items


110. String Object Name is bound to an object at some point, but this may change. The name is not synonymous with a
Representation specific address is memory.!
111. Subclasses A class can extend the definition of another class
- Allows use (or extension ) of methods and attributes already defined in the previous one.
- New class: subclass. Original: parent, ancestor or superclass

To define a subclass, put the name of the superclass in parentheses after the subclass's name on the first line of the
definition.

Class Cs_student(student):

- Python has no 'extends' keyword like Java.


- Multiple inheritance is supported.

Example:

class car
4 wheels...

subclass volvo
other attributes?
112. sys.argv - Internal system variable
- Used to obtain command line arguments
- Processes inputs

The first element of the sys.argv list is always the module name, followed by the whitespace-separated arguments.

import sys for i in range(len(sys.argv)):


print "sys.argv[" + str(i) + "] is " + sys.argv[i]

sys.argv[0] is testargs.py sys.argv[1] is here


113. sys.path The sys.path variable specifies the locations where Python will look for imported modules. The sys.path variable is also
a list and may be freely manipulated by the running program. The first element is always the "current" directory where
the top-level module resides.

import sys

print "path has", len(sys.path), "members"

sys.path.insert(0, "./samples") import sample

sys.path = []
import math
114. sys private ...
versions
115. sys.stdin , The sys.stdin, sys.stdout, and sys.stderr attributes hold the file objects corresponding to standard input, standard
sys.stdout , output, and standard error, respectively. Just like every other attribute in the sys module, these may also be
sys.stderr changed at any time!

f = open("somefile.txt", "w") sys.stdout = f print "This is going to be written to the file!"


sys.stdout = sys.__stdout__

If you want to restore the standard file objects to their original values, use the sys.__stdin__, sys.__stdout__, and
sys.__stderr__ attributes.
116. T / F are True
strings
immutable? We cannot change them! Changing a string through re-assignment means creating a new string object and
reassigning the name.!
117. Trimming a txt = "some string"
string
txt = txt[0:4]

print txt

#Output = some
118. Using Lists as You can use lists as a quick stack data structure.
Stacks
The append() and pop() methods implement a LIFO structure.

The pop(index) method will remove and return the item at the specified index. If no index is specified, the last item is
popped from the list.

stack.append(value)
- Adds value to end

stack.pop()
- Removes last value
119. using the The first argument is the filename, the second is the mode.
open() method
f = open("filename.txt", 'rb')
120. What are each of the statements used except:
when handling exceptions? Catch all (or all other)
exception types

except name:
Catch a specific exception only

except name as value: Catch the listed exception and its instance

except (name1, name2):


Catch any of the listed exceptions

except (name1, name2) as value:


Catch any of the listed exceptions and its instance

else:
Run if no exception is raised

finally:
Always perform this block
121. What are the built-in string methods? s.upper()
- Returns in all CAPS

s.lower
- Returns in all lower

s.split()
- Lets you separate a string by providing what separates them

s.isalpha()
- Returns T/F if its all letters

s.isdigit()
- Returns T/F if its a digit

s.isalum()
- Returns T/F if it is alphanumeric string

s.isspace()
- Returns T/F if there's white space
122. What are the different time modules and time.time()
what do they do? - returns the time in seconds since the epoch (typically 1/1/1970), simply measures
elapsed wall clock time.

time.sleep(s)
- suspends execution for s seconds.

time.clock()
- returns the current processor time in seconds. Only measures time during which the
CPU is actively working on behalf of the program
123. What are the different ways you f = open("somefile.txt, 'r')
can open a file and what are the - Opens a file for read only
differences?
f = open("somefile.txt, 'w')
- Opens a file for writing only

f = open("somefile.txt, 'a')
- Opens a file for appending

f = open("somefile.txt, 'rb')
- Opens a file for read only in binary format
124. What are the four statements break: terminates the current loop.
provided for manipulating loop
structures and their definition? continue: immediately begin the next iteration of the loop.

pass: do nothing. Use when a statement is required syntactically.

else: represents a set of statements that should execute when a loop terminates.
125. What is an object? An object has both a state and behavior. The state defines the object, and the behavior defines
what the object does.
126. What is a Regular Expression? A sequence of characters that forms a search pattern.

RegEx can be used to check if a string contains the specified search pattern.

- "digits1234"
- [a-z][0-9]
- Pattern says any letter a-z and number 0-9
- If it contains any of the following you'll have a match
- Compile -> search -> lets you know if there's a match
127. What is __name__ ? Within a module, the module's name (as a string) is available as the value of the global
variable __name__.

If a module is executed directly however, the value of the global variable __name__ will be
"__main__".
128. What is the purpose of __init__ method an take any number of arguments
constructor__init__
in __init__, self refers to the object currently being created; so, in other class methods, it refers to
the instance whose method was called
129. What is the role of handling Explicitly handling exceptions allows us to control otherwise undefined behavior in our
exceptions? program, as well as alert users to errors. Use try/except blocks to catch and recover from
exceptions.
130. What is the sys module and how The sys module provides access to some variables used or maintained by the interpreter as
do you use it? well as some methods for interacting with the interpreter. It allows you to receive information
about the runtime environment as well as make modifications to it.

To use the sys module, just execute the import sys statement.
131. What kind of package is Numpy, NumPy/SciPy - numerical and scientific function libraries.
Scipy, and Plotting?
Plotting - Matplotlib for complex scientific applications
132. What would be the printed outputs for the following c) 20,18,16
program?
for i in range(20,14,-2):
print i
a) 18,19,20
b) 20,19,18,17
c) 20,18,16
d) 20,18,16,14
133. When should you use a List? When you need:

A collection of elements of varying type.

The ability to order your elements.

The ability to modify or add to the collection.

When you don't require elements to be indexed by a custom value.

When you need a stack or a queue.

Your elements are not necessarily unique.


134. When should you use a set? When the elements must be unique.

When you need to be able to modify or add to the collection.

When you need support for mathematical set operations.

When you don't need to store nested lists, sets, or dictionaries as


elements.
135. When should you use a Tuple? When storing elements that will not need to be changed.

When performance is a concern.

When you want to store your data in logical immutable pairs, triples,
etc.
136. When should you use Dictionaries? When you need to create associations in the form of key:value pairs.

When you need fast lookup for your data, based on a custom key.

When you need to modify or add to your key:value pairs.

You might also like