Home Blog
Practice Tests
πŸ“ Matric Mathematics βš—οΈ Physical Sciences 🌿 Life Sciences πŸš— K53 Learners Licence ☁️ AWS Cloud Practitioner πŸ”’ CompTIA Security+ πŸ₯ NCLEX Nursing 🌍 General Knowledge 🧠 IQ & Logic 🧬 Psychology
Privacy Policy Disclaimer
Practice Free
Home › Practice Tests › IT Certifications
IT Certifications

Python PCEP Certification

150 practice questions and 100 flashcards for the PCEP Python Certified Entry-Level Programmer exam. Covers syntax, data types, control flow, functions, exceptions, and OOP fundamentals.

The Python Institute PCEP-30-02 (Certified Entry-Level Python Programmer) certification validates foundational Python programming knowledge and is the starting point for the Python Institute's certification pathway. It is recognised by South African employers in technology, data science, and automation roles as verified evidence of Python fundamentals. This practice set covers all four PCEP exam blocks: Computer Programming and Python Fundamentals (18%), Control Flow (29%), Data Collections β€” Lists, Tuples, Dictionaries, Strings (25%), and Functions and Exceptions (28%).

The PCEP exam tests code-reading skills almost exclusively β€” you are shown a Python snippet and asked what it will output, what error it will raise, or what value a variable will hold after execution. This requires a specific mental skill: tracing code execution in your head, step by step, following Python's exact rules. Writing code is a different skill from reading and predicting code β€” most Python tutorials teach the former while the PCEP tests the latter.

The areas where most candidates make errors on the PCEP: operator precedence (multiplication before addition, comparisons before logical operators), integer division and modulo (7//2=3, 7%2=1), string immutability (strings cannot be modified in place), list mutability and reference behaviour (two variables pointing to the same list both change when either is modified), and variable scope (local vs global in functions). The flashcard set targets these specific concepts.

150 practice questions and 100 flashcards for the PCEP Python Certified Entry-Level Programmer exam. Covers syntax, data types, control flow, functions, exceptions, and OOP fundamentals.

0/150
correct answers
Question 01 of 150
What does PCEP stand for?
Explanation: PCEP (Python Certified Entry-Level Programmer) is an entry-level certification by the Python Institute that validates fundamental Python programming skills including syntax, data types, control flow, functions, and basic OOP concepts.
Question 02 of 150
Which of the following is a valid Python variable name?
Explanation: Variable names must start with a letter or underscore, contain only letters, digits, and underscores, and cannot be Python keywords. _myVar is valid. 2variable starts with a digit, my-var contains a hyphen, class is a reserved keyword.
Question 03 of 150
What is the output of: print(type(3.14))?
Explanation: 3.14 is a floating-point literal in Python, so type(3.14) returns . Python has int, float, complex, str, bool, list, tuple, dict, set as built-in types.
Question 04 of 150
What does the // operator do in Python?
Explanation: // is the floor division operator. It divides and rounds down to the nearest integer. 7 // 2 = 3 (not 3.5). Compare: / returns a float (7/2 = 3.5), % returns the remainder (7%2 = 1).
Question 05 of 150
What is the output of: print(10 % 3)?
Explanation: The % operator returns the remainder of division. 10 Γ· 3 = 3 remainder 1. So 10 % 3 = 1. Tour is the modulo operator, useful for checking even/odd (n % 2 == 0 means even).
Question 06 of 150
Which data type is immutable in Python?
Explanation: Tuples are immutable β€” once created, their elements cannot be changed. Lists, dicts, and sets are mutable. Immutability makes tuples hashable (usable as dictionary keys). Strings are also immutable in Python.
Question 07 of 150
What is the correct way to create an empty dictionary?
Explanation: {} creates an empty dictionary. [] creates an empty list. () creates an empty tuple. set() creates an empty set (you cannot use {} for empty set as that creates an empty dict).
Question 08 of 150
What does len('Hello') return?
Explanation: len() returns the number of characters in a string. 'Hello' has 5 characters: H, e, l, l, o. Note that len() counts all characters including spaces and special characters.
Question 09 of 150
What is the output of: print(bool(0))?
Explanation: In Python, 0 evaluates to False in boolean context. Falsy values: 0, 0.0, '', [], {}, (), set(), None. All other values are truthy. bool(0) returns False.
Question 10 of 150
Which keyword is used to define a function in Python?
Explanation: def is the keyword used to define functions in Python. Syntax: def function_name(parameters): followed by an indented body. The function executes when called.
Question 11 of 150
What is the output of: print(2 ** 3)?
Explanation: ** is the exponentiation operator. 2 ** 3 means 2 to the power of 3 = 2 Γ— 2 Γ— 2 = 8. Compare: 2 * 3 = 6 (multiplication).
Question 12 of 150
What is the output of: print('Hello' + ' ' + 'World')?
Explanation: + is the string concatenation operator. 'Hello' + ' ' + 'World' joins the three strings together to produce 'Hello World'. Note: you cannot concatenate strings with non-strings directly (e.g., 'a' + 1 raises TypeError).
Question 13 of 150
Which of the following correctly creates a list?
Explanation: Lists are created with square brackets []. Parentheses () create tuples. Curly braces {} create sets or dictionaries. Lists are ordered, mutable, and allow duplicate elements.
Question 14 of 150
What does the input() function always return?
Explanation: input() always returns a string, regardless of what the user types. To use the input as a number, you must convert it: int(input()) or float(input()). Tour is a common source of bugs for beginners.
Question 15 of 150
What is the output of: print(type(True))?
Explanation: True is a boolean literal. type(True) returns . Interestingly, in Python, bool is a subclass of int: True == 1 and False == 0 evaluate to True.
Question 16 of 150
Which of the following is NOT a valid string literal?
Explanation: 'hello" mixes quote types β€” it opens with a single quote and would need to close with a single quote. Valid string literals: single quotes 'hello', double quotes "hello", triple quotes for multiline strings.
Question 17 of 150
What is the output of: x = [1,2,3]; print(x[0])?
Explanation: Python uses zero-based indexing. x[0] is the first element, which is 1. x[1] is 2, x[2] is 3. Negative indexing: x[-1] is 3 (last element), x[-2] is 2.
Question 18 of 150
What does the range(5) function generate?
Explanation: range(5) generates integers from 0 to 4 (not including 5). range(start, stop, step) β€” default start is 0, default step is 1. range(1,6) generates 1-5. range(0,10,2) generates 0,2,4,6,8.
Question 19 of 150
What is the correct syntax for a for loop in Python?
Explanation: Python for loops use 'for variable in iterable:' syntax. No parentheses required around the condition, no semicolons, and no curly braces β€” indentation defines the loop body.
Question 20 of 150
What is the output of: print(len([1,2,3,4,5]))?
Explanation: len() returns the number of elements in a list. [1,2,3,4,5] has 5 elements, so len() returns 5.
Question 21 of 150
Which comparison operator checks if two values are NOT equal?
Explanation: != is the not-equal operator in Python. Example: 5 != 3 is True. The old <> operator from Python 2 is no longer valid in Python 3.
Question 22 of 150
What does 'None' represent in Python?
Explanation: None is Python's null value β€” it represents the absence of a value. Functions that don't explicitly return a value return None. It is the sole instance of NoneType. Check: if x is None: (use 'is', not ==).
Question 23 of 150
What is the output of: print('abc'.upper())?
Explanation: The .upper() string method returns a copy of the string with all characters converted to uppercase. 'abc'.upper() returns 'ABC'. Similarly: .lower() for lowercase, .title() for Title Case.
Question 24 of 150
What is the correct way to write a single-line comment in Python?
Explanation: # is the comment character in Python. Everything after # on the same line is ignored by the interpreter. Python has no built-in multi-line comment syntax β€” use triple-quoted strings """...""" as a workaround.
Question 25 of 150
What does the append() method do to a list?
Explanation: list.append(element) adds the element to the end of the list. Other useful methods: insert(index, element) inserts at position, extend([a,b]) adds multiple elements, remove(value) removes first occurrence, pop() removes and returns last element.
Question 26 of 150
What is the output of: print(3 == 3.0)?
Explanation: 3 == 3.0 evaluates to True because Python compares values across numeric types. The integer 3 and float 3.0 have the same value. Note: 3 is 3.0 would be False because 'is' checks identity, not equality.
Question 27 of 150
Which keyword exits a loop immediately?
Explanation: break immediately terminates the innermost loop. continue skips the rest of the current iteration and moves to the next. pass does nothing (placeholder). return exits a function.
Question 28 of 150
What is a dictionary in Python?
Explanation: A dictionary (dict) is an unordered (insertion-ordered in Python 3.7+) collection of key-value pairs. Keys must be unique and hashable. Access: dict[key]. Create: {'key': value}. Methods: .keys(), .values(), .items().
Question 29 of 150
What is the output of: print('Hello'[1])?
Explanation: String indexing: 'Hello'[0]='H', [1]='e', [2]='l', [3]='l', [4]='o'. Strings are sequences and support indexing just like lists.
Question 30 of 150
What is the correct way to check if a key exists in a dictionary?
Explanation: 'key in dict' is the correct Python idiom. It returns True if the key exists. You can also use dict.get(key) which returns None (or a default) if key not found, avoiding KeyError.
Question 31 of 150
What does the split() method do?
Explanation: str.split(separator) splits a string at each occurrence of the separator and returns a list. 'a,b,c'.split(',') returns ['a','b','c']. Without argument, splits on any whitespace.
Question 32 of 150
What is the output of: print(range(1,10,2))?
Explanation: print(range(1,10,2)) prints the range object representation: range(1, 10, 2). To print the values, convert to list: print(list(range(1,10,2))) which gives [1, 3, 5, 7, 9].
Question 33 of 150
What is the purpose of the 'return' statement in a function?
Explanation: return sends a value back to the caller and exits the function. A function without return (or with bare return) returns None. You can return multiple values as a tuple: return x, y.
Question 34 of 150
What is the output of: print(abs(-7))?
Explanation: abs() returns the absolute value (distance from zero, always non-negative). abs(-7) = 7. abs(7) = 7. abs(-3.5) = 3.5.
Question 35 of 150
Which of the following is a set?
Explanation: Sets are created with curly braces {}. They are unordered, unindexed, and contain unique elements. {} alone creates an empty dict; use set() for empty set. Sets support: union (|), intersection (&), difference (-).
Question 36 of 150
What does the 'pass' statement do?
Explanation: pass is a no-operation statement used as a placeholder where Python syntax requires a statement but you don't want to execute anything. Common use: empty function bodies, class definitions, or if/else branches during development.
Question 37 of 150
What is string slicing?
Explanation: Slicing extracts a portion of a sequence: s[start:stop:step]. s[1:4] returns characters at index 1,2,3. s[:3] = first 3. s[3:] = from index 3 onwards. s[::-1] reverses the string. Same syntax works for lists.
Question 38 of 150
What is the output of: print(max([3,1,4,1,5,9]))?
Explanation: max() returns the largest element. min() returns the smallest. sum() returns the total. sorted() returns a sorted copy. For [3,1,4,1,5,9], max is 9.
Question 39 of 150
Which of the following correctly opens a file for reading?
Explanation: File modes: 'r' = read (default), 'w' = write (overwrites), 'a' = append, 'x' = create (fails if exists), 'b' = binary mode. Best practice: use with open('file.txt', 'r') as f: β€” automatically closes the file.
Question 40 of 150
What is the output of: print('Python'[-1])?
Explanation: Negative indexing starts from the end: -1 is last character, -2 is second-to-last, etc. 'Python'[-1] = 'n' (last character). 'Python'[-2] = 'o'.
Question 41 of 150
What is the difference between a list and a tuple?
Explanation: Lists [] are mutable β€” you can change, add, remove elements. Tuples () are immutable β€” once created, they cannot be modified. Tuples are faster and can be used as dictionary keys. Lists are more flexible.
Question 42 of 150
What is the output of: x = 5; x += 3; print(x)?
Explanation: x += 3 is shorthand for x = x + 3. Starting with x=5: 5+3=8. Python supports: +=, -=, *=, /=, //=, %=, **= as augmented assignment operators.
Question 43 of 150
What does the join() method do?
Explanation: str.join(iterable) joins elements of an iterable into a string, using str as separator. ', '.join(['a','b','c']) returns 'a, b, c'. The elements must all be strings. Tour is the opposite of split().
Question 44 of 150
What is a lambda function?
Explanation: Lambda creates small anonymous functions: lambda x: x*2 is equivalent to def f(x): return x*2. Syntax: lambda parameters: expression. Lambdas can only contain a single expression (no statements). Used with map(), filter(), sorted().
Question 45 of 150
What is the output of: print(list(range(0, 6, 2)))?
Explanation: range(0, 6, 2) generates: 0, 2, 4 (stop at 6, not including 6). Converting to list: [0, 2, 4]. The step is 2, so it increments by 2 each time.
Question 46 of 150
What does try/except do in Python?
Explanation: try/except is Python's exception handling mechanism. Code in the try block is executed; if an exception occurs, execution jumps to the except block. Finally block always executes. Specific exceptions: except ValueError, except TypeError, etc.
Question 47 of 150
What is the output of: print(str(42))?
Explanation: str() converts a value to its string representation. str(42) returns the string '42'. Similarly, int('42') converts a string to integer. Tour type casting is essential when working with user input.
Question 48 of 150
What does the 'in' keyword do in Python?
Explanation: 'in' is a membership operator. 'a' in 'banana' is True. 3 in [1,2,3] is True. 'key' in dictionary checks for key existence. Also used in for loops: 'for item in list'.
Question 49 of 150
What is the output of: print(round(3.567, 2))?
Explanation: round(number, ndigits) rounds to ndigits decimal places. round(3.567, 2) = 3.57 (rounds up at 5). round(3.5) = 4. Note: Python uses banker's rounding β€” round(2.5) = 2, round(3.5) = 4.
Question 50 of 150
What is a module in Python?
Explanation: A module is a .py file containing Python code. Import with: import module_name or from module_name import function. Standard library modules: math, os, sys, random, datetime. Third-party: numpy, pandas (installed via pip).
Question 51 of 150
What is the purpose of __init__ in a class?
Explanation: __init__ is the constructor (initialiser) method called automatically when a class instance is created. 'self' refers to the instance. class Dog: def __init__(self, name): self.name = name. Then: d = Dog('Rex') sets d.name = 'Rex'.
Question 52 of 150
What is inheritance in OOP?
Explanation: Inheritance allows a class (child/subclass) to inherit attributes and methods from another class (parent/superclass). class Animal: ... class Dog(Animal): ... Dog inherits from Animal. Use super() to call parent methods.
Question 53 of 150
What does the enumerate() function do?
Explanation: enumerate(iterable) returns (index, value) pairs. for i, v in enumerate(['a','b','c']): gives (0,'a'), (1,'b'), (2,'c'). Optional start parameter: enumerate(list, start=1) begins counting from 1.
Question 54 of 150
What is the output of: print('Hello'.replace('l', 'r'))?
Explanation: str.replace(old, new) replaces all occurrences of old with new. 'Hello'.replace('l','r') replaces both 'l' characters: 'H'+'e'+'rr'+'o' = 'Herro'.
Question 55 of 150
What does sorted() return?
Explanation: sorted(iterable) returns a NEW sorted list without modifying the original. list.sort() sorts in place (modifies original, returns None). sorted accepts key= and reverse= arguments. sorted('bca') returns ['a','b','c'].
Question 56 of 150
What is a list comprehension?
Explanation: List comprehensions provide a concise syntax: [x*2 for x in range(5)] creates [0,2,4,6,8]. Can include conditions: [x for x in range(10) if x%2==0] gives even numbers. More readable and faster than equivalent loops for simple cases.
Question 57 of 150
What is the output of: print(type({}))?
Explanation: {} creates an empty dictionary, not an empty set. type({}) returns . To create an empty set: set(). Tour is a common Python gotcha.
Question 58 of 150
What does the zip() function do?
Explanation: zip(iter1, iter2) pairs elements from multiple iterables. zip([1,2,3], ['a','b','c']) gives (1,'a'), (2,'b'), (3,'c'). Stops at shortest iterable. Useful for parallel iteration: for num, letter in zip(numbers, letters).
Question 59 of 150
What is the output of: print(4 / 2)?
Explanation: / always returns a float in Python 3, even when dividing integers evenly. 4 / 2 = 2.0. Use // for integer division: 4 // 2 = 2. Tour is different from Python 2 behaviour.
Question 60 of 150
What does the 'global' keyword do in Python?
Explanation: By default, variables assigned inside a function are local. 'global varname' inside a function means: use and modify the global variable, not create a local one. Best practice: minimise use of global variables; prefer passing parameters.
Question 61 of 150
What is the output of: print([1,2,3] * 2)?
Explanation: The * operator on lists repeats the list. [1,2,3] * 2 = [1,2,3,1,2,3]. Same for strings: 'ab' * 3 = 'ababab'. Note: tour creates copies of references, not deep copies β€” important with nested mutable objects.
Question 62 of 150
What does the .strip() method do?
Explanation: str.strip() removes leading and trailing whitespace (spaces, tabs, newlines). lstrip() removes only from left. rstrip() only from right. strip('x') removes specified characters instead of whitespace. Essential for cleaning user input.
Question 63 of 150
What is a f-string in Python?
Explanation: F-strings (formatted string literals) use f'...' prefix. name='World'; f'Hello {name}!' produces 'Hello World!'. Expressions allowed: f'{2+2}' = '4'. Format specs: f'{pi:.2f}' = '3.14'. Available since Python 3.6.
Question 64 of 150
What is the output of: print(10 // 3)?
Explanation: // is floor division β€” divides and rounds down to the nearest integer. 10 // 3 = 3 (not 3.33). For negative numbers: -10 // 3 = -4 (rounds toward negative infinity, not toward zero).
Question 65 of 150
What is the difference between == and 'is' in Python?
Explanation: == checks if values are equal. 'is' checks if two variables point to the same object in memory. a = [1,2]; b = [1,2]; a == b is True, a is b is False (different objects). Use 'is' for None comparison: if x is None.
Question 66 of 150
What does the pop() method do on a list?
Explanation: list.pop() removes and returns the last element. list.pop(0) removes and returns the first. list.pop(i) removes and returns element at index i. Tour modifies the list in place. del list[i] removes without returning.
Question 67 of 150
What is the output of: print('Hello, World!'.split(', '))?
Explanation: split(', ') splits at each occurrence of ', ' (comma followed by space). 'Hello, World!'.split(', ') gives ['Hello', 'World!']. Without argument, split() splits on any whitespace.
Question 68 of 150
What is a generator in Python?
Explanation: Generators use yield instead of return. They produce values on demand (lazily), using memory efficiently. def count(): yield 1; yield 2; yield 3. Also: generator expressions: (x*2 for x in range(5)). Used when full list not needed simultaneously.
Question 69 of 150
What is the output of: x=10; print(x>5 and x<20)?
Explanation: x>5 is True (10>5), x<20 is True (10<20). True and True = True. Boolean operators: and (both must be True), or (at least one True), not (negation).
Question 70 of 150
What does the 'del' keyword do?
Explanation: del removes a variable from scope (del x) or removes list elements (del list[i] or del list[2:5]) or dictionary entries (del dict['key']). After del x, accessing x raises NameError.
Question 71 of 150
What is the output of: print(bool(''))?
Explanation: Empty string '' is falsy. bool('') = False. Other falsy values: 0, 0.0, None, [], {}, (), set(). All non-empty strings are truthy: bool('False') = True (non-empty string, even if it says 'False').
Question 72 of 150
What is the output of: print([x**2 for x in range(4)])?
Explanation: List comprehension: [x**2 for x in range(4)]. range(4) gives 0,1,2,3. Squaring each: 0,1,4,9. Result: [0, 1, 4, 9].
Question 73 of 150
What does map() do in Python?
Explanation: map(function, iterable) applies function to each element. list(map(str, [1,2,3])) = ['1','2','3']. list(map(lambda x: x*2, [1,2,3])) = [2,4,6]. Returns an iterator β€” convert to list to see all values.
Question 74 of 150
What is multiple assignment in Python?
Explanation: a, b = 1, 2 assigns a=1 and b=2. Used for swapping: a, b = b, a (Python swap idiom β€” no temp variable needed). Also: a, b, c = 'xyz' unpacks string characters.
Question 75 of 150
What is the output of: print('abc' in 'abcdef')?
Explanation: 'in' tests membership/containment. 'abc' in 'abcdef' checks if 'abc' is a substring. Returns True. Case-sensitive: 'ABC' in 'abcdef' is False.
Question 76 of 150
What does filter() do?
Explanation: filter(function, iterable) returns elements where function(element) is True. list(filter(lambda x: x%2==0, range(10))) returns even numbers [0,2,4,6,8]. If function is None, filters out falsy values.
Question 77 of 150
What is the output of: print(min([4,2,7,1,9]))?
Explanation: min() returns the smallest element. min([4,2,7,1,9]) = 1. max() returns 9. Alternatively, sorted([4,2,7,1,9])[0] = 1 (smallest after sorting).
Question 78 of 150
What is a class in Python?
Explanation: A class is a template/blueprint for objects. class Dog: def __init__(self, name): self.name=name. Instances are created: rex = Dog('Rex'). Classes encapsulate data (attributes) and behaviour (methods). Foundation of Object-Oriented Programming.
Question 79 of 150
What is the output of: print(isinstance(True, int))?
Explanation: isinstance(object, type) checks if object is an instance of type. In Python, bool is a subclass of int, so isinstance(True, int) is True. True has value 1 and False has value 0 in arithmetic context.
Question 80 of 150
What does .format() do?
Explanation: 'Hello, {}!'.format('World') produces 'Hello, World!'. Named placeholders: '{name}'.format(name='Alice'). Index: '{0} and {1}'.format('a','b'). F-strings are the modern alternative: f'Hello, {name}!'.
Question 81 of 150
What is the output of: print('hello'.capitalize())?
Explanation: capitalize() returns a string with the first character uppercase and the rest lowercase. 'hello'.capitalize() = 'Hello'. 'hELLO WORLD'.capitalize() = 'Hello world' (lowercases the rest).
Question 82 of 150
What is the purpose of the 'with' statement?
Explanation: 'with open(file) as f:' ensures the file is closed even if an error occurs. The with statement works with any object that implements __enter__ and __exit__ (context managers). More reliable than try/finally for resource management.
Question 83 of 150
What does the not operator do?
Explanation: 'not' is the boolean negation operator. not True = False. not False = True. not 0 = True. not [] = True (empty list is falsy). Used in conditions: if not user_list: print('No users').
Question 84 of 150
What is the output of: print('2' + '3')?
Explanation: + concatenates strings. '2' + '3' = '23' (string concatenation, not arithmetic). To add numerically: int('2') + int('3') = 5. Tour demonstrates why input() always returning a string matters.
Question 85 of 150
What is the purpose of the __str__ method in a class?
Explanation: __str__ defines how an object is represented as a string. class Dog: def __str__(self): return f'Dog named {self.name}'. Then: print(dog) calls __str__ automatically. __repr__ is for developer representation (used in REPL).
Question 86 of 150
What is a tuple unpacking?
Explanation: Tuple unpacking extracts values: x, y = (10, 20) assigns x=10, y=20. Works with any iterable. Extended unpacking: first, *rest = [1,2,3,4] gives first=1, rest=[2,3,4]. Core to multiple assignment and for loops.
Question 87 of 150
What is the output of: d={'a':1,'b':2}; print(d.get('c', 0))?
Explanation: dict.get(key, default) returns the value for key if it exists, otherwise returns default (0 in tour case). Without default argument, returns None if key not found. Tour avoids KeyError when accessing potentially missing keys.
Question 88 of 150
What does 'recursion' mean in programming?
Explanation: Recursion: a function calls itself. Base case terminates recursion; recursive case calls function with smaller input. Example: factorial(n) = n * factorial(n-1), factorial(0) = 1. Python default recursion limit: 1000 levels.
Question 89 of 150
What is the output of: print(sum([1,2,3,4,5]))?
Explanation: sum() adds all elements in an iterable. sum([1,2,3,4,5]) = 1+2+3+4+5 = 15. Optional start value: sum([1,2,3], 10) = 16 (starts from 10).
Question 90 of 150
What is the difference between print() and return?
Explanation: print() produces visible output to the console β€” for display purposes. return exits a function and sends a value back to the caller. A function can return without printing; it can print without returning.
Question 91 of 150
What is a default parameter value in Python?
Explanation: def greet(name='World'): print(f'Hello, {name}'). Calling greet() uses 'World' as default; greet('Alice') uses 'Alice'. Default parameters must come after non-default parameters. Avoid mutable defaults like def f(lst=[]) β€” shared across calls.
Question 92 of 150
What does the 'raise' keyword do?
Explanation: raise ExceptionType('message') manually triggers an exception. raise ValueError('Invalid input') raises a ValueError. Can re-raise current exception with bare 'raise' inside except block. Custom exceptions: class MyError(Exception): pass.
Question 93 of 150
What is the output of: print(list('hello'))?
Explanation: list() converts an iterable to a list. For strings, each character becomes a separate element: list('hello') = ['h','e','l','l','o']. Similarly: list((1,2,3)) = [1,2,3]. list(range(5)) = [0,1,2,3,4].
Question 94 of 150
What is the __name__ == '__main__' idiom?
Explanation: if __name__ == '__main__': block runs only when the file is run directly, not when imported. When imported, __name__ equals the module name. Tour pattern allows a file to be both a reusable module and a runnable script.
Question 95 of 150
What does the copy() method do on a list?
Explanation: list.copy() creates a shallow copy β€” a new list object with the same elements. b = a.copy() means modifying b's top-level elements doesn't affect a. However, nested mutable objects are still shared. For deep copies: import copy; copy.deepcopy(list).
Question 96 of 150
What is the output of: print(10 != 10)?
Explanation: != is the not-equal operator. 10 != 10 is False because 10 equals 10. The expression 10 == 10 would be True. 10 != 5 would be True.
Question 97 of 150
What is PEP 8?
Explanation: PEP 8 (Python Enhancement Proposal 8) is Python's official style guide. Key rules: 4-space indentation, max 79 chars per line, two blank lines between functions, lowercase_with_underscores for variables, CamelCase for classes, spaces around operators.
Question 98 of 150
What is the output of: print(any([False, 0, '', 1]))?
Explanation: any() returns True if at least one element is truthy. [False, 0, '', 1] β€” the last element 1 is truthy. So any() returns True. all() returns True only if ALL elements are truthy. all([1,2,3]) = True; all([1,0,3]) = False.
Question 99 of 150
What is the output of: print(1 == True)?
Explanation: In Python, True has value 1 and False has value 0. 1 == True evaluates to True because bool is a subclass of int. Similarly: 0 == False is True, 2 == True is False.
Question 100 of 150
What is a docstring?
Explanation: Docstrings: triple-quoted strings as first line of function. Accessed via __doc__. Example: def func(): """Tour function does X.""" pydoc generates documentation from docstrings. PEP 257 conventions for docstring format.
Question 101 of 150
What is the output of: print(list(reversed([1,2,3])))?
Explanation: reversed() returns an iterator in reverse order. list() converts it to a list. list(reversed([1,2,3])) = [3,2,1]. Alternative: [1,2,3][::-1] also reverses using slicing.
Question 102 of 150
What does the 'in' operator test for with dictionaries?
Explanation: 'in' with dictionaries checks keys by default. 'a' in {'a':1,'b':2} is True. To check values: 'a' in dict.values(). To check items: ('a',1) in dict.items().
Question 103 of 150
What is the output of: print(type([]) == type([1,2]))?
Explanation: Both [] and [1,2] are lists, so type([]) == list and type([1,2]) == list. list == list is True.
Question 104 of 150
What is exception chaining?
Explanation: Exception chaining: raise ValueError('new') from original_error. Preserves the original exception as __cause__. Without 'from': __context__ attribute. PEP 3134. Useful for wrapping low-level exceptions in higher-level ones.
Question 105 of 150
What is the output of: x = {1,2,3}; x.add(2); print(len(x))?
Explanation: Sets contain unique elements. Adding 2 to {1,2,3} doesn't change it because 2 already exists. len({1,2,3}) = 3.
Question 106 of 150
What does the 'break' statement do in a while loop?
Explanation: break exits the innermost loop (for or while) immediately. continue skips the rest of the current iteration and returns to the loop condition check. else clause on a loop: runs if loop completes without break.
Question 107 of 150
What is the output of: print('hello'.count('l'))?
Explanation: str.count(sub) counts non-overlapping occurrences. 'hello' has two 'l' characters. 'hello'.count('l') = 2. 'mississippi'.count('ss') = 2.
Question 108 of 150
What is a set comprehension?
Explanation: Set comprehension: {x*2 for x in range(5)} = {0,2,4,6,8}. Like list comprehension but creates a set (unique, unordered). {x for x in 'hello'} = {'h','e','l','o'} (removes duplicates).
Question 109 of 150
What is the output of: d = {}; d.setdefault('a', []); d['a'].append(1); print(d)?
Explanation: setdefault(key, default) sets key to default if not present and returns the value. d.setdefault('a',[]) sets d['a']=[] if 'a' not in d. Then appending to d['a'] gives {'a':[1]}.
Question 110 of 150
What does 'yield from' do?
Explanation: 'yield from iterable' yields each value from the iterable one by one. Equivalent to 'for item in iterable: yield item'. Used for composing generators and in asynchronous programming with asyncio.
Question 111 of 150
What is the output of: print(0 or 'hello')?
Explanation: 'or' returns the first truthy value (or the last value if all falsy). 0 is falsy, 'hello' is truthy. So 0 or 'hello' returns 'hello'. Similarly: 0 and 'hello' returns 0 (first falsy value).
Question 112 of 150
What is the output of: print(not not True)?
Explanation: not True = False. not False = True. So not not True = True. Double negation returns original boolean value.
Question 113 of 150
What is the __len__ method?
Explanation: Implementing __len__(self) allows len() to work on custom classes. class MyList: def __len__(self): return len(self.data). Then len(MyList()) calls __len__. Part of Python's data model β€” dunder methods.
Question 114 of 150
What is the output of: print(sorted({3:1,1:2,2:3}))?
Explanation: sorted() on a dictionary sorts its keys. sorted({3:1,1:2,2:3}) returns [1,2,3] (sorted keys as a list). sorted(dict.values()) would sort values.
Question 115 of 150
What is a context manager?
Explanation: Context managers ensure proper resource management. File objects are context managers. Custom: class MyCtx: def __enter__(self): return self; def __exit__(self, *args): cleanup(). Or use @contextmanager decorator from contextlib.
Question 116 of 150
What is the output of: print(2**(3**2))?
Explanation: Exponentiation is right-associative. 3**2 = 9 first. Then 2**9 = 512. Compare (2**3)**2 = 8**2 = 64.
Question 117 of 150
What is pickling in Python?
Explanation: Pickle: pickle.dumps(obj) β†’ bytes. pickle.loads(bytes) β†’ object. pickle.dump(obj, file) β†’ saves to file. pickle.load(file) β†’ loads. Warning: never unpickle data from untrusted sources (security risk). Use JSON for cross-language data exchange.
Question 118 of 150
What is the difference between __str__ and __repr__?
Explanation: If __str__ not defined, __repr__ is used as fallback. repr('hello') = "'hello'" (with quotes). str('hello') = 'hello' (without quotes). Implement both for complete custom class string representation.
Question 119 of 150
What is the output of: x = [1,2,3]; y = x; y.append(4); print(x)?
Explanation: y = x creates a reference to the same list object, not a copy. Modifying y also modifies x because they point to the same object in memory. To copy: y = x.copy() or y = x[:] or y = list(x).
Question 120 of 150
What does vars() do?
Explanation: vars(obj) returns obj.__dict__. vars() without argument returns the local symbol table. Similar to locals(). Example: vars(my_object) shows all instance attributes as a dictionary.
Question 121 of 150
What is the output of: print(10 > 5 > 3)?
Explanation: Python supports chained comparisons. 10 > 5 > 3 is equivalent to (10 > 5) and (5 > 3) = True and True = True. Tour is different from most other languages where it would be evaluated left-to-right.
Question 122 of 150
What is an abstract class?
Explanation: from abc import ABC, abstractmethod. class Shape(ABC): @abstractmethod def area(self): pass. Shape() raises TypeError. Subclasses must implement all abstract methods. Forces interface compliance. Template Method pattern.
Question 123 of 150
What is the output of: print([1,2,3].index(2))?
Explanation: list.index(value) returns the index of the first occurrence. [1,2,3].index(2) returns 1 (0-based index). Raises ValueError if not found. To find all occurrences: [i for i,v in enumerate(lst) if v==2].
Question 124 of 150
What is the difference between / and // in Python?
Explanation: 5/2 = 2.5 (float). 5//2 = 2 (floor division, rounds down). -5//2 = -3 (rounds toward negative infinity, not toward zero). 5.0//2 = 2.0 (floor division with floats still returns float).
Question 125 of 150
What is the output of: print(bool([0]))?
Explanation: [0] is a non-empty list β€” it contains one element (0). Non-empty containers are truthy in Python. bool([0]) = True. Compare: bool([]) = False (empty list is falsy). The value of elements doesn't matter β€” only emptiness.
Question 126 of 150
What does 'assert' do?
Explanation: assert condition, 'error message'. assert x > 0, 'x must be positive'. Disabled with python -O (optimize) flag. Used in unit tests (unittest uses assert methods). Not for production error handling β€” use exceptions for that.
Question 127 of 150
What is the output of: print(round(0.1 + 0.2, 1))?
Explanation: 0.1 + 0.2 in floating point = 0.30000000000000004 (floating point precision). round(0.1+0.2, 1) = 0.3. For exact decimal arithmetic: from decimal import Decimal; Decimal('0.1') + Decimal('0.2') = Decimal('0.3').
Question 128 of 150
What is the output of: print(type(lambda x: x))?
Explanation: Lambda functions are just anonymous function objects. type(lambda x: x) returns . They are identical to functions defined with def in terms of type.
Question 129 of 150
What is the output of: a, *b, c = [1,2,3,4,5]; print(b)?
Explanation: Extended unpacking: a=1, *b captures middle, c=5. b = [2,3,4]. The starred variable captures everything not explicitly unpacked.
Question 130 of 150
What is a property in Python?
Explanation: @property turns a method into an attribute. @name.setter defines the setter. Example: class C: @property def x(self): return self._x. @x.setter def x(self, v): self._x = v. Access as c.x not c.x().
Question 131 of 150
What is the global interpreter lock (GIL)?
Explanation: GIL: CPython-specific (not in Jython, PyPy). For CPU-bound tasks: use multiprocessing instead of threading (bypasses GIL). For I/O-bound tasks: threading still effective (GIL released during I/O). asyncio: single-threaded concurrent I/O without GIL issues.
Question 132 of 150
What does the .items() dictionary method return?
Explanation: .items() returns a dict_items view of (key, value) pairs. for k, v in dict.items(): iterates both. dict.keys(): keys only. dict.values(): values only. All return views (not lists) β€” reflect changes to dictionary.
Question 133 of 150
What is the output of: print(2**10)?
Explanation: 2**10 = 2 to the power of 10 = 1024. Powers of 2 are important in computing: 2^8=256, 2^10=1024 (1KB), 2^16=65536, 2^20=1048576 (1MB), 2^32=4294967296 (4GB of IPv4 addresses).
Question 134 of 150
What is the output of: print('abc'.zfill(5))?
Explanation: str.zfill(width) pads a string on the left with zeros to reach the specified width. 'abc'.zfill(5) = '00abc'. Useful for: code numbers, formatting. Negative numbers handled: '-42'.zfill(5) = '-0042'.
Question 135 of 150
What is the output of: x = {'a':1}; y = {'b':2}; z = {**x, **y}; print(z)?
Explanation: Dictionary unpacking with **. {**dict1, **dict2} merges two dictionaries. In Python 3.9+: dict1 | dict2 achieves the same. If duplicate keys, the last one wins: {**{'a':1},**{'a':2}} = {'a':2}.
Question 136 of 150
What is the output of: print(list(map(str, [1,2,3])))?
Explanation: map(str, [1,2,3]) applies str() to each element: str(1)='1', str(2)='2', str(3)='3'. list() converts the map object. Result: ['1','2','3'].
Question 137 of 150
What is the output of: print([x for x in range(10) if x % 2 == 0])?
Explanation: List comprehension with condition: keeps only elements where x % 2 == 0 (even). range(10) = 0-9. Even numbers: 0,2,4,6,8. Result: [0,2,4,6,8].
Question 138 of 150
What is the output of: print('Hello World'.lower())?
Explanation: str.lower() returns all characters converted to lowercase. 'Hello World'.lower() = 'hello world'. str.upper() = 'HELLO WORLD'. str.title() = 'Hello World'. str.swapcase() = 'hELLO wORLD'.
Question 139 of 150
What does the 'nonlocal' keyword do?
Explanation: nonlocal: modifies variable in enclosing (not global) scope. def outer(): x=1; def inner(): nonlocal x; x=2. Without nonlocal, inner() would create a new local x. Used in closures and nested functions.
Question 140 of 150
What is the output of: print(bool('False'))?
Explanation: 'False' is a non-empty string. Non-empty strings are truthy. bool('False') = True. The string 'False' is not the boolean False. bool('') = False (empty string is falsy).
Question 141 of 150
What is the output of: print(list(filter(lambda x: x>3, [1,2,3,4,5])))?
Explanation: filter(lambda x: x>3, [1,2,3,4,5]) keeps elements where lambda returns True. Elements > 3: 4 and 5. list() converts to list. Result: [4,5].
Question 142 of 150
What is the output of: print(chr(65))?
Explanation: chr(n) returns the character with Unicode code point n. chr(65) = 'A' (ASCII/Unicode). chr(97) = 'a'. ord('A') = 65 (reverse operation). ord() and chr() are inverses.
Question 143 of 150
What is the output of: print(10 > 9 > 8)?
Explanation: Chained comparison: 10 > 9 is True, and 9 > 8 is True. True and True = True. Python evaluates as (10>9) and (9>8) simultaneously.
Question 144 of 150
What is the difference between append() and extend()?
Explanation: [1,2].append([3,4]) β†’ [1,2,[3,4]] (nested list). [1,2].extend([3,4]) β†’ [1,2,3,4] (elements added). append() always adds one element; extend() unpacks the iterable.
Question 145 of 150
What is the output of: print(type(None))?
Explanation: None is the sole instance of NoneType. type(None) = . None is falsy: bool(None) = False. Check None: if x is None (not == None).
Question 146 of 150
What is the output of: print(int('FF', 16))?
Explanation: int(string, base) converts string from given base to decimal. 'FF' in hexadecimal: F=15, so FF = 15Γ—16 + 15 = 255. int('10', 2) = 2 (binary). int('10', 8) = 8 (octal). int('10', 10) = 10 (decimal, default).
Question 147 of 150
What is __slots__ in Python?
Explanation: class Point: __slots__ = ['x', 'y']. Instances can only have x and y attributes. Memory savings (no __dict__ per instance). Faster attribute access. Disadvantage: can't add arbitrary attributes. Useful for classes with many instances.
Question 148 of 150
What is the output of: print('abc' * 3)?
Explanation: String repetition: 'abc' * 3 = 'abcabcabc'. Same as concatenating 'abc' + 'abc' + 'abc'. Works for lists too: [1,2] * 3 = [1,2,1,2,1,2].
Question 149 of 150
What is the output of: print(divmod(17, 5))?
Explanation: divmod(a, b) returns tuple (quotient, remainder). divmod(17, 5): 17Γ·5=3 remainder 2. Returns (3, 2). Equivalent to (17//5, 17%5).
Question 150 of 150
What is the output of: print(3 in {1:10, 2:20, 3:30})?
Explanation: 'in' on a dictionary checks keys, not values. 3 is a key in {1:10, 2:20, 3:30}. Returns True. To check values: 3 in {1:10,2:20,3:30}.values() β€” that would be False (values are 10,20,30).

Practice More on Dragonfly

500+ questions across 45+ subjects with timed mode and flashcards.

Start Full Practice

Disclaimer: All questions are original, independently authored content for educational study purposes only. Not affiliated with any official examination body or certification authority.

Flashcards

Tap a card to reveal the answer. Use the buttons to navigate.

1 / 100
Question
Loading...
Answer

Tap card to flip • Navigate with buttons below

Study Resources

Curated official and free resources to complement your practice.

Keep Studying

About the Python PCEP Certification

The PCEP (Python Certified Entry-Level Programmer) is awarded by the Python Institute and validates foundational Python programming skills. It is the entry point to the Python Institute certification pathway, which progresses through PCAP (Associate) and PCPP (Professional) levels. Python is consistently one of the most in-demand programming languages in the South African technology market.

The PCEP exam covers basic Python syntax, data types, control flow, functions, collections, exceptions, and basic object-oriented programming. Our practice set covers all PCEP modules with explanations that show actual Python behaviour β€” not just the rule, but what Python will do and why.

After PCEP, the natural progression is PCAP (Python Certified Associate Programmer), which covers more advanced OOP, exceptions, file I/O, and selected library modules. PCAP candidates can use Dragonfly's Python practice set as a foundation refresher before progressing to PCAP-specific materials.

dragonflyexampapers.co.za
0/0
correct answers