Professional Documents
Culture Documents
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) 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) 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.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
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:
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
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
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.
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.
sumProd(x,y)
66. for loop for var in sequence:
statements
67. Formatting with the format method print("Your total Correct is: {} ".format(Correct))
d1 = {}
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 = []
mylist1 = list()
mylist2 = list(sequence)
Access:
mylist[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.
Access:
TupleName[index]
Modify:
except ValueError:
print("Ooops !! That was not a valid number. Try again.")
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
pattern = "Fred"
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.
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:
#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.
The plot function can actually take any number of arguments. Common usage of plot:
Dynamic Typing:
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)
Although you must specify self explicitly when defining the method, you don't include it when calling the
method.
Defining a method:
Calling a method:
x.set_age(23)
106. Sequence Data Types strings, list, tuple
107. Set Set: An unordered collection of unique objects
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
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):
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
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!
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
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.
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:
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.