Font size
WorksheetsPython Programming Quiz
Total questions: 133
Worksheet time: 1hrs 7mins
In which of the following does the Cricket Fan class correctly inherit from the Party Animal class?
from party import Party Animal
class CricketFan(PartyAnimal)
An= PartyAnimal()
CricketFan = PartyAnimal()
In Python, a class is... for a concrete object.
nuisance
instance
blueprint
distraction
Which of the following is the correct way to define an initializer method?
def init(title, author):
def init(self, title, author):
def init():
init(self, title, author):
What keyword is used to indicate the start of a method in a Python class?
def
break
function
continue
Which of the following statements is not true about object-oriented programming?
One of the benefits of object-oriented programming is that it can hide complexity.
A class contains functions as well as the data that is used by those functions.
Constructor methods are required to initialize an object and destructor methods are required to destroy the object when no longer required.
A powerful feature of object-oriented programming is the ability to create a new class by extending an existing class.
What is the output of the following code? python class Person: def_init__(self, id): self.id =id sam Person(100) sam_dict_['age'] $I=49$ print(sam.age len(sam._dict))
49
50
51
48
Which came first, the instance or the class?
Class
Function
Instance
Method
What's the output of the following code snippet? python class Dog: def walk(self): return "walking" def speak(self): return "Woof!" class Jack Russell Terrier(Dog): def talk(self): return super().speak() bobo JackRussell Terrier() bobo.talk()
Woof!
walking
CanineError: Tail curvature exceeded
None of the others
Which of the following code uses the inheritance feature of Python?
Class Foo: Pass
Class Foo(object): pass class Hoo(object): pass
Class Foo: pass class Hoo (Foo): pass
None of the others
What would the following mean in a regular expression? $[a-z0-9]$
Match any number of lowercase letters followed by any number of digits
Match a lowercase letter or a digit
Match an entire line as long as it is lowercase letters or digits
Match any text that is surrounded by square braces
What will the following Python code print out? python friends = ['Joseph', 'Glenn', 'Sally'] friends.sort() print(friends[0])
Glenn
Joseph
Sally
friends
For the following list, how would you print out 'Sally'? python friends = ['Joseph', 'Glenn', 'Sally']
print(friends[3])
print(friends['Sally'])
print(friends[2])
print(friends[2:1])
What does the following Python program print out? str1 = "Hello" str2 = "there" bob str1 str2 print(bob)
Hello
0
Hellothere
Hello There
Which of the following will result in an error?
print(str1[2])
str1[1] = "x"
print(str1[0:9])
Both (b) and
Which method can be used to remove any whitespace from both the beginning and the end of a string?
Istrip()
strip()
rstrip()
strim()
What would the following Python code print out? python stuff = dict() print(stuff['candy'])
-1
0
The program would fail with a traceback
candy
Which of these collections defines a DICTIONARY?
("apple", "banana", "cherry")
{"name": "apple", "color": "green"}
{"apple", "banana", "cherry"}
["apple", "banana", "cherry"]
What is the output for: "Tutorials Point" [100:200]?
Index error
.
'Tutorials Point'
Syntax error
Which of the following command is used to open a file "c:\temp.txt" in write-mode only?
outfile = open("c:\temp.txt", "w")
outfile = open("c:\temp.txt", "w")
outfile = open( $file=$ "c:\temp.txt", "w+")
outfile = open( $file=$ "c:\temp.txt", "w+")
Given the file dog_breeds.txt, which of the following is the correct way to open the file for reading as a text file?
open('dog_breeds.txt', 'wb')
open('dog_breeds.txt', 'rb')
open('dog_breeds.txt', 'r')
open('dog_breeds.txt', 'w')
Whenever possible, what is the recommended way to ensure that a file object is properly closed after usage?
It doesn't matter
By using the with statement
By using the try/finally block
Making sure that you use the close() method before the end of the script
A list of lines is returned if using the method of
readable()
readlines()
readline()
read()
If we open a file as follows: xfile = open('mbox.txt)
for line in xfile:
while (getline(xfile, line)) {
READ xfile INTO LINE
READ (xfile, *, $END=10)$ line
When reading a file using the file object, what method is best for reading the entire file into a single string?
readlines()
readline()
read_file_to_str()
.read()
Which operator can be used to compare two values?
<>
=
>=
==
Which of the following statement about Python is not correct?
The python ecosystem is very rich and provides easy to use tools for data science
Due to its proprietary nature, database access from Python is not available for many databases
There are libraries and APIs available to access many of the popular databases from Python
Python is a popular scripting language for connecting and accessing databases
What is the proper way to say "good-bye" to Python?
quit()
stop()
exit()
end()
A USB memory stick is an example of which of the following components of computer architecture?
Central Processing Unit
Main Memory
Secondary Memory
None of these
What is the most common Unicode encoding when moving data between systems?
UTF-128
UTF-8
UTF-32
UTF-64
How would you express the constant floating-point value $3.2\times10^{3}$ in Python?
3.2e-3
3.2e3
0.32
32e-3
You have the following dictionary definition: d={'foo': 100, 'bar': 200, 'baz': 300} What method call will delete the entry whose value is 200?
d.pop("bar")
d.remove("bar")
d.remove("200")
d.pop("200")
Identify the data structure we use in the code given below: python # Code starts asthetic1 = 'quizOrbit asthetic2 = 'QuizOrbit print(asthetic1 = asthetic2) # Code ends
HashMap
Dictionary
True
Which of the following data structures in Python are immutable?
Linked List
Tree
Tuple
All of the above
What is the output of the following code? python class Hum: def __init__(self, x = 1): self.x = x self.y = 1 def call(self, other_y): self.y = self.x + other_y print(self.x) p1 = Hum(2) p2 = Hum(4) p1.call(p2.x) print(p1.y)
22
46
00
11
What does the Python help() function show when we pass an object into it as a parameter?
It shows the parent class
It shows the number of parameters to the constructor
It shows the methods and attributes of the object
It shows the type of the object
What does the __init__() function do in Python?
Initializes the class for use
This function is called when a new object is instantiated.
Initializes all the data attributes to zero when called
None of the above
For the following code: python x = 0 if x < 10: print("Below 10") if x < 20: print("Below 20") else: print("Something else") What is the output?
x = 20
This code will never print Something else regardless of the value for x.
x = 20
It will print out "Below 20"
What is the purpose of the following Python code? python fhand = open('mbox-short.txt') x = 0 for line in fhand: x = x + 1 print(x)
Remove the leading and trailing spaces from each line in mbox.txt
Count the lines in the file mbox.txt
Convert the lines in mbox.txt to upper case
Reverse the order of the lines in mbox.txt
What is the output of print(list[3]) if list = ['abcd', 786, 2.23, 'john', 70.2]
['abcd', 786, 2.23]
abcd
[786, 2.23]
None of the above.
Once again consider this dictionary: d = {'foo': 100, 'bar': 200, 'baz': 300} What is the result of this statement: d['bar'] = d['foo']
It raises an exception
200, 300
[200, 300]
(200, 300)
List a is defined as follows: l = [5, 6, 7] Which of the following statements adds 'd' and 'e' to the end of a, so that it then equals ['a', 'b', 'c', 'd', 'e']
l.extend(['d', 'e'])
l.append(['d', 'e'])
l += ['d', 'e']
all of them are false
Which of the following is not a Python reserved word?
iterate
continue
else
input
In the following code, x = y. What is x?
A variable
A constant
A parameter
A pointer
What is the value of the following expression? 4 + 2 * 10
44
24
25
4.2
Which of the following elements of a mathematical expression in Python is evaluated first?
Addition +
Multiplication *
Subtraction -
Parentheses ()
How do you create a variable x with the numeric value 5?
x == 5
x.value = 5
Both the answers A and B are correct
Both the answers A and B are incorrect
What is the correct syntax to output the type of a variable or object in Python?
print(type(x))
print(type of x)
print type(x)
print(type(x))
When you have multiple lines in an if block, how do you indicate the end of the if block?
You omit the semicolon ; on the last line of the if block
You de-indent the next line past the if block to the same level of indent as the original if statement
You put the colon : character on a line by itself to indicate we are done with the if block
You use a curly brace { } after the last line of the if block
You look at the following text if x == 0: print('Still') print('All done') It looks perfect but Python is giving you an 'IndentationError: on the second print statement. What is the most likely reason?
In order to make humans feel inadequate, Python randomly emits 'Indentation Errors' on perfectly good code - after about an hour the error will just go away without any changes to your program.
Python has reached its limit on the largest Python program that can be run
Python thinks 'Still' is a mis-spelled word in the string
You have mixed tabs and spaces in the file
What will the following code print? python x = 6 if x < 10: print('Small') elif x < 10: print('Medium') else: print('LARGE') print('All done')
LARGE All done
Small
Small All done
Small Medium LARGE All done
What is the iteration variable in the following Python code? for letter in 'banana': print(letter)
banana
for
letter
If a class is derived from two different classes, it's called ___________.
Multilevel Inheritance
Multiple Inheritance
Hierarchical Inheritance
Hybrid Inheritance
Given the code: class People(): def __init__(self, name): self.name = name def namePrint(self): print(self.name) person1 = People("Sally") person2 = People("Louise") person1.namePrint() What is the correct answer?
person1 and person2 are two different instances of the People class
The init method is used to set initial values for attributes
self is not used in def namePrint(self)
person2 has a different value for 'name' than person1
Given the code: class People(): def __init__(self, name): self.name = name def namePrint(self): print(self.name) person1 = People("Sally") person2 = People("Louise") person1.namePrint() What is the correct output?
Sally
Louise
Sally Louise
person1
What's the output of the following code snippet? class Dog: def walk(self): return "walking" def speak(self): return "Woof!" class JackRussellTerrier(Dog): def speak(self): return "Arff!" bobo = JackRussellTerrier() bobo.walk()
Arff
walking
AttributeError: 'JackRussellTerrier' object has no attribute 'walk'
Woof!
Object and class attributes are accessed using ___________ notation in Python:
Dot notation.
Arrow notation.
Plus notation.
And notation.
The _______ keyword defines a template indicating the data that will be in an object of the class and the functions that can be called on an object of the class
Class
object
class
instance
Given the code: class Pokemon(): def __init__(self, name, type): self.name = name self.type = type def stringPokemon(self): print("Pokemon name is {self.name} and type is {self.type}") class GrassType(Pokemon): def stringPokemon(self): print("Grass type pokemon name is {self.name}") poke1 = GrassType("Bulbasaur", "Grass") poke1.stringPokemon() poke2 = Pokemon("Charizard", "Fire") poke2.stringPokemon() What is the correct output?
Grass type pokemon name is Bulbasaur Pokemon name is Charizard and type is Fire
Pokemon name is Bulbasaur and type is Grass Pokemon name is Charizard and type is Fire
Grass type pokemon name is Bulbasaur Grass type pokemon name is Charizard
Error because the extending class has a stringPokemon() function which already exists.
Which of the following statements is true?
A class is a blueprint for the object
You can only make a single object from the given class
Both statements are true
Neither statement is true
What is 'self' typically used for in a Python method within a class?
To terminate a loop
To set the residual value in an expression where the method is used
The number of parameters to the method
To refer to the instance in which the method is being called
Which method can be used to replace parts of a string?
replace()
replaceString()
repl()
repl()
Which method can be used to return a string in upper case letters?
toLower()
.lower()
lowercase()
lowerCase()
How would you use the index operator to print out the letter q from the following string? X = "From marquard@uct.ac.za"
print(X[q])
print(X[10])
print(X[9])
print(X[8])
What is a correct syntax to output "Hello World" in Python?
echo "Hello World"
p("Hello World")
print("Hello World")
echo("Hello World")
(1) ast = "Hello Bob (2) ast = ast() (3) ast (4) ast = ast.upper() (5) print('First' ast) (6) ast = ast() (7) print('Second' ast) In the following code (numbers added) - which will be the last line to execute successfully?
1
2
5
6
Which data structure is the output of the code given below? # Code starts col = (2,4,6), (5,7,9) finalAns = list(col) print(type(finalAns)) # Code Ends
Tree
List
Set
Dictionary
What does the following Python code print out? a = [1, 2, 3] b = [4, 5, 6] c = a + b print(c)
21
[1, 2, 3, 4, 5, 6]
If it raises an exception
0
Which collection does not allow duplicate members?
SET
DICTIONARY
TUPLE
LIST
What does the following Python code do? fhand = open('mbox-short.txt') inp = fhand.read()
Checks to see if the file exists and can be written
Turns the text in the file into a graphic image like a PNG or JPG
Reads the entire file into the variable inp as a string
Prompts the user for a file name
The following code sequence fails with a traceback when the user enters a file that does not exist. How would you avoid the traceback and make it so you could print out your own error message when a bad file name was entered? fname = raw_input('Enter the file name: ') try: fhand = open(fname) except: print('Bad file name:', fname) exit()
try / except
signal handlers
try/catch/finally
on error resume next
What do we use the second parameter of the open() call to indicate
How large we expect the file to be
The list of folders to be searched to find the file we want to open
Whether we want to read data from the file or write data to the file
What disk drive the file is stored on
What is the purpose of the newline character in text files?
It adds a new network connection to retrieve files from the network
It indicates the end of one line of text and the beginning of another line of text
It enables random movement throughout the file
It allows us to open more than one files and read them in a synchronized manner
How do you insert something on a new line in a file?
write newline(x)
\n
You cannot do this
type the content on the line below
If you write a Python program to read a text file and you see extra blank lines in the output that are not present in the file input as shown below, what Python string function will likely solve the problem? From: stephen.marquard@uct.ac.za From: louis@media.berkeley.edu From: zqian@umich.edu From: rjlowe@iupui.edu
find()
startswith()
rstrip()
split()
What is the name of this symbol -> ?
Chevrons
Hash tags
Colon
Semi-Colon
Which of the parts of a computer actually executes the program 'instructions'?
RAM
CPU
Input Output Devices
Secondary Memory
What extension must you add to the end of a file when saving?
.py
.txt
.pyth
.txt
What is the best way to think about a 'Syntax Error' while programming?
The computer needs to have its software upgraded
The computer is overheating and just wants you to stop to let it cool down
The computer has used GPS to find your location and hates everyone from your town
The computer did not understand the statement that you entered
What are the names of the two types of mode that are used in Python?
Interactive mode & Script mode
Interactive mode & Scratch mode
Interactive mode & Imperial mode
Imperial mode & Script mode
Which of the following statements assigns the value 100 to the variable x in Python
x == 100
let x = 100
x <- 100
x = 100
x = 100
What is the output of the following python code snippet? emp1 = ('Ajay', 25, 100000) emp2 = ('Nithe', 21, 120000) emp1[2] = 20000 print(emp1[2] + emp2[2]) # Code Ends
55000
25000
Type Error
None of the above.
What does the following Python code print out? a = [1, 2, 3] b = [4, 5, 6] c = a - b print(c)
21
[1, 2, 3, 4, 5, 6]
If it raises an exception
0
Find the output of the code given below? # Code starts x = [21, 25, 37, 94] x.append(75, 62, 79) print(len(x)) # Code Ends
1
4
7
Error
What is the correct way to create a function in Python?
def function[]:
define function(){ }
function() { }
create function()
def function():
In Python, a function within a class definition is called a?
an operation
a method
a callable
a class function
a factory
For the following code, which of the following statements is true? def PrintHello(): print("Hello") x = PrintHello()
Both PrintHello() and x refer to the same object
PrintHello() and x refer to different objects
Syntax error! You cannot assign function to a variable in Python
Find the output of the given Python program. a = 10 if a <= 15: print("Hi") else: print("Know Program!")
Hi
Hello
Hi Hello
Hi Know Program
Which of the following reserved keyword is used to end a function, return generator?
break
switch
Return
yield
What is the result of the following statement list([x for x in range(3, 6)])
[3, 4, 5]
3, def
[100, 101, 102]
It causes an exception
Which data structure is being put to use in the code given below? # Code starts org = 'QuizOrbit' count = {} for i in org: if i in count: count[i]+=1 else: count[i]=1 print(count) # Code Ends
String
List
Tuple
Dictionary
Which of these collections defines a LIST?
{"name": "apple", "color": "green"}
["apple", "banana", "cherry"]
{"apple", "banana", "cherry"}
("apple", "banana", "cherry")
If you want to transform a list of strings, say ['a','b','c'] into a single string with a comma between each item, which of the following would you give as the input to join()?
,
string
input_list
str
ng would you give as the input to join()?
,
string
input_list
str
What do we do to a Python statement that is immediately after an if statement to indicate that the statement is to be executed only when the if statement is true?
Un-indent the all of the conditional code
Indent the line below the if statement
Start the statement with a '>' character
Begin the statement with a curly brace { }
What will be the value of x after the following statement executes? x = 1 * 2 - 3 / 4 % 2
1
2
4
6
Assume x and y are assigned as follows: x = 3; y = 5; What is the effect of this statement? x, y = y, x
The values of x and y are unchanged
Both x and y are 5
Both x and y are 2
The values of x and y are swapped
Which of the following Python statements would print out the length of a list stored in the variable data?
print(length(data))
print(data.length())
print(len(data))
print(data.length)
What will be the value of x after the following statement executes? x = 1 + 2 * 3 - 8 / 4
3.0
4.5
4
5.0
Which statement is used to stop a loop?
exit
break
stop
return
How do you start writing an if statement in Python?
if x < y
if (x > y)
if x > y then:
if x > y
What is true about the following code segment if x == 5: print('First') print('Second') print('Third')
Depending on the value of x, either all three of the print statements will execute or none of the statements will execute
The string 'First' will always print out regardless of the value for x.
The string 'Is 5' will never print out regardless of the value for x.
Only two of the three print statements will print out if the value of x is less than zero.
True or False? In order to extend a class, the new class should have access to all the data and inner workings of the parent class
True
False
What is the last action that must be performed on a file?
Close
Save
End
Write
Which of these operators is not a 'comparison / logical operator'?
==
=
<=
>=
In the following code: print(98.6). What is '98.6'?
A variable
A constant
A parameter
A pointer
What does the following Python sequence print out? x = 'From: Using the character' print(x[1])
F
From: Using the ]
[From:]
From:
Which of the following is NOT a good synonym for 'class' in Python?
direction
blueprint
pattern
template
Which of the following statements is not true about object-oriented programming?
One of the benefits of object-oriented programming is that it can hide complexity.
A class contains functions as well as the data that is used by those functions.
Constructor methods are required to initialize an object and destructor methods are required to destroy the object when no longer required.
A powerful feature of object-oriented programming is the ability to create a new class by extending an existing class.
Which of the following would separate a string 'input_string' on the first 2 occurrences of the letter 'a'?
e.split('input_string', 2)
e.split('input_string', 'a', 2)
e.split('input_string', 'a', maxsplit=2)
input_string.split('a', maxsplit=2)
List a is defined as follows: a = [1, 2, 3, 4] Select all of the following statements that remove the middle element 3 from a so that a equals [1, 2, 4]
a[2:2] = []
a[2] = []
del a[2]
a.remove(3)
How would you express the constant floating-point value $3.2\times10^3$ in Python?
3.2e-3
3.2e3
0.32
32e-3
For the following code, which of the following statements is true? def PrintHello(): print('Hello') x = PrintHello()
PrintHello() is a function and x is a variable. None of them are objects
Both PrintHello() and x refer to the same object
PrintHello() and x refer to different objects.
Syntax error! You cannot assign function to a variable in Python.
Which of these words is a reserved word in Python?
while
payroll
names
pizza
What Python function would you use if you wanted to prompt the user for a file name to open?
file_input()
read()
input()
open()
_______ is not a keyword, but by convention it is used to refer to the current instance (object) of a class.
class
def
'self'
'init'
Which of the following does not correctly create an object instance?
puppy: Dog('Tame')
dog = Dog('Jamie')
jamie = Dog()
puppy = new Dog('Tame')
What is the type of the return value of the re.findall() method?
A list of strings
An integer
A boolean
A single character
Which of the following is a comment in Python?
// This is a test
/* This is a test */
# This is a test
& This is a test
What will the following Python code print out? friends = ['Joseph', 'Glenn', 'Sally'] friends.sort() print(friends[0])
Glenn
Joseph
Sally
Friends
What is the syntax to look up the fullname attribute in an object stored in the variable colleen?
colleen : fullname
colleen . fullname
colleen.fullname
colleen['fullname']
What is the result of this statement? print(ord('foo'))
102
It raises an exception
102, 111, 111
324
class People(): def __init__(self, name): self.name = name def namePrint(self): print(self.name) person1 = People("Sally") person2 = People("Louise") person1.namePrint()
Sally
Louise
Sally Louise
person1
What would the following Python code print out? fruit = "Banana" fruit[0] = 'b' print(fruit)
Nothing would print - the program fails with a traceback error
B
b
banana
What is the output of the following code? class Point: def __init__(self, x=0, y=0): self.x = x self.y = y p1 = Point() print(p1.x, p1.y)
Initializes the class for use
0 0
1 1
None None
X y
What is the Python reserved word that we use in two-way if tests to indicate the block of code that is to be executed if the logical test is False?
break
switch
else
toggle
What is the most common Unicode encoding when moving data between systems?
UTF-128
UTF-8
UTF-32
UTF-64
Which one is NOT a legal variable name?
myvar
Myvar
My_var
My-var
Which of the following can be used to invoke the _init_ method in B from A, where A is a subclass of B?
super().__init__()
super()._init_self()
B.init()
Which method can be used to return a string in upper case letters?
upper()
uppercase()
toUpperCase()
upperCase()
What does the following code print out? print("123" + "abc")
123abc
123+abc
This is a syntax error because you cannot add strings
hello world
What will the following program print out? x = 15 x = x + 10 print(x)
25
5
15
"print x"
Python scripts' files have names that end with:
.pyc
.py
.exe
.doc
For the following list, how would you print out 'Sally'? friends = ['Joseph', 'Glenn', 'Sally']
print(friends['Sally'])
print(friends[2:1])
print(friends[2])
print(friends[3])
