CertSafari

    Free Python Institute PCEP™ – Certified Entry-Level Python Programmer Sample Questions

    35 free sample questions from our bank of 426+, covering every exam domain, with answers and detailed explanations. Updated August 2026.

    Domain 1: Computer Programming and Python Fundamentals

    Subdomain 1.1: Understand fundamental terms and definitions

    1.Which term best describes the process by which Python executes code?

    1. A.Interpretation
    2. B.Compilation
    3. C.Just-in-time compilation
    4. D.Bytecode interpretation
    Show answer & explanation

    Correct answer: DBytecode interpretation

    • A. While Python is often called an interpreted language, general interpretation typically means executing source code line by line without an intermediate representation. Python actually compiles source code to bytecode first, so this term alone is imprecise for the standard implementation.
    • B. Compilation is the process of translating source code into another form, such as bytecode or machine code. Python does compile source code to bytecode, but this is only one step; the bytecode is then interpreted by the Python Virtual Machine. Thus, 'compilation' alone does not fully describe Python's execution model.
    • C. Just-in-time (JIT) compilation compiles code during execution, often for performance. Standard CPython does not use JIT compilation; it relies on bytecode interpretation. JIT is used in some alternative Python implementations like PyPy, but not in the default one.
    • D. Correct. Python's standard execution model involves compiling source code into bytecode (.pyc files) and then interpreting that bytecode using the Python Virtual Machine (PVM). This two-step process is commonly referred to as bytecode interpretation, which accurately describes how Python runs code.

    Subdomain 1.1: Understand fundamental terms and definitions

    2.What type of error occurs if you try to use a variable name that starts with a digit?

    1. A.Lexical error: it begins with a digit, which is an invalid token.
    2. B.Syntax error: this violates the grammar rule for identifiers.
    3. C.Semantic error: the variable name does not convey meaning.
    4. D.No error: identifiers may start with digits in Python without issue.
    Show answer & explanation

    Correct answer: ALexical error: it begins with a digit, which is an invalid token.

    • A. Correct. Python's lexer (tokenizer) scans the source code and breaks it into tokens. Identifiers must start with a letter or underscore; a digit at the beginning is not a valid token, causing a lexical error. This error is caught before syntax analysis.
    • B. Incorrect. While the identifier rule is part of the language grammar, the error is detected during lexical analysis, not syntax parsing. Syntax errors typically involve incorrect structure (e.g., missing colons, unmatched parentheses).
    • C. Incorrect. Semantic errors relate to the meaning or logic of the code (e.g., using a variable before assignment, type mismatches). A name starting with a digit is invalid regardless of meaning, so it is not a semantic issue.
    • D. Incorrect. Python explicitly forbids identifiers beginning with a digit. The interpreter will reject such names, raising a SyntaxError (or IndentationError) at compile time; it will not run successfully.

    Subdomain 1.1: Understand fundamental terms and definitions

    3.Which phase of the compilation process involves checking the grammatical structure of the source code?

    1. A.Lexical analysis
    2. B.Syntax analysis
    3. C.Semantic analysis
    4. D.Code generation
    Show answer & explanation

    Correct answer: BSyntax analysis

    • A. Incorrect. Lexical analysis is the process of converting source code into tokens such as keywords, identifiers, and operators. It does not check the grammatical structure of the program.
    • B. Correct. Syntax analysis is the phase where the parser checks whether the token sequence follows the grammar rules of the language. This is the stage that determines if the code is syntactically valid.
    • C. Incorrect. Semantic analysis checks the meaning of the code after syntax has been verified, such as type compatibility and variable usage. It goes beyond just structure or grammar.
    • D. Incorrect. Code generation is the phase that produces machine code, bytecode, or another lower-level representation from the analyzed source. It happens after lexical, syntax, and semantic analysis.

    Subdomain 1.1: Understand fundamental terms and definitions

    4.Which of the following are syntax errors in Python?(Select 3)

    1. A.A missing colon at the end of a for statement.
    2. B.A division by zero operation in the code.
    3. C.Unbalanced parentheses in an expression.
    4. D.Using an undefined variable in an expression.
    5. E.An identifier that starts with a digit.
    6. F.A logical error in a loop condition.
    Show answer & explanation

    Correct answers: A, C, EA missing colon at the end of a for statement.; Unbalanced parentheses in an expression.; An identifier that starts with a digit.

    • A. Correct. A missing colon at the end of a for statement violates Python's grammar rules, preventing the code from being parsed. This is a classic syntax error detected before execution.
    • B. Incorrect. Division by zero is a runtime error (ZeroDivisionError), not a syntax error. The code is syntactically valid but fails during execution.
    • C. Correct. Unbalanced parentheses make an expression invalid according to Python's syntax rules, causing a parse error. The interpreter cannot properly parse the code.
    • D. Incorrect. Using an undefined variable results in a runtime error (NameError), not a syntax error. The code is syntactically valid but fails when the variable is looked up during execution.
    • E. Correct. An identifier that starts with a digit is not allowed in Python's naming rules, so the code cannot be parsed. This is a syntax error.
    • F. Incorrect. A logical error in a loop condition means the program runs but produces incorrect results. This is a semantic error, not a syntax error, as the code follows Python's grammatical rules.

    Subdomain 1.3: Introduce literals and variables into code and use different numeral systems

    5.Which of the following are valid Python variable names?(Select 4)

    1. A.myVar
    2. B.my_var
    3. C._my_var
    4. D.2myvar
    5. E.my-var
    6. F.MYVAR
    Show answer & explanation

    Correct answers: A, B, C, FmyVar; my_var; _my_var; MYVAR

    • A. Correct. `myVar` starts with a letter and contains only letters, which is allowed in Python identifiers. Python is case-sensitive, so mixed-case names are valid.
    • B. Correct. `my_var` starts with a letter and contains an underscore, both allowed in Python identifiers. Underscores can appear anywhere except as the first character (though they can start with underscore as well).
    • C. Correct. `_my_var` starts with an underscore, which is permitted in Python identifiers. Such names are often used for internal or private variables.
    • D. Incorrect. `2myvar` begins with a digit, which is not allowed. Python identifiers must start with a letter or underscore.
    • E. Incorrect. `my-var` contains a hyphen, which is not permitted in Python identifiers. Hyphens are interpreted as the subtraction operator.
    • F. Correct. `MYVAR` consists only of uppercase letters, which are allowed. Python identifiers are case-sensitive, so `MYVAR` is distinct from `myvar`.

    Subdomain 1.3: Introduce literals and variables into code and use different numeral systems

    6.Which expression correctly converts the binary string '1010' to its decimal integer value?

    1. A.int("1010", 2)
    2. B.int("1010", 10)
    3. C.binary("1010")
    4. D.int("1010", 16)
    Show answer & explanation

    Correct answer: Aint("1010", 2)

    • A. Correct. The int() function with base 2 interprets the string as a binary number and returns its decimal equivalent, which is 10.
    • B. Incorrect. int() with base 10 treats the string as a decimal number, returning 1010, not a binary conversion.
    • C. Incorrect. Python does not have a built-in binary() function for this conversion; calling binary() raises a NameError.
    • D. Incorrect. int() with base 16 interprets the string as hexadecimal, yielding 4112 in decimal, not the binary conversion.

    Subdomain 1.3: Introduce literals and variables into code and use different numeral systems

    7.What is the result of the expression 3000 / 2 in Python 3? Fill in the blank with the appropriate literal value.

    1. A.1500.0
    2. B.1500
    3. C.4.5
    Show answer & explanation

    Correct answer: A1500.0

    • A. Correct. In Python 3, 3000 / 2 evaluates to 1500.0, a float literal.
    • B. Incorrect. 1500 is an integer literal, but 3000 / 2 returns a float (1500.0) in Python 3.
    • C. Incorrect. 4.5 does not equal 1500.0, the result of 3000 / 2.

    Subdomain 1.3: Introduce literals and variables into code and use different numeral systems

    8.Which of the following Python string literals will produce a string that contains the two characters backslash and n (i.e., \n)?

    1. A."Hello\nWorld"
    2. B."Hello\\nWorld"
    3. C."Hello/nWorld"
    4. D."Hello\tWorld"
    Show answer & explanation

    Correct answer: B"Hello\\nWorld"

    • A. Incorrect. The escape sequence \n is interpreted as a newline character, not as the two characters backslash and n. When printed, it outputs Hello on one line and World on the next.
    • B. Correct. The double backslash \\ escapes to a single backslash in the resulting string, so the string value contains the literal characters backslash and n.
    • C. Incorrect. The forward slash is not an escape character; the string contains a slash followed by n, not a backslash and n.
    • D. Incorrect. \t is an escape sequence for a tab character, so the string contains a tab between Hello and World, not the literal characters backslash and n.

    Domain 2: Control Flow – Conditional Blocks and Loops

    Subdomain 2.2: Perform different types of iterations

    9.What does the 'pass' statement do in Python?

    1. A.To stop the current iteration and move to the next one
    2. B.To act as a placeholder when code is needed but not executed
    3. C.To immediately exit a loop and stop further iterations
    4. D.To skip the rest of the loop and re-evaluate its condition
    Show answer & explanation

    Correct answer: BTo act as a placeholder when code is needed but not executed

    • A. Incorrect. This describes the 'continue' statement, which terminates the current loop iteration and proceeds to the next one. 'pass' does not affect loop flow.
    • B. Correct. 'pass' is a no-operation statement used as a placeholder where Python syntax requires a statement but no action is intended. It is commonly used in empty functions, classes, or conditional blocks to allow the code to run without errors.
    • C. Incorrect. This describes the 'break' statement, which immediately exits the loop regardless of the condition. 'pass' leaves program flow unchanged.
    • D. Incorrect. This also describes the 'continue' statement, which skips the remaining code in the current iteration and then re-evaluates the loop condition. 'pass' performs no action.

    Subdomain 2.2: Perform different types of iterations

    10.What is the effect of the 'continue' statement within a loop?

    1. A.It causes the loop to exit entirely and immediately.
    2. B.It skips the rest of the current iteration and goes to the next.
    3. C.It freezes the loop until an external event resumes it.
    4. D.It restarts the loop from the very first iteration.
    Show answer & explanation

    Correct answer: BIt skips the rest of the current iteration and goes to the next.

    • A. Incorrect. Exiting the entire loop immediately is the behavior of the break statement, not continue. The continue statement only affects the current iteration.
    • B. Correct. The continue statement skips the remaining code in the current loop iteration and moves on to the next iteration. It does not terminate the loop.
    • C. Incorrect. The continue statement does not freeze the loop or wait for an external event. It simply skips to the next iteration immediately.
    • D. Incorrect. The continue statement does not restart the loop from the beginning. It only skips the current iteration's remaining code and proceeds with the next iteration.

    Subdomain 2.2: Perform different types of iterations

    11.Which of the following loops creates an infinite loop?

    1. A.for i in range(10):
    2. B.while False:
    3. C.while True:
    4. D.for i in range(0, 10, 1):
    Show answer & explanation

    Correct answer: Cwhile True:

    • A. Incorrect. This for loop iterates over a fixed range of 10 numbers (0 to 9) and then stops. It is not an infinite loop because the range has a definite end.
    • B. Incorrect. The condition `while False:` is never true, so the loop body is skipped entirely. It never executes even once, let alone infinitely.
    • C. Correct. The loop `while True:` continuously evaluates the condition as true, so it repeats indefinitely until interrupted by a break statement, return, or exception. This is the standard way to create an infinite loop in Python.
    • D. Incorrect. Similar to option A, this for loop iterates over a fixed range from 0 to 9 with step 1, and terminates after 10 iterations. It does not run indefinitely.

    Subdomain 2.2: Perform different types of iterations

    12.The __________ function generates a sequence of numbers that can be used to control the number of iterations in a for loop.

    1. A.range()
    2. B.list()
    3. C.int()
    Show answer & explanation

    Correct answer: Arange()

    • A. Correct. The range() function generates an immutable sequence of numbers, often used in for loops to specify the number of iterations. It is specifically designed for this purpose.
    • B. Incorrect. The list() function converts an iterable into a list object. While a list can be iterated, it does not generate a sequence of numbers; it merely stores existing items.
    • C. Incorrect. The int() function converts a value to an integer. It does not produce a sequence or collection suitable for iteration.

    Domain 3: Data Collections – Tuples, Dictionaries, Lists, and Strings

    Subdomain 3.2: Collect and process data using tuples

    13.What happens when this code runs? ``` t = (1, 2, 3) t[1] = 5 ```

    1. A.t becomes (1,5,3)
    2. B.TypeError is raised
    3. C.IndexError is raised
    4. D.t remains unchanged
    Show answer & explanation

    Correct answer: BTypeError is raised

    • A. Incorrect. Tuples are immutable in Python, so you cannot modify their elements after creation. The code does not change the tuple to (1, 5, 3); it raises an error.
    • B. Correct. Attempting to assign to an element of a tuple raises a TypeError because tuples do not support item assignment. This is the expected behavior for immutable sequences.
    • C. Incorrect. IndexError occurs when trying to access an index that is out of range. Here, index 1 is valid, so the issue is immutability, not an invalid index.
    • D. Incorrect. The code does not leave the tuple unchanged and continue; it raises an exception when the assignment is attempted, so the program stops with an error.

    Subdomain 3.2: Collect and process data using tuples

    14.Given the tuple `t = (0, 1, 2, 3, 4, 5)`, what does `print(t[::2])` output?

    1. A.(0, 2, 4)
    2. B.(1, 3, 5)
    3. C.(0, 1, 2, 3, 4, 5)
    4. D.(5, 3, 1)
    Show answer & explanation

    Correct answer: A(0, 2, 4)

    • A. Correct. The slice `t[::2]` starts at index 0 (default) and steps by 2, selecting every second element: indices 0, 2, and 4, which correspond to values 0, 2, and 4.
    • B. Incorrect. This would be the output of `t[1::2]`, which starts at index 1 and takes every second element, yielding (1, 3, 5). The given slice starts at index 0, so it selects even indices.
    • C. Incorrect. This is the original tuple without any slicing. It would be produced by `t[:]` or `t[::1]`. Using a step of 2 removes every other element, so the result is shorter.
    • D. Incorrect. This would be the result of `t[::-2]`, which starts at the end and takes every second element backward. A positive step does not reverse the order.

    Subdomain 3.2: Collect and process data using tuples

    15.Which lines of code will raise a `TypeError`? (Choose all that apply.)(Select 2)

    1. A.t = (1,2,3); t[0] = 10
    2. B.t = (1,2,3); t.append(4)
    3. C.t = (1,2,3);print(t[1])
    4. D.t = (1,2,3);del t[0]
    5. E.t = (1,2,3); t.pop()
    6. F.t = (1,2,3); t[1:2]
    Show answer & explanation

    Correct answers: A, Dt = (1,2,3); t[0] = 10; t = (1,2,3);del t[0]

    • A. Correct. Tuples are immutable, so attempting to assign a new value to an index (e.g., `t[0] = 10`) raises a `TypeError`.
    • B. Incorrect. Tuples do not have an `append()` method because they are immutable. Calling `t.append(4)` raises an `AttributeError`, not a `TypeError`.
    • C. Incorrect. Accessing an element by index, such as `t[1]`, is valid for tuples and does not raise any error.
    • D. Correct. Tuples do not support item deletion via `del` on an index. Attempting `del t[0]` raises a `TypeError` because the tuple is immutable.
    • E. Incorrect. Tuples do not have a `pop()` method. Calling `t.pop()` raises an `AttributeError`, not a `TypeError`.
    • F. Incorrect. Slicing a tuple, e.g., `t[1:2]`, is valid and returns a new tuple without modifying the original. It does not raise an error.

    Subdomain 3.1: Collect and process data using lists

    16.Given `my_list = [1, 2, 3, 4, 5]`, what is the value of `my_list[1:4]`?

    1. A.[1, 2, 3]
    2. B.[2, 3, 4]
    3. C.[2, 3, 4, 5]
    4. D.[1, 2, 3, 4]
    Show answer & explanation

    Correct answer: B[2, 3, 4]

    • A. Incorrect. Python slice indices are start-inclusive and stop-exclusive. `my_list[1:4]` starts at index 1 (value 2) and ends before index 4 (value 5), so it does not include the element at index 0 (value 1). Option A corresponds to indices 0 through 2, not 1 through 3.
    • B. Correct. The slice `my_list[1:4]` returns elements at indices 1, 2, and 3, which are the values 2, 3, and 4. The start index 1 is included, and the stop index 4 is excluded.
    • C. Incorrect. If the stop index were included, this would be the result, but Python slices exclude the stop index. `my_list[1:4]` ends before index 4, so the value 5 at index 4 is not part of the slice.
    • D. Incorrect. This slice starts at index 0, not index 1. `my_list[1:4]` begins at index 1 (the second element), so it does not include the first element (value 1).

    Subdomain 3.1: Collect and process data using lists

    17.Given `matrix = [[1, 2], [3, 4]]`, what is `matrix[1][0]`?

    1. A.1
    2. B.2
    3. C.3
    4. D.4
    Show answer & explanation

    Correct answer: C3

    • A. Incorrect. `matrix[1]` selects the second inner list `[3, 4]`, so `matrix[1][0]` accesses its first element, which is 3, not 1. Value 1 would be `matrix[0][0]`, the first element of the first inner list.
    • B. Incorrect. Value 2 is obtained with `matrix[0][1]`, the second element of the first inner list. Here, `matrix[1][0]` indexes the second row and first column, yielding 3.
    • C. Correct. `matrix[1]` refers to the second sublist `[3, 4]`, and `[0]` accesses its first element. Therefore, `matrix[1][0]` equals 3.
    • D. Incorrect. Value 4 is `matrix[1][1]`, the second element of the second inner list. The expression `matrix[1][0]` gives the first element of that list, which is 3.

    Subdomain 3.1: Collect and process data using lists

    18.What is the result of the following code? ``` my_list = [5, 1, 4, 2] my_list.sort() print(my_list[0]) ```

    1. A.5
    2. B.1
    3. C.2
    4. D.4
    Show answer & explanation

    Correct answer: B1

    • A. Incorrect. After calling sort(), the list is reordered in ascending order to [1, 2, 4, 5], so the first element is 1, not 5. The original order is changed in place.
    • B. Correct. The sort() method sorts the list in ascending order, resulting in [1, 2, 4, 5]. Index 0 refers to the first element, which is 1.
    • C. Incorrect. After sorting, the list is [1, 2, 4, 5]; the value 2 is the second element, not the first. print(my_list[0]) accesses only index 0.
    • D. Incorrect. After sorting, the list is [1, 2, 4, 5]; the value 4 is the third element, not the first. The code prints the smallest number in the sorted list.

    Subdomain 3.1: Collect and process data using lists

    19.Which of the following expressions evaluate to a list containing five zeros? (Choose all that apply)(Select 3)

    1. A.[0] * 5
    2. B.list(range(0, 5))
    3. C.[0 for _ in range(5)]
    4. D.[0, 0, 0, 0, 0]
    5. E.list(0, 0, 0, 0, 0)
    6. F.[0] * [2]
    Show answer & explanation

    Correct answers: A, C, D[0] * 5; [0 for _ in range(5)]; [0, 0, 0, 0, 0]

    • A. Correct. The expression `[0] * 5` repeats the single-item list `[0]` five times, producing `[0, 0, 0, 0, 0]`. This is a standard and valid way to create a list with repeated values in Python.
    • B. Incorrect. `list(range(0, 5))` generates a list of integers from 0 to 4, i.e., `[0, 1, 2, 3, 4]`, not five zeros.
    • C. Correct. The list comprehension `[0 for _ in range(5)]` iterates five times, appending `0` each time, resulting in `[0, 0, 0, 0, 0]`. This is a valid way to create a list of five zeros.
    • D. Correct. The literal `[0, 0, 0, 0, 0]` directly defines a list containing five zeros. This explicitly matches the requirement.
    • E. Incorrect. `list(0, 0, 0, 0, 0)` is invalid syntax. The `list()` constructor accepts at most one iterable argument, not multiple separate integers. This raises a TypeError.
    • F. Incorrect. `[0] * [2]` is invalid because list multiplication requires an integer as the multiplier, not a list. Python raises a TypeError for multiplying a list by a list.

    Subdomain 3.3: Collect and process data using dictionaries

    20.Which of the following expressions create a valid dictionary in Python?(Select 3)

    1. A.d = {'a': 1, 'b': 2}
    2. B.d = ['a': 1, 'b': 2]
    3. C.d = dict([('a', 1), ('b', 2)])
    4. D.d = {'a', 'b'}
    5. E.d = {1: 'a', 2: 'b'}
    6. F.d = dict{'a': 1, 'b': 2}
    Show answer & explanation

    Correct answers: A, C, Ed = {'a': 1, 'b': 2}; d = dict([('a', 1), ('b', 2)]); d = {1: 'a', 2: 'b'}

    • A. Correct. This uses standard dictionary literal syntax with curly braces, colons separating keys and values, and commas between pairs. It is a valid way to create a dictionary.
    • B. Incorrect. Square brackets are used for list literals, not dictionaries. The colon inside square brackets is invalid Python syntax. A dictionary literal must use curly braces, or use the dict() constructor with appropriate arguments.
    • C. Correct. The dict() constructor accepts an iterable of key-value pairs. Here, a list of tuples is provided, each tuple containing a key and a value, which is a valid way to create a dictionary.
    • D. Incorrect. Curly braces with comma-separated values but without colons create a set, not a dictionary. To create a dictionary, key-value pairs with colons are required.
    • E. Correct. This is a valid dictionary literal with integer keys and string values. Dictionaries can use any immutable type as keys, including integers.
    • F. Incorrect. The dict constructor is called with parentheses, not curly braces. `dict{'a': 1, 'b': 2}` raises a SyntaxError. Correct usage is `dict(a=1, b=2)` or `dict([('a', 1), ('b', 2)])`.

    Subdomain 3.3: Collect and process data using dictionaries

    21.Which of the following is a valid dictionary in Python?

    1. A.15
    2. B.'pens'
    3. C.None
    4. D.{'notebooks': 10}
    Show answer & explanation

    Correct answer: D{'notebooks': 10}

    • A. Incorrect. `15` is an integer literal, not a dictionary. It does not have key-value pairs.
    • B. Incorrect. `'pens'` is a string literal, not a dictionary. It is enclosed in quotes and represents a sequence of characters.
    • C. Incorrect. `None` is a special keyword in Python representing the absence of a value, not a dictionary.
    • D. Correct. `{'notebooks': 10}` is a valid Python dictionary with one key-value pair, enclosed in curly braces.

    Subdomain 3.3: Collect and process data using dictionaries

    22.Which method is used to add or update key-value pairs in a dictionary?

    1. A.user.update({'age': 25, 'city': 'NYC'})
    2. B.user.add({'age': 25, 'city': 'NYC'})
    3. C.user.append({'age': 25, 'city': 'NYC'})
    4. D.user.merge({'age': 25, 'city': 'NYC'})
    Show answer & explanation

    Correct answer: Auser.update({'age': 25, 'city': 'NYC'})

    • A. Correct. The `update()` method is used to add new key-value pairs or modify existing ones in a dictionary. It takes another dictionary (or an iterable of key-value pairs) and updates the dictionary accordingly.
    • B. Incorrect. Dictionaries do not have an `add()` method; `add()` is associated with sets, not dictionaries.
    • C. Incorrect. `append()` is a list method used to add elements to the end of a list; it is not available for dictionaries.
    • D. Incorrect. Dictionaries do not have a `merge()` method. While merging dictionaries can be done using other techniques (e.g., `update()` or the `|` operator), `merge()` is not a method of dict.

    Subdomain 3.3: Collect and process data using dictionaries

    23.To check if a key exists in a dictionary, use the ______ operator.

    1. A.in
    2. B.not in
    3. C.is
    Show answer & explanation

    Correct answer: Ain

    • A. Correct. The 'in' operator is used to test whether a key exists in a dictionary. For example, 'key in dict' returns True if the key is present.
    • B. Incorrect for checking existence. The 'not in' operator checks for the absence of a key, returning True if the key is not present. It is the opposite of what the sentence requires.
    • C. Incorrect. The 'is' operator checks object identity, not dictionary membership. It does not determine whether a key is contained in a dictionary.

    Subdomain 3.4: Operate with strings

    24.What is the output of 'HelloWorld'[4:1:-1]?

    1. A.oll
    2. B.oW
    3. C.ollW
    4. D.loW
    Show answer & explanation

    Correct answer: Aoll

    • A. Correct. The slice starts at index 4 ('o'), moves backward with step -1 through indices 3 and 2 ('l', 'l'), and stops before index 1, yielding 'oll'.
    • B. Incorrect. The slice does not produce 'oW' because it moves backward from index 4, not forward, and 'W' at index 5 is not included in the slice range.
    • C. Incorrect. The slice does not produce 'ollW' because it stops before index 1 (exclusive), so index 5 ('W') is not included; only indices 4, 3, and 2 are included.
    • D. Incorrect. The slice does not produce 'loW' because the start index is 4 ('o'), not 3, and the step is negative, moving backward, so 'l' at index 3 comes after 'o', not before.

    Subdomain 3.4: Operate with strings

    25.What does the strip() method do when called with no arguments on a string?

    1. A.Removes all whitespace characters from the string.
    2. B.Removes leading and trailing whitespace characters.
    3. C.Removes only the leading whitespace characters from the string.
    4. D.Removes only the trailing whitespace characters from the string.
    Show answer & explanation

    Correct answer: BRemoves leading and trailing whitespace characters.

    • A. Incorrect. The strip() method does not remove whitespace from the middle of the string; it only removes leading and trailing whitespace.
    • B. Correct. When called without arguments, strip() removes all leading and trailing whitespace characters (spaces, tabs, newlines) from the string, leaving internal whitespace unchanged.
    • C. Incorrect. The strip() method removes whitespace from both ends, not just the leading side. To remove only leading whitespace, use the lstrip() method.
    • D. Incorrect. The strip() method removes whitespace from both ends, not just the trailing side. To remove only trailing whitespace, use the rstrip() method.

    Subdomain 3.4: Operate with strings

    26.What is the length of the string 'C:\\new\\file'?

    1. A.10
    2. B.11
    3. C.8
    4. D.12
    Show answer & explanation

    Correct answer: B11

    • A. Incorrect. In Python, '\\' is an escape sequence for a single backslash. Thus the actual string is 'C:\new\file' which has 11 characters (C, :, \, n, e, w, \, f, i, l, e). Counting as 10 likely omits one character, e.g., the colon or a backslash.
    • B. Correct. The string literal 'C:\\new\\file' contains two escape sequences '\\', each representing one backslash. The resulting string is 'C:\new\file' with characters: C, :, \, n, e, w, \, f, i, l, e — totaling 11 characters.
    • C. Incorrect. 8 is too low. The actual string has 11 characters, including the colon and both backslashes. This option likely ignores multiple characters.
    • D. Incorrect. 12 would be the length if each backslash were counted as two characters, but each '\\' represents a single character. The correct length is 11.

    Subdomain 3.4: Operate with strings

    27.Which of the following string methods can be used to verify that a string consists only of digits? (Choose all that apply)(Select 3)

    1. A.isdigit()
    2. B.isnumeric()
    3. C.isdecimal()
    4. D.isalpha()
    5. E.isalnum()
    Show answer & explanation

    Correct answers: A, B, Cisdigit(); isnumeric(); isdecimal()

    • A. Correct. isdigit() returns True if all characters in the string are digits (including digits from other scripts, e.g., superscripts) and there is at least one character. It can be used to verify a string consists only of digits.
    • B. Correct. isnumeric() returns True if all characters are numeric characters (including digits, fractions, Roman numerals, etc.) and there is at least one character. It is broader than isdigit() but still checks for numeric-only content.
    • C. Correct. isdecimal() returns True if all characters are decimal digits (e.g., 0-9 and decimal digits from other scripts) and there is at least one character. It is the most strict of the three digit-checking methods.
    • D. Incorrect. isalpha() checks whether all characters are alphabetic letters, not digits. It returns False for strings containing digits.
    • E. Incorrect. isalnum() checks whether all characters are alphanumeric (letters or digits). It does not require the string to be only digits; a string with letters would also pass.

    Domain 4: Functions and Exceptions

    Subdomain 4.2: Organize interaction between the function and its environment

    28.Examine this code: counter = 0 def increment(): counter = counter + 1 increment() print(counter) What is the result?

    1. A.The result is that it prints 1.
    2. B.The result is that it prints 0.
    3. C.An UnboundLocalError occurs.
    4. D.The result is that it prints None.
    Show answer & explanation

    Correct answer: CAn UnboundLocalError occurs.

    • A. Incorrect. The function attempts to assign to 'counter' locally, but it is referenced before assignment, causing an UnboundLocalError. Thus the program does not print 1.
    • B. Incorrect. Although the global counter is 0, the code never reaches the print statement because an error occurs during the function call.
    • C. Correct. Inside increment(), Python treats 'counter' as a local variable due to the assignment. When executing counter = counter + 1, the local variable is used before being assigned, leading to an UnboundLocalError.
    • D. Incorrect. The function does not return anything, but the main issue is that an exception is raised before print(counter) can execute, so the program does not print None.

    Subdomain 4.2: Organize interaction between the function and its environment

    29.What is the output of the following? value = 5 def show(): print(value) value = 10 show()

    1. A.5
    2. B.10
    3. C.UnboundLocalError
    4. D.SyntaxError
    Show answer & explanation

    Correct answer: CUnboundLocalError

    • A. Incorrect. The assignment `value = 10` inside the function makes `value` a local variable, so the global value 5 is not accessible. The `print(value)` statement tries to read the local variable before it is assigned, causing an error.
    • B. Incorrect. The `print(value)` statement is executed before the assignment `value = 10`, so the function does not output 10. The code raises an error at the print statement.
    • C. Correct. Because `value` is assigned inside `show()`, Python treats it as a local variable throughout the function. When `print(value)` runs, the local `value` has not been assigned yet, raising an `UnboundLocalError`.
    • D. Incorrect. The code is syntactically valid; no `SyntaxError` occurs. The error is a runtime `UnboundLocalError`, which is not a syntax error.

    Subdomain 4.2: Organize interaction between the function and its environment

    30.Which of the following statements about default parameter values are true? (Select all that apply)(Select 3)

    1. A.Default values are evaluated when the function is defined.
    2. B.Mutable defaults persist changes across calls.
    3. C.Modifying a mutable default leads to unexpected side effects.
    4. D.Default values are restricted to immutable types.
    5. E.If a default is a function call, it is evaluated each call.
    6. F.Functions cannot have more than three default parameters.
    Show answer & explanation

    Correct answers: A, B, CDefault values are evaluated when the function is defined.; Mutable defaults persist changes across calls.; Modifying a mutable default leads to unexpected side effects.

    • A. Correct. Default values are evaluated once at function definition time, not each time the function is called. The computed value is reused for all calls that omit the argument.
    • B. Correct. If the default is mutable (e.g., list, dict), modifications made inside the function persist across subsequent calls because the same object is reused.
    • C. Correct. Modifying a mutable default can cause unexpected side effects, as the shared object carries changes to later calls. This is why mutable defaults are generally discouraged.
    • D. Incorrect. Default values can be of any type, including mutable objects like lists or dictionaries. The only restriction is that parameters with defaults must come after those without.
    • E. Incorrect. If a default value is the result of a function call, that call is evaluated only once when the function is defined, not at each invocation. The resulting value is stored as the default.
    • F. Incorrect. Python imposes no limit on the number of parameters with default values. The only syntactic rule is that default parameters must follow non-default parameters.

    Subdomain 4.2: Organize interaction between the function and its environment

    31.Which statement is true about the following code? def func(): global y y = y + 1 y = 5 func() print(y)

    1. A.The code outputs the integer 6 after the function call.
    2. B.The code outputs the integer 5 after the function call.
    3. C.The code raises UnboundLocalError as y is not defined locally.
    4. D.The code raises NameError because y is never assigned a value.
    Show answer & explanation

    Correct answer: AThe code outputs the integer 6 after the function call.

    • A. Correct. The `global y` declaration inside the function binds the name `y` to the global variable. The function increments the global `y` from 5 to 6, and thus `print(y)` outputs 6.
    • B. Incorrect. The function does not leave `y` unchanged; it increments the global variable via the `global` keyword. Therefore, the output is 6, not 5.
    • C. Incorrect. The `global` statement does not require the variable to be defined before it; it simply declares that the name refers to the global scope. Since `y` is defined globally before the function call, no UnboundLocalError occurs.
    • D. Incorrect. The global variable `y` is explicitly assigned the value 5 before the function is called, so it is initialized. No NameError is raised.

    Subdomain 4.1: Decompose the code using functions

    32.Given the function definition below, which call prints `Hello Sam`? def greet(greeting, name): print(greeting, name)

    1. A.greet("Hello", "Sam")
    2. B.greet("Sam", "Hello")
    3. C.greet(name="Hello", greeting="Sam")
    4. D.greet("Sam")
    Show answer & explanation

    Correct answer: Agreet("Hello", "Sam")

    • A. This call passes the greeting first and the name second, matching the parameter order, so it prints Hello followed by Sam.
    • B. This call swaps the positional arguments, so greeting becomes Sam and name becomes Hello, printing them in the wrong order.
    • C. This call assigns Hello to name and Sam to greeting via keywords, which prints Sam Hello, not Hello Sam.
    • D. This call supplies only one positional argument for a function that requires two, so Python raises a TypeError instead of printing anything.

    Subdomain 4.1: Decompose the code using functions

    33.What value is produced by calling the following function as check(5)? def check(n): if n > 0: return return n

    1. A.None
    2. B.5
    3. C.True
    4. D.An error, because return must include a value
    Show answer & explanation

    Correct answer: ANone

    • A. Since 5 is greater than 0, the bare return statement with no expression executes, and a return with no expression always produces None.
    • B. The argument value itself is never sent back in this branch; the second return statement that would return n is never reached.
    • C. Nothing in this function evaluates or returns a Boolean value, so this outcome does not match how the code behaves.
    • D. A return statement without an expression is valid Python syntax; it simply causes the function to exit while producing the value None.

    Subdomain 4.1: Decompose the code using functions

    34.Which of the following are true characteristics of Python generator functions?(Select 3)

    1. A.A generator function contains at least one yield statement
    2. B.Calling a generator function immediately executes its entire body
    3. C.A generator produces values lazily, one at a time, on each call to next()
    4. D.Generator functions must always include a return statement to produce values
    5. E.A generator object can be iterated with a for loop
    Show answer & explanation

    Correct answers: A, C, EA generator function contains at least one yield statement; A generator produces values lazily, one at a time, on each call to next(); A generator object can be iterated with a for loop

    • A. The presence of at least one such statement in the function body is exactly what distinguishes a generator function from a regular one.
    • B. Calling the function only creates a generator object; the body does not run until the generator is advanced through iteration or next().
    • C. Values are computed and produced only as they are requested, which is the defining lazy-evaluation behavior of generators.
    • D. A generator function typically has no explicit return of a value at all; it yields values instead, and any return simply ends iteration.
    • E. Generator objects implement the iterator protocol, so a for loop can consume their yielded values directly.

    Subdomain 4.1: Decompose the code using functions

    35.To make a function produce a series of values lazily, one at a time, instead of computing and returning them all at once, use the ____ keyword inside its body.

    1. A.yield
    2. B.return
    3. C.pass
    Show answer & explanation

    Correct answer: Ayield

    • A. This keyword pauses execution and hands back one value at a time, which is exactly what lazy, on-demand value production requires.
    • B. This keyword sends back a single value and ends the function entirely, which does not support producing a series of values over time.
    • C. This keyword is a no-op placeholder statement and has no effect on producing or returning values at all.

    Want the full experience?

    These are just samples. Practice the full Python Institute PCEP™ – Certified Entry-Level Python Programmer question bank in quiz mode — free, no signup, with domain practice and exam simulation.