
Jillur Quddus • 1 September 2020
Back to Course Overview
Introduction
In this final module of our Introduction to Python course, we will consolidate everything that we have learnt by taking a practice Certified Associate in Python Programming (PCAP) examination paper (aligned to exam version PCAP-31-02).
Python Certification
A formal certification in any skill is a worthwhile endeavour, most importantly for personal growth but also to enable employers to validate your knowledge. As technology continues to advance rapidly and as organisations become more data-driven, the need for employees to have a strong grounding in coding and fundamental computing principles is just as important as foundations in mathematics and language skills. A certification in a programming language, such as Python, is therefore an immensely valuable asset for both employees and modern organisations.
PCAP Exam
The Python Institute is an independent non-profit project set up by the Open Education and Development Group (OpenEDG) to promote the Python programming language, train the next generation of Python programmers, and to support professional careers in Python programming and related technologies. They offer independent and vendor-neutral certification in the Python programming language across the following three competency levels:
- Entry Level - Certified Entry-Level Python Programmer (PCEP) certification.
Enables individuals to validate their knowledge of fundamental computer programming concepts including data types, functions, conditions, loops and the basics of Python programming language syntax, semantics and its runtime environment. - Associate - Certified Associate in Python Programming (PCAP) certification.
Enables individuals to validate their knowledge of general computer programming concepts including everying in the PCEP syllabus plus conditional execution, loops, intermediate Python programming syntax, semantics and its runtime environment, object oriented programming, general coding techniques and best practices. - Professional - Certified Professional in Python Programming (PCPP 1 and PCPP 2) certification.
Enables individuals to validate their professional credentials as an advanced Python software developer including everything in the PCEP and PCAP syllabuses plus advanced object oriented programming, mathematics, science and engineering-oriented Python modules, graphical user interface (GUI) programming, network programming, testing principles and techniques, software design patterns, database programming, and creating complete software services and systems.
Our Introduction to Python course has been purposely aligned to the PCAP examination syllabus (exam version PCAP-31-02), as this provides learners with a strong coding foundation from which to develop a modern professional career in Data Science, Software Engineering and/or Data Engineering amongst other career pathways.
Exam Information
Further information on the PCAP examination may be found on the PCAP Certification webpage, the key points of which are listed below (correct as of September 2020):
- Exam Code: PCAP-31-02 (Pearson Vue) or PCAP-NP-31-02 (OpenEDG Testing Service)
- Pre-Requisites: None
- Duration: 65 minutes (exam)
- Number of Questions: 40
- Format: Single and multiple choice
- Language: English
- Pass Mark: 70%
- Full Exam Price: USD 295.00
Exam Syllabus
The PCAP examination syllabus (exam version PCAP-31-02), to which our Introduction to Python course is aligned, covers four major areas in Python 3.x programming, namely:
- Control and Evaluations (10 exam questions)
- Data Aggregates (10 exam questions)
- Functions and Modules (10 exam questions)
- Classes, Objects and Exceptions (10 exam questions)
Each area is worth 25% of the total examination mark, with each question worth 1 point. The pass mark is 70%, or 28 points out of a maximum of 40 points. Details of the topics covered in each of these four areas may be found on the PCAP Exam Syllabus webpage.
Exam Price
The full exam fee is USD 295.00. Retakes are unlimited as long as those retakes are at least 15 days apart. Please refer to the PCAP Testing Policies webpage for further information.
PCAP Practice Exam
To help learners prepare for the PCAP examination, a sample PCAP-31-02 examination paper is provided below, with answers cross-referenced with the relevant modules in our Introduction to Python course.
Control and Evaluations
Question 1
2 ** 3 ** 2 ** 1
- A. Invalid
- B. Equal to
16
- C. Equal to
16.0
- D. Equal to
512
- E. Equal to
64
- F. Equal to
128.0
D. Equal to
512
Explanation
The exponential operator
**
raises a base value by an exponent or power. Also recall that the exponential operator groups from right to left. Therefore 2 ** 3 ** 2 ** 1
evaluates to 2 ** (3 ** (2 ** 1)) = 2 ** 9 = 512
.References
Control and Evaluations Part 1 - Arithmetic Operators
Control and Evaluations Part 1 - Operator Precedence
Question 2
Peter's sister's name's "Anna"
- A.
"Peter's sister's name's \"Anna\""
- B.
'Peter\'s sister\'s name\'s \"Anna\"'
- C.
"Peter's sister's name's "Anna""
- D.
'Peter's sister's name's "Anna"'
A and B
Explanation
The existence of a double quote character in a string that itself is defined and enclosed by double quote characters will cause the Python interpreter to raise a
SyntaxError
exception. Similarly the existence of a single quote character in a string that itself is define and enclosed by single quote characters will also raise a SyntaxError
exception. To overcome this, we may 'escape' those illegal characters by prefixing them with the \
backslash character.References
Control and Evaluations Part 2 - Escape Character
Question 3
i = 250
while len(str(i)) > 72:
i *= 2
else:
i //= 2
print(i)
- A.
125
- B.
250
- C.
72
- D.
500
A.
125
Explanation
The
*
multiplication operator calculates the product of two given numbers. The //
floor division, or quotient, operator calculates the floor division and returns the integral part of the quotient (i.e. returns the largest integer less than or equal to normal division). The str()
function is applied to the integer 250
resulting in a string literal of length 3
. Consequently the else
clause is invoked and assigns to the variable i
the evaluation of 250 //= 2
which is 125
.References
Control and Evaluations Part 1 - Arithmetic Operators
Control and Evaluations Part 1 - Assignment Operators
Control and Evaluations Part 2 - While-else Loop
Question 4
n = 0
while n < 4:
n += 1
# insert your code here
1 2 3 4
- A.
print(n)
- B.
print(n, sep=" ")
- C.
print(n, end=" ")
- D.
print(n, " ")
C.
print(n, end=" ")
Explanation
The Python
print()
function accepts an optional end
sequence argument that specifies what to print at the end of the output. By default, the end sequence is the new line feed \n
character.References
Control and Evaluations Part 2 - Print Function
Control and Evaluations Part 2 - While Loop
Question 5
x = 0
y = 2
z = len("Python")
x = y > z
print(x)
- A.
int
- B.
float
- C.
str
- D.
bool
- E.
NoneType
D.
bool
Explanation
The
>
'greater than' comparison operator will compare two given values and return True
if the condition is met, False
otherwise. The =
assignment operator is then used to assign this boolean value to the variable x
.References
Control and Evaluations Part 1 - Assignment Operators
Control and Evaluations Part 1 - Comparison Operators
Question 6
Val
variable be when the following snippet finishes its execution?Val = 1
Val2 = 0
Val = Val ^ Val2
Val2 = Val ^ Val2
Val = Val ^ Val2
- A.
0
- B.
1
- C.
2
- D.
4
- E. The code is erroneous
A.
0
Explanation
The
^
bitwise XOR operator (exclusive OR) compares each bit of two operands. If only one of the two bits is set to 1, then the output of bitwise XOR is also 1, otherwise 0. In this case, the variable Val
is assigned the value of 1
, then 1 ^ 0
which evaluates to 1
. The variable Val2
is assigned the value 0
, then 1 ^ 0
which evaluates to 1
. Finally the variable Val
is assigned the value 1 ^ 1
which evaluates to 0
.References
Control and Evaluations Part 1 - Bitwise XOR
Question 7
z, y, x = 2, 1, 0
x, z = z, y
y = y - z
# put line here
print(x, y, z)
0, 1, 2
- A.
x, y, z = y, z, x
- B.
z, y, x = x, z, y
- C.
y, z, x = x, y, z
- D. The code is erroneous
A and B
Explanation
Sequence unpacking enables multiple variables to be assigned the values of the elements in a given sequence, as long as there are as many variables on the left side of the assignment operator as there are elements in the given sequence on the right side.
References
Data Aggregates Part 2 - Tuple Assignment
Question 8
a = 0
b = a ** 0
if b < a + 1:
c = 1
elif b == 1:
c = 2
else:
c = 3
print(a + b + c)
- A.
1
- B.
2
- C.
3
- D. The code is erroneous
C.
3
Explanation
The
**
exponential operator raises a base value by an exponent of power. In this case, the variable a
is assigned the value 0
and the variable b
is assigned the value 0 ** 0
which, in Python, evaluates to the value 1
. Consequently the elif b == 1
statement is invoked, and the variable c
is assigned the value 2. Consequently the value of a + b + c
is 0 + 1 + 2
which evaluates to 3
.References
Control and Evaluations Part 1 - Arithmetic Operators
Control and Evaluations Part 2 - If-elif Statement
Question 9
i = 10
while i > 0 :
i -= 3
print("*")
if i <= 3:
break
else:
print("*")
- A. Three
- B. Two
- C. One
- D. The code is erroneous
A. Three
Explanation
The variable
i
is initially assigned the value 10
. On the first iteration of the while
loop, i
is then assigned the value i = 10 - 3 = 7
, and the *
character is printed. On the second iteration of the while
loop, i
is then assigned the value i = 7 - 3 = 4
, and the *
character is printed. Finally on the third iteration of the while
loop, i
is assigned the value i = 4 - 3 = 1
, at which point the third and final *
character is printed and the while
is terminated as a result of the break
keyword.References
Control and Evaluations Part 2 - While-else Loop
Control and Evaluations Part 2 - Break Statement
Question 10
# Example 1
for i in range(1, 4, 2):
print("*")
# Example 2
for i in range(1, 4, 2):
print("*", end="")
# Example 3
for i in range(1, 4, 2):
print("*", end="**")
# Example 4
for i in range(1, 4, 2):
print("*", end="**")
print("***")
- A. Example 1: two, Example 2: one, Example 3: one, Example 4: one
- B. Example 1: two, Example 2: one, Example 3: one, Example 4: two
- C. Example 1: two, Example 2: one, Example 3: two, Example 4: three
- D. Example 1: one, Example 2: one, Example 3: one, Example 4: two
A. Example 1: two, Example 2: one, Example 3: one, Example 4: one
Explanation
In example 1,
range(1, 4, 2)
returns the integers 1 and 3, hence two lines are printed. In example 2, range(1, 4, 2)
returns the integers 1 and 3 but the end
sequence argument in the print()
function replaces the default end sequence \n
with ""
in which case only one line is printed. In example 3, range(1, 4, 2)
returns the integers 1 and 3 but the end
sequence argument in the print()
function replaces the default end sequence \n
with "**"
in which case only one line is printed. Finally example 4 is the same as example 3, as the very final print("***")
statement is out of the scope of example 4 due to its indentation.References
Control and Evaluations Part 2 - For Loop
Control and Evaluations Part 2 - Range Function
Control and Evaluations Part 2 - Print Function
Data Aggregates
Question 11
- A. UNICODE is the name of an operating system
- B. UTF-8 is the name of a data transmission device
- C. ASCII is an acronym for Automatic Systems of Computer Inner Interoperability
- D. The Python Language Reference is the official reference manual that describes the syntax and semantics of the Python language
- E. Python strings are immutable, which means they cannot be sliced
- F. Python strings are mutable, which means they can be sliced
- G. Lists and strings in Python can be sliced
D and G
Explanation
Unicode is a universal character set. UTF-8 is the name of an encoding for all characters in the Unicode standard. ASCII stands for American Standard Code for Information Interchange. Though string objects are indeed immutable, they are still sequences of characters and hence may be sliced, resulting in a new string object being returned. Lists and strings are both sequences and hence may be sliced.
References
Data Aggregates Part 1 - Character Encodings
Data Aggregates Part 1 - Advanced Strings
Data Aggregates Part 1 - Advanced Lists
Question 12
x = "20"
y = "30"
print(x > y)
- A.
True
- B.
False
- C.
None
- D. The comparison causes a runtime exception/error
B.
False
Explanation
Sequence objects, such as strings and lists, may be compared with other objects of the same sequence type. If two strings are compared, then the Unicode code point number is used to order and compare individual characters.
References
Data Aggregates Part 1 - String Comparisons
Data Aggregates Part 1 - Character Encodings
Question 13
s = "Hello, Python!"
print(s[-14:15])
- A.
Hello, Python!
- B.
!nohtyP ,olleH
- C.
Hello, Python!Hello, Python!
- D.
!nohtyP ,olleH!nohtyP ,olleH
- E. The program causes a runtime exception/error
- F. The result cannot be predicted
A.
Hello, Python!
Explanation
In slicing notation, negative indexes start the slice from the end of the sequence where the last element in a sequence has a negative index of
-1
. In this case, the element at index -14
is the character H
. Furthermore slice indices are handled gracefully in Python, and when the end index is out of bounds Python will default to the length of the sequence.References
Control and Evaluations Part 2 - List Slicing
Control and Evaluations Part 2 - Index and Negative Indexing
Data Aggregates Part 1 - Advanced String Slicing
Question 14
lst = ["A", "B", "C", 2, 4]
del lst[0:-2]
print(lst)
- A.
[2, 4]
- B.
['C', 2, 4]
- C.
['B', 'C', 2, 4]
- D.
['A', 'B']
A.
[2, 4]
Explanation
The
del
keyword enables us to delete specific elements from a list. In this case, the elements starting from index 0 i.e. "A"
up to but not including index -2 i.e. 2
are deleted from the list in place. In other words, the elements "A"
, "B"
and "C"
are deleted.References
Control and Evaluations Part 2 - Index and Negative Indexing
Control and Evaluations Part 2 - Deleting Elements and Lists
Question 15
dict = { 'a': 1, 'b': 2, 'c': 3 }
for item in dict:
print(item)
- A.
a
b
c
- B.
1
2
3
- C.
a:1
b:2
c:3
- D.
0
1
2
- E. The code is erroneous
A
Explanation
When we use a
for
loop with a single variable to iterate over a dictionary object, we are iterating over the keys in the dictionary by default. In this case the keys are 'a'
, 'b'
and 'c'
where the print()
function defaults to a new line feed character \n
as its end sequence.References
Data Aggregates Part 2 - Iterating Dictionaries
Question 16
s = 'python'
for i in range(len(s)):
i = s[i].upper()
print(s, end="")
- A.
PYTHON
- B.
Python
- C.
python
- D.
P
Y
T
H
O
N
- E.
P
y
t
h
o
n
- F. The code will cause a runtime exception
C.
python
Explanation
The length of the string literal
'python'
is 6, thus range(6)
will return an iterable of integers 0, 1, 2, 3, 4 and 5. The for
loop will assign to the inner variable i
the uppercase character at the current index. However the final print()
function exists outside of the scope of the for
loop and prints the value assigned to the variable s
which is not changed by the for
loop in any event. Therefore the final output is simply the original string literal assigned to the variable s
, namely python
.References
Data Aggregates Part 1 - Advanced Strings
Question 17
lst = [i // i for i in range(0,4)]
sum = 0
for n in lst:
sum += n
print(sum)
- A.
0
- B.
3
- C.
7
- D.
11
- E. The program will cause a runtime exception
E. The program will cause a runtime exception
Explanation
In the list comprehension used to create the list called
lst
, Python will attempt the floor division 0 // 0
which is undefined and hence will raise a ZeroDivisionError
exception.References
Control and Evaluations Part 1 - Arithmetic Operators
Data Aggregates Part 1 - List Comprehension
IO and Exceptions - Exceptions
Question 18
lst = [[c for c in range(r)] for r in range(3)]
for x in lst:
for y in x:
if y < 2:
print('*', end='')
- A. One
- B. Two
- C. Three
- D. Four
- E. The program will cause a runtime exception/error
C. Three
Explanation
The list comprehension used to create the list object assigned to the variable
lst
will return the list of elements [[], [0], [0, 1]]
. In the outer for
loop, x
will be assigned each sub-list in lst
. In the inner for
loop, y
will be assigned each element in the current sub-list. If the current element in the current sub-list has a value less than 2 (which occurs three times), then the *
character will be printed.References
Data Aggregates Part 1 - List Comprehension
Control and Evaluations Part 2 - For Loop
Control and Evaluations Part 2 - Range Function
Question 19
1024
to the monitor?lst = [2 ** x for x in range(0, 11)]
print(lst???)
- A.
[0]
- B.
[1]
- C.
[-1]
- D.
[1024]
- E.
[:]
C.
[-1]
Explanation
The list comprehension used to create the list object assigned to the variable
lst
will return the list of elements [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024]
. Hence to access the element with value 1024
, we use the index -1
which refers to the last element in a sequence.References
Data Aggregates Part 1 - List Comprehension
Control and Evaluations Part 2 - Range Function
Control and Evaluations Part 2 - Index and Negative Indexing
Question 20
lst1 = "12,34"
lst2 = lst1.split(',')
print(len(lst1) < len(lst2))
- A.
True
- B.
False
- C.
None
- D. The program will cause a runtime exception/error
B.
False
Explanation
The variable
lst1
will reference a string object with the literal value '12,34'
and hence is of length 5. The variable lst2
will reference a list object with string elements ['12', '34']
and hence is of length 2. The final <
comparison operator will evaluate 5 < 2
which will return False
.References
Control and Evaluations Part 2 - String Methods
Functions and Modules
Question 21
def fun(a, b=0, c=5, d=1):
return a ** b ** c
print(fun(b=2, a=2, c=3))
- A. print
5
- B. print
64
- C. print
256
- D. print
512
- E. The program will cause a runtime exception/error
C. print
256
Explanation
The function named
fun
returns the evaluation of a ** (b ** c)
which, when passed the arguments a=2
, b=2
and c=3
evaluates to 2 ** (2 ** 3) = 2 ** 8 = 256
.References
Functions and Modules Part 1 - Defining Functions
Functions and Modules Part 1 - Calling Functions
Functions and Modules Part 1 - Keyword Arguments
Control and Evaluations Part 1 - Arithmetic Operators
Control and Evaluations Part 1 - Operator Precedence
Question 22
x = 5
f = lambda x: 1 + 2
print(f(x))
- A. print
5
- B. print
8
- C. print
3
- D. The program will cause a runtime exception/error
C. print
3
Explanation
The expression contained within the lambda function
f = lambda x: 1 + 2
is 1 + 2
which does not operate on the given argument x
. In this case therefore, 1 + 2 = 3
will always be returned by this lambda function, regardless of the argument value passed when the function is called..References
Functions and Modules Part 1 - Lambda Functions
Question 23
from math import pi as xyz # line 01
print(pi) # line 02
- A. The program will print the mathematical constant π = 3.141592..., to available precision
- B. The program will cause a runtime exception/error
- C. The program makes an alias for the name
pi
in the form ofxyz
- D. The original name
pi
will become inaccessible - E. Replacing line 02 with
print(xyz)
will cause the program to run without errors
B, C, D and E
Explanation
This program will make an alias for the constant value
pi
called xyz
, meaning that any references to pi
in the subsequent code must be replaced with references to its alias xyz
.References
Functions and Modules Part 2 - Importing Modules
Question 24
__init__.py
file? (Select all that apply)- A. It cannot be an empty file
- B. It can execute an initialization code for a package
- C. It is required to make Python treat a given directory as a Python package directory
- D. It is required to make Python treat a given directory containing packages as a directory without packages
B and C
Explanation
In order for Python to treat a directory as a package, it must contain a file named
__init__.py
. This initialisation file can either be empty, or hold Python code that is executed when that package is initialised. But in either case, the file must exist for that directory to be treated as a package.References
Functions and Modules Part 2 - Init File
Question 25
from random import randint
for i in range(10):
print(random(1, 5))
- A. The program will generate a sequence of ten (pseudo)random integers from
1
to5
- B. The program will generate a sequence of ten (pseudo)random integers from
1
to4
- C. The program will generate a sequence of ten (pseudo)random numbers from
1
to5
- D. The program will generate a sequence of ten (pseudo)random numbers from
1
to4
- E. The result cannot be predicted
- F. The program will cause a runtime exception/error
F. The program will cause a runtime exception/error
Explanation
In this Python program, we import the entity named
randint
from the Python module named random
. At no point do we explicitly import an entity named random
. Therefore the subsequent call to the random()
function will raise a NameError
exception as the name random
is not defined.References
Functions and Modules Part 2 - Importing Modules
Question 26
x = 1 # line 1
def a(x): # line 2
return 2 * x # line 3
x = 2 + a(x) # line 4
print(a(x)) # line 5
- A. print
8
- B. print
4
- C. print
6
- D. Cause a runtime exception on line 4
- E. Cause a runtime exception on line 5
A. print
8
Explanation
The function named
a()
will return a given argument value multiplied by two. The variable x
is initially assigned the value 1
. It is then assigned the evaluation of 2 + a(x) = 2 + a(1) = 2 + 2 = 4
. Finally the print()
function will print a(x) = a(4) = 8
.References
Functions and Modules Part 1 - Functions
Functions and Modules Part 1 - Name Scope
Question 27
a = 'hello' # line 1
def x(a,b): # line 2
z = a[0] # line 3
return z # line 4
print(x(a)) # line 5
- A. print
hello
- B. print
h
- C. print
ello
- D. Cause a runtime exception on line 2
- E. Cause a runtime exception on line 3
- F. Cause a runtime exception on line 4
- G. Cause a runtime exception on line 5
G. Cause a runtime exception on line 5
Explanation
The function
x()
expects to be passed two positional arguments a
and b
. The function body does not operate on the argument b
, but nevertheless since it is defined in the function header and is not defined with a default value, then is must be passed to the function when it is called. Subsequently execution of line 5 will raise a TypeError
exception since a second positional argument value is not passed to the function.References
Functions and Modules Part 1 - Calling Functions
Question 28
s = 'SPAM'
def f(x):
return s + 'MAPS'
print(f(s))
- A. It will print:
SPAM
- B. It will print:
MAPS
- C. It will print:
None
- D. It will print:
SPAMMAPS
- E. It will print:
SPAM MAPS
- F. It will cause a runtime exception/error
- G. It will print an empty line
D. It will print:
SPAMMAPS
Explanation
The function named
f()
will return a new string object with a literal value starting with the string literal assigned to the variable named s
concatenated with the string literal MAPS
. However since there is no variable with local scope named s
, Python will instead use the variable named s
that is defined outside of the function and hence has global scope.References
Functions and Modules Part 1 - Name Scope
Question 29
- A. Positional arguments are also called keyword arguments
- B. The order of arguments matters when they are passed positionally
- C. The order of arguments matters when they are passed by their name
- D. A function can be called with a mix of positional and keyword arguments
B and D
Explanation
Unless we are using Keyword Arguments to send arguments to functions, then the order of the arguments (referred to as positional arguments) is important and must match the order defined in the function header. Furthermore, when calling a function, it must be called with the correct number of arguments as defined in the function header. If not, a
TypeError
exception is raised. Finally Python allows us to call a function with a mix of positional and keyword arguments using the /
and *
operators respectively.References
Functions and Modules Part 1 - Calling Functions
Functions and Modules Part 1 - Passing Mixed Arguments
Question 30
def gen():
lst = range(5)
for i in lst:
yield i*i
for i in gen():
print(i, end="")
- A. It will print:
- B. It will print:
014916
- C. It will print:
0
1
4
9
16
- D. It will cause a runtime exception/error
- E. It will print an empty line
B. It will print:
014916
Explanation
The generator function named
gen()
will return a lazy iterator of integers where the full set of elements that will be lazily evaluated are 0, 1, 4, 9 and 16. The for
loop will iterate over the iterable object returned by the gen()
generator function and print the next lazily evaluated integer element, where the default end sequence for the print()
function is replaced with ""
.References
Functions and Modules Part 1 - Generator Functions
Functions and Modules Part 1 - Generators and For Loops
Control and Evaluations Part 2 - Range Function
Classes and Exceptions
Question 31
- A. The
class
keyword marks the beginning of the class definition - B. An object cannot contain any references to other objects
- C. A class may define an object
- D. A constructor is used to instantiate an object
- E. An object variable is a variable that is stored separately in every object
A, C and D
Explanation
We create a class using the
class
keyword followed by the name of the class and then the : colon operator. Instances of classes are called objects, where a special type of methods called a constructor is executed when a new instance of a class is instantiated.References
Classes and Objects Part 1 - Classes
Classes and Objects Part 1 - Objects
Classes and Objects Part 1 - Constructors
Question 32
- A. Inheritance means passing attributes and methods from a superclass to a subclass
- B.
issubclass(class1, class2)
is an example of a function that returnsTrue
ifclass2
is a subclass ofclass1
- C. Multiple inheritance means that a class has more than one superclass
- D. Polymorphism is the situation in which a subclass is able to modify its superclass behavior
- E. A single inheritance is always more difficult to maintain than a multiple inheritance
A, C and D
Explanation
Inheritance refers to the ability for a class to inherit attributes and methods from a parent class. It is possible for a subclass to inherit from multiple base or superclasses simultaneously, in what is known as multiple inheritance. And overriding refers to the ability of subclasses to inherit methods from a superclass, but to then change the logic of those methods so that the behaviour is specific to that subclass, which is a feature of polymorphism.
References
Classes and Objects Part 1 - Inheritance
Classes and Objects Part 1 - Multiple Inheritance
Classes and Objects Part 1 - Overriding Methods
Question 33
- A. A class definition may have any number of constructors, but their names must be unique
- B. It is not possible to safely check if an object has a certain attribute
- C. A class constructor cannot return a value
- D.
__bases__
is a tuple filled with the names of all the direct superclasses - E.
issubclass(c1, c2)
is a function that checks ifc1
is an object derived from classc2
C and D
Explanation
A constructor is a special type of method whose method body is executed when a new instance of a class is instantiated, but returns no value. The
__bases__
special attribute, when applied to classes, is a tuple containing the base classes that a given class is inherited from.References
Classes and Objects Part 1 - Constructors
Classes and Objects Part 1 - Introspection
Question 34
# Example 1
x = 1
y = 0
z = x%y
print(z)
# Example 2
x = 1
y = 0
z = x/y
print(z)
- A. A
ZeroDivisionError
exception will be raised in Example 1, while Example 2 will print0
to the screen - B. A
ZeroDivisionError
exception will be raised in Example 2, while Example 1 will print0
to the screen - C. A
ZeroDivisionError
exception will be raised in Example 1 and Example 2 - D. A
ValueError
exception will be raised in Example 1, and aZeroDivisionError
exception will be raised in Example 2 - E. A
ValueError
exception will be raised in Example 2, and aZeroDivisionError
exception will be raised in Example 1
C. A
ZeroDivisionError
exception will be raised in Example 1 and Example 2Explanation
The
%
modulus operator returns the remainder after division. In example 1, division by zero is being attempted which will raise a ZeroDivisionError
exception. Similarly in example 2, division by zero is also being attempted which again will raise a ZeroDivisionError
exception.References
Control and Evaluations Part 1 - Arithmetic Operators
IO and Exceptions - Exceptions
Question 35
x = 0
try:
print(x)
print(1 / x)
except ZeroDivisionError:
print("ERROR MESSAGE")
finally:
print(x + 1)
print(x + 2)
- A.
1
2
- B.
ERROR MESSAGE
1
2
- C.
0
2
- D.
0
ERROR MESSAGE
1
2
D
Explanation
The variable
x
is assigned the value 0
which will be printed first. Then an attempt to divide by zero will be attempted in print(1 / x)
which will raise a ZeroDivisionError
exception. This exception will be handled by the except
clause which will print ERROR MESSAGE
. The finally
clause will be executed next, which will print the value x + 1 = 0 + 1 = 1
. And finally, since the ZeroDivisionError
exception has been handled and the Python application will not have terminated on an unhandled exception, x + 2 = 1 + 2 = 3
will be printed.References
IO and Exceptions - Try Except Finally
Question 36
class A:
def a(self):
print("A", end='')
class B(A):
def a(self):
print("B", end='')
class C(B):
def b(self):
print("B", end='')
a = A()
b = B()
c = C()
a.a()
b.a()
c.b()
- A.
AB
- B.
ABB
- C.
BA
- D.
BBA
- E.
AAA
- F.
BBB
B.
ABB
Explanation
The object
a
is instantiated from the class A
where its method named a()
will print the letter A
. The object b
is instantiated from the class B
which is derived from the class A
. However class B
overrides the method a()
with its own implementation which will print the letter B
. Finally object c
is instantiated from the class C
which is derived from the class B
, but which defines a new method named b()
which will print the letter B
. All calls to the print()
function across all classes and methods replace the default print end sequence with ''
.References
Classes and Objects Part 1 - Inheritance
Classes and Objects Part 1 - Overriding Methods
Question 37
try:
print("Hello")
raise Exception
print(1/0)
except Exception as e:
print(e)
- A. Two identical non-empty lines
- B. Two different non-empty lines
- C. Two empty lines
- D. One non-empty line and one empty line
D. One non-empty line and one empty line
Explanation
First the
print("Hello")
statement will be executed, which will print a non-empty line containing the string literal Hello
. Next an exception of type Exception
is explicitly raised, but without an error message. This exception is handled by the except
clause which will print an empty line as no error message was provided when the exception was explicitly raised.References
IO and Exceptions - Raising Exceptions
Question 38
CriticalError
have been raised separately?# Example 1
class CriticalError(Exception):
def __init__(self, message='ERROR MESSAGE A'):
Exception.__init__(self, message)
raise CriticalError
raise CriticalError("ERROR MESSAGE B")
# Example 2
class CriticalError(Exception):
def __init__(self, message='ERROR MESSAGE A'):
Exception.__init__(self, message)
raise CriticalError("ERROR MESSAGE B")
- A. No, both errors raised will display the same message:
ERROR MESSAGE A
- B. No, both errors raised will display the same message:
ERROR MESSAGE B
- C. No, both errors raised will display no message
- D. Yes, the first error raised will display the message
ERROR MESSAGE A
, while the secondERROR MESSAGE B
- E. Yes, the first error raised will display no message, while the second
ERROR MESSAGE B
- F. Yes, the first error raised will display no message, while the second
ERROR MESSAGE A
D. Yes, the first error raised will display the message
ERROR MESSAGE A
, while the second ERROR MESSAGE B
Explanation
In example 1, the statement
raise CriticalError
will explicitly raise a user-defined exception of type CriticalError
which will print a stacktrace followed by the message CriticalError: ERROR MESSAGE A
. However since there is no except
clause to handle exceptions of type CriticalError
, the statement raise CriticalError("ERROR MESSAGE B")
will never be executed as the Python application will have already terminated. In example 2, the statement raise CriticalError("ERROR MESSAGE B")
will explicitly raise a user-defined exception of type CriticalError
but with a custom error message that will override the default message string literal value. Therefore, a stacktrace will be printed followed by the message CriticalError: ERROR MESSAGE B
.References
IO and Exceptions - User Defined Exceptions
IO and Exceptions - Unhandled Exceptions
Question 39
test.txt
file and retrieve each line in it. Which option will you use? (Select all that apply)file = open(test.txt)
# insert code here
file.close()
- A.
print(file.readlines())
- B.
print(readlines(file))
- C.
print(file.readlines(:)
- D.
for l in file:
print(l)
- E.
print(file.lines())
- F.
print(file.read())
- G.
print(read.file(test.txt))
A, D and F
Explanation
The method
file.readlines()
returns a list containing each line in a file as a list item. The method file.read()
without a size argument will read the entire contents of a file.References
IO and Exceptions - Reading Files
IO and Exceptions - Common File Methods
Question 40
f = open("file.txt", "w")
f.close()
- A. Open the file
file.txt
in write mode - B. Delete the file contents if the file
file.txt
already exists - C. Leave the file contents unchanged if the file
file.txt
already exists - D. Create the file
file.txt
if it does not exist - E. Raise the
FileNotFoundError
exception if the file does not exist
A, B and D
Explanation
To write to a file in Python, we first invoke the Python
open()
function in either write-mode 'w'
, append-mode 'a'
or exclusive creation mode 'x'
. Both write-mode and append-mode are used to write to existing files, but the key difference is that in write-mode, the contents of the file will be ovewritten if the file already exists, whereas in append-mode the file will be appended to. In both cases, if the files does not already exist then the file is created.References
IO and Exceptions - Writing Files
Thank You
Thank you for taking the time to complete our Introduction to Python course. You now have a strong coding foundation which includes knowledge of general computing concepts, common data structures, control flow, functions and object oriented programming, from which to develop a modern professional career in data science, software engineering and/or data engineering amongst other career pathways.
What's Next
Schedule a PCAP examination to test your knowledge and become certified in a skill that is in high-demand across all industries!
