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
The following expression
is:
- A. Invalid
- B. Equal to
16
- C. Equal to
16.0
- D. Equal to
512
- E. Equal to
64
- F. Equal to
128.0
AnswerD. Equal to
512
ExplanationThe 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
.
ReferencesControl and Evaluations Part 1 -
Arithmetic OperatorsControl and Evaluations Part 1 -
Operator Precedence Question 2
If you want to build a string that reads:
Peter's sister's name's "Anna"
which of the following literals would you use? (Select all that apply)
- 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"'
AnswerA and B
ExplanationThe 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.
ReferencesControl and Evaluations Part 2 -
Escape Character Question 3
What is the expected output of the following snippet?
i = 250
while len(str(i)) > 72:
i *= 2
else:
i //= 2
print(i)
AnswerA.
125
ExplanationThe
*
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
.
ReferencesControl and Evaluations Part 1 -
Arithmetic OperatorsControl and Evaluations Part 1 -
Assignment OperatorsControl and Evaluations Part 2 -
While-else Loop Question 4
What snippet would you insert in the line indicated below:
n = 0
while n < 4:
n += 1
# insert your code here
to print the following string to the monitor after the loop finishes its execution:
- A.
print(n)
- B.
print(n, sep=" ")
- C.
print(n, end=" ")
- D.
print(n, " ")
AnswerC.
print(n, end=" ")
ExplanationThe 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.
ReferencesControl and Evaluations Part 2 -
Print FunctionControl and Evaluations Part 2 -
While Loop Question 5
What is the value type returned after executing the following snippet?
x = 0
y = 2
z = len("Python")
x = y > z
print(x)
- A.
int
- B.
float
- C.
str
- D.
bool
- E.
NoneType
AnswerD.
bool
ExplanationThe
>
'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
.
ReferencesControl and Evaluations Part 1 -
Assignment OperatorsControl and Evaluations Part 1 -
Comparison Operators Question 6
What will the final value of the
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
AnswerA.
0
ExplanationThe
^
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
.
ReferencesControl and Evaluations Part 1 -
Bitwise XOR Question 7
Which line can be used instead of the comment to cause the snippet to produce the following expected output? (Select all that apply)
z, y, x = 2, 1, 0
x, z = z, y
y = y - z
# put line here
print(x, y, z)
Expected output:
- 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
AnswerA and B
ExplanationSequence 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.
ReferencesData Aggregates Part 2 -
Tuple Assignment Question 8
What is the expected output of the following snippet?
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
AnswerC.
3
ExplanationThe
**
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
.
ReferencesControl and Evaluations Part 1 -
Arithmetic OperatorsControl and Evaluations Part 2 -
If-elif Statement Question 9
How many stars (*) does the following snippet print?
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
AnswerA. Three
ExplanationThe 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.
ReferencesControl and Evaluations Part 2 -
While-else LoopControl and Evaluations Part 2 -
Break Statement Question 10
How many lines does each of the following code examples output when run separately?
# 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
AnswerA. Example 1: two, Example 2: one, Example 3: one, Example 4: one
ExplanationIn 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.
ReferencesControl and Evaluations Part 2 -
For LoopControl and Evaluations Part 2 -
Range FunctionControl and Evaluations Part 2 -
Print Function Data Aggregates
Question 11
Which of the following statements are true? (Select all that apply)
- 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
AnswerD and G
ExplanationUnicode 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.
ReferencesData Aggregates Part 1 -
Character EncodingsData Aggregates Part 1 -
Advanced StringsData Aggregates Part 1 -
Advanced Lists Question 12
What is the result of the following comparison?
x = "20"
y = "30"
print(x > y)
- A.
True
- B.
False
- C.
None
- D. The comparison causes a runtime exception/error
AnswerB.
False
ExplanationSequence 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.
ReferencesData Aggregates Part 1 -
String ComparisonsData Aggregates Part 1 -
Character Encodings Question 13
What is the expected output of the following snippet?
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
AnswerA.
Hello, Python!
ExplanationIn 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.
ReferencesControl and Evaluations Part 2 -
List SlicingControl and Evaluations Part 2 -
Index and Negative IndexingData Aggregates Part 1 -
Advanced String Slicing Question 14
What is the expected output of the following snippet?
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']
AnswerA.
[2, 4]
ExplanationThe
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.
ReferencesControl and Evaluations Part 2 -
Index and Negative IndexingControl and Evaluations Part 2 -
Deleting Elements and Lists Question 15
What is the expected output of the following snippet?
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
AnswerA
ExplanationWhen 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.
ReferencesData Aggregates Part 2 -
Iterating Dictionaries Question 16
What is the expected output of the following snippet?
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
AnswerC.
python
ExplanationThe 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
.
ReferencesData Aggregates Part 1 -
Advanced Strings Question 17
What is the expected output of the following snippet?
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
AnswerE. The program will cause a runtime exception
ExplanationIn 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.
ReferencesControl and Evaluations Part 1 -
Arithmetic OperatorsData Aggregates Part 1 -
List ComprehensionIO and Exceptions -
Exceptions Question 18
How many stars (*) will the following snippet send to the console?
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
AnswerC. Three
ExplanationThe 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.
ReferencesData Aggregates Part 1 -
List ComprehensionControl and Evaluations Part 2 -
For LoopControl and Evaluations Part 2 -
Range Function Question 19
What would you insert instead of ??? so that the program prints
1024
to the monitor?
lst = [2 ** x for x in range(0, 11)]
print(lst???)
- A.
[0]
- B.
[1]
- C.
[-1]
- D.
[1024]
- E.
[:]
AnswerC.
[-1]
ExplanationThe 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.
ReferencesData Aggregates Part 1 -
List ComprehensionControl and Evaluations Part 2 -
Range FunctionControl and Evaluations Part 2 -
Index and Negative Indexing Question 20
What is the expected output of the following snippet?
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
AnswerB.
False
ExplanationThe 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
.
ReferencesControl and Evaluations Part 2 -
String Methods Functions and Modules
Question 21
What is the expected behavior of the following snippet?
def fun(a, b=0, c=5, d=1):
return a ** b ** c
print(fun(b=2, a=2, c=3))
It will:
- A. print
5
- B. print
64
- C. print
256
- D. print
512
- E. The program will cause a runtime exception/error
Question 22
What is the expected behavior of the following snippet?
x = 5
f = lambda x: 1 + 2
print(f(x))
It will:
- A. print
5
- B. print
8
- C. print
3
- D. The program will cause a runtime exception/error
AnswerC. print
3
ExplanationThe 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..
ReferencesFunctions and Modules Part 1 -
Lambda Functions Question 23
What can we deduce from the following snippet? Select the true sentences. (select all that apply)
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 of xyz
- D. The original name
pi
will become inaccessible - E. Replacing line 02 with
print(xyz)
will cause the program to run without errors
AnswerB, C, D and E
ExplanationThis 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
.
ReferencesFunctions and Modules Part 2 -
Importing Modules Question 24
What is true about the
__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
AnswerB and C
ExplanationIn 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.
ReferencesFunctions and Modules Part 2 -
Init File Question 25
What is the expected behavior of the following code snippet?
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
to 5
- B. The program will generate a sequence of ten (pseudo)random integers from
1
to 4
- C. The program will generate a sequence of ten (pseudo)random numbers from
1
to 5
- D. The program will generate a sequence of ten (pseudo)random numbers from
1
to 4
- E. The result cannot be predicted
- F. The program will cause a runtime exception/error
AnswerF. The program will cause a runtime exception/error
ExplanationIn 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.
ReferencesFunctions and Modules Part 2 -
Importing Modules Question 26
What is the expected behavior of the following snippet?
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
It will:
- 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
AnswerA. print
8
ExplanationThe 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
.
ReferencesFunctions and Modules Part 1 -
FunctionsFunctions and Modules Part 1 -
Name Scope Question 27
What is the expected behavior of the following snippet?
a = 'hello' # line 1
def x(a,b): # line 2
z = a[0] # line 3
return z # line 4
print(x(a)) # line 5
It will:
- 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
AnswerG. Cause a runtime exception on line 5
ExplanationThe 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.
ReferencesFunctions and Modules Part 1 -
Calling Functions Question 28
What is the expected behavior of the following snippet?
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
AnswerD. It will print:
SPAMMAPS
ExplanationThe 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.
ReferencesFunctions and Modules Part 1 -
Name Scope Question 29
Select the true statements: (select all that apply)
- 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
AnswerB and D
ExplanationUnless 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.
ReferencesFunctions and Modules Part 1 -
Calling FunctionsFunctions and Modules Part 1 -
Passing Mixed Arguments Question 30
What is the expected behavior of the following snippet?
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
AnswerB. It will print:
014916
ExplanationThe 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
""
.
ReferencesFunctions and Modules Part 1 -
Generator FunctionsFunctions and Modules Part 1 -
Generators and For LoopsControl and Evaluations Part 2 -
Range Function Classes and Exceptions
Question 31
Select the true statements: (select all that apply)
- 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
AnswerA, C and D
ExplanationWe 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.
ReferencesClasses and Objects Part 1 -
ClassesClasses and Objects Part 1 -
ObjectsClasses and Objects Part 1 -
Constructors Question 32
Select the true statements: (select all that apply)
- A. Inheritance means passing attributes and methods from a superclass to a subclass
- B.
issubclass(class1, class2)
is an example of a function that returns True
if class2
is a subclass of class1
- 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
AnswerA, C and D
ExplanationInheritance 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.
ReferencesClasses and Objects Part 1 -
InheritanceClasses and Objects Part 1 -
Multiple InheritanceClasses and Objects Part 1 -
Overriding Methods Question 33
Select the true statements: (select all that apply)
- 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 if c1
is an object derived from class c2
AnswerC and D
ExplanationA 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.
ReferencesClasses and Objects Part 1 -
ConstructorsClasses and Objects Part 1 -
Introspection Question 34
What will happen when you run each of the following code snippets?
# 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 print 0
to the screen - B. A
ZeroDivisionError
exception will be raised in Example 2, while Example 1 will print 0
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 a ZeroDivisionError
exception will be raised in Example 2 - E. A
ValueError
exception will be raised in Example 2, and a ZeroDivisionError
exception will be raised in Example 1
AnswerC. A
ZeroDivisionError
exception will be raised in Example 1 and Example 2
ExplanationThe
%
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.
ReferencesControl and Evaluations Part 1 -
Arithmetic OperatorsIO and Exceptions -
Exceptions Question 35
What is the expected output of the following code?
x = 0
try:
print(x)
print(1 / x)
except ZeroDivisionError:
print("ERROR MESSAGE")
finally:
print(x + 1)
print(x + 2)
The program will print the following to the screen:
- A.
1
2
- B.
ERROR MESSAGE
1
2
- C.
0
2
- D.
0
ERROR MESSAGE
1
2
AnswerD
ExplanationThe 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.
ReferencesIO and Exceptions -
Try Except Finally Question 36
The following class hierarchy is given. What is the expected output of the code?
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
AnswerB.
ABB
ExplanationThe 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
''
.
ReferencesClasses and Objects Part 1 -
InheritanceClasses and Objects Part 1 -
Overriding Methods Question 37
If the following snippet is executed and the exception is raised
try:
print("Hello")
raise Exception
print(1/0)
except Exception as e:
print(e)
we will see:
- 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
AnswerD. One non-empty line and one empty line
ExplanationFirst 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.
ReferencesIO and Exceptions -
Raising Exceptions Question 38
Is there any difference in the error messages displayed once the two newly defined exceptions
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 second ERROR 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
AnswerD. Yes, the first error raised will display the message
ERROR MESSAGE A
, while the second
ERROR MESSAGE B
ExplanationIn 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
.
ReferencesIO and Exceptions -
User Defined ExceptionsIO and Exceptions -
Unhandled Exceptions Question 39
You want to access the
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))
AnswerA, D and F
ExplanationThe 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.
ReferencesIO and Exceptions -
Reading FilesIO and Exceptions -
Common File Methods Question 40
The following code snippet when run
f = open("file.txt", "w")
f.close()
will (select all that apply):
- 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
AnswerA, B and D
ExplanationTo 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.
ReferencesIO 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!