PCEP (30-03) Practice Test

PCEP™ – Certified Entry-Level Python Programmer

PCEP overview

  • 200 practice questions
  • 32 flashcards
  • 5 study guide topics
  • 39 key terms

What you'll study

  • Computer Programming and Python Fundamentals17%
  • Control Flow: Conditional Blocks and Loops23%
  • Data Collections: Lists, Tuples, Sets, Dictionaries, and Strings26%
  • Functions and Exceptions20%
  • File Handling and Module Imports14%

PCEP™ – Certified Entry-Level Python Programmer (exam code PCEP-30-03) is the entry-level credential in the Python Institute's General-Purpose Programming certification pathway, which continues with PCAP™, PCPP1™ and PCPP2™. It is intended for students, beginners, career changers and working professionals who want independent evidence that they can read, trace, complete and write short Python programs. There are no prerequisites, and the exam deliberately emphasizes practical code understanding rather than advanced software engineering. The 35-question, 50-minute exam is delivered through the OpenEDG testing service (TestNow™) and is scored across five weighted sections: Computer Programming and Python Fundamentals (17%), Control Flow: Conditional Blocks and Loops (23%), Data Collections: Lists, Tuples, Sets, Dictionaries, and Strings (26%), Functions and Exceptions (20%), and File Handling and Module Imports (14%). A passing score is 70%, and the credential is valid for five years. Because collections and control flow together account for roughly half the paper, preparation should centre on predicting the output of small snippets - loop boundaries, slice results, mutability, argument passing and caught exceptions - rather than memorising definitions. Building and debugging short scripts is the most reliable way to prepare, supplemented by the free Python Essentials 1 course and the published syllabus.

Common mistakes

Predicting that -7 // 2 is -3 and that -7 % 2 is -1, i.e. applying C/Java truncate-toward-zero rules to Python's // and %.

Most candidates arrive from languages where integer division truncates toward zero and the remainder takes the dividend's sign. Python's // floors toward negative infinity and % takes the divisor's sign, so answers only differ when a negative operand is involved - exactly the case the exam likes to test.

What to do instead

Re-derive with the identity a == (a // b) * b + (a % b) and check the sign of b first: -7 // 2 == -4, -7 % 2 == 1, 7 % -2 == -1, 7 // -2 == -4. Also recall // on floats returns a float (7.0 // 2 -> 3.0) and that /, // and % all raise ZeroDivisionError.

Evaluating Boolean and arithmetic expressions with equal precedence and left-to-right grouping, e.g. reading 'not a == b' as '(not a) == b', '2 ** 3 ** 2' as 64, or assuming 'x or y' always evaluates to True/False.

English reading order and other languages' syntax suggest these groupings, but 'not' binds looser than comparisons, '**' is right-associative, comparisons chain, and 'and'/'or' short-circuit by returning one of their operands rather than a bool.

What to do instead

Memorise the ladder: ** (right-assoc), unary +/-, * / // %, + -, comparisons (chained, e.g. 5 > 3 > 1 is True but (5 > 3) > 1 is False), not, and, or. So 2 ** 3 ** 2 == 512 and not 1 == 2 is True. Track operand returns too: 0 or 'x' -> 'x', [] and 'x' -> [], 'a' and 'b' -> 'b'.

Assuming the else clause of a for or while loop runs only when the body never executed, or that it still runs after a break.

The keyword 'else' suggests if/else semantics, and many candidates also confuse it with the try/except/else clause. Python's loop else is really a 'no break' clause.

What to do instead

Read loop else as 'executed only if the loop finished without hitting break'. It runs for an empty iterable (for x in []: ... else: runs), runs when a while condition becomes false, and is not skipped by continue. A break anywhere in the body skips it; use a found flag if the logic feels ambiguous.

Miscounting how many times a loop body runs: treating a dedented statement as part of the body, or expecting range(5, 0) / range(0, 5, -1) to produce values.

Python marks blocks by indentation rather than braces, and editors re-indent on paste, so a total or print that sits at the header's column runs once, not per iteration. range() is also stop-exclusive and direction-sensitive, so a start/stop/step combination that 'looks ascending' yields an empty sequence.

What to do instead

Trace loops by writing the iteration number and the value of every variable in a column, and check each line's indentation against the colon-terminated header: the body is exactly the lines indented deeper. Remember range(a, b) stops before b, and a negative step needs start > stop (range(5, 0, -1) -> 5,4,3,2,1; range(0, 5, -1) -> empty).

Treating b = a as a copy for lists and dicts, and deleting elements from a list with a for loop over that same list.

Assignment binds a name to an existing object, so a and b are two labels on one box and a mutation through either name shows up in both. A for loop walks a live index, so removing an element shifts the remaining ones left and the following element is skipped.

What to do instead

Draw both names pointing at one object; create independent copies with a[:], a.copy(), list(a), dict(d) or copy.deepcopy for nested data. To filter or delete, build a new list ([x for x in a if keep(x)]) or iterate over a copy (for x in a[:]), and remember that passing a list to a function passes the same object, so in-place changes are visible to the caller.

Writing t = (5) and expecting a one-element tuple, s = {} and expecting an empty set, calling s[0] on a set, or assuming str.upper() / tuple item assignment mutate the object.

Parentheses only group an expression, {} is a dict literal because dict predates set literals, sets are unordered and unindexed, and strings and tuples are immutable, so their methods return new objects instead of changing one in place.

What to do instead

Use (5,) for a one-element tuple, set() for an empty set (or {1, 2} for a populated one), and iterate a set or use sorted(s)[0] rather than indexing it. Assign with s = s.upper(). Expect TypeError for s[0] = 'x' on a str or tuple, and remember a slice never raises for an out-of-range bound ('abc'[10:20] -> '') while an index does ('abc'[10] -> IndexError).

Defining a function such as def add(item, bucket=[]) and being surprised that successive calls accumulate items, or assuming the caller's arguments are always protected from change.

Default expressions are evaluated once, when the def statement executes, so the same list object is reused for every call that omits the argument. Similarly, arguments are bound by object reference, so mutating a list or dict parameter is visible to the caller, while rebinding an immutable parameter is not.

What to do instead

Use an immutable sentinel and build inside the body: def add(item, bucket=None): if bucket is None: bucket = []. For the passing question, ask whether the function mutates the object (visible outside) or rebinds the name (invisible outside), and remember that reassigning a global inside a function without a global declaration creates a local, producing UnboundLocalError.

Putting a broad except Exception (or a bare except) before a specific handler, assuming the exception name stays usable after the block, or assuming a finally block is skipped when the try block returns.

Handlers are tested top to bottom and the first match wins, so a broad clause makes later ones dead code; in Python 3 the 'as e' name is deleted when the except block ends; and finally is designed to run on every exit path, including return, break and an uncaught exception.

What to do instead

Order handlers from most specific to most general (ValueError before Exception), avoid bare except (it also catches KeyboardInterrupt and SystemExit), and copy the exception to another variable if you need it later. Remember try/except/else runs else only when no exception occurred, and that raising a built-in like ValueError('msg') is legal while raise 'msg' is a TypeError.

Opening a file with mode 'w' to read data, forgetting that readlines() keeps the trailing newline, or writing an int directly to a file handle.

Mode 'w' silently truncates an existing file before any read or write, the default mode is 'r' so a missing file raises FileNotFoundError, read() and readlines() preserve '\n' characters, and write() accepts only str, so non-string arguments raise TypeError.

What to do instead

Choose the mode deliberately: 'r' read, 'w' truncate-and-write, 'a' append, 'x' create-or-fail. Use with open(path) as f: so the file closes even on error, compare lines with line.strip() or line.rstrip('\n'), and convert before writing (f.write(str(n) + '\n')). Remember a closed handle raises ValueError: I/O operation on closed file.

Mixing the two import forms - writing import math and then calling sqrt(16), or from math import sqrt and then calling math.sqrt(16) - or expecting a module's top-level code not to run on import.

import math binds only the name math, so the function must be reached as math.sqrt; from math import sqrt binds the function name directly and leaves math undefined. Module-level statements execute once, the first time the module is imported in that process, and the result is cached in sys.modules.

What to do instead

Decide which name you created: after import math use math.sqrt; after from math import sqrt use sqrt. Avoid from module import * in exam code because later names can shadow earlier ones. If a script must both be importable and runnable, guard side effects with if name == 'main':, and watch for a local file whose name shadows a standard-library module.

Exam requirements can change. Confirm current details with the exam provider.

PCEP practice

200 questions. Each one lists the choices, the correct answer, and an explanation. With JavaScript, this list opens one question at a time. The checker at the top of this page saves progress in this browser when it is available.

  1. Question 1Computer Programming and Python Fundamentals

    Which of the following is a valid Python identifier?

    1. _total2 Correct answer.
    2. class
    3. total-2
    4. 2nd_place

    Explanation

    A Python identifier may contain letters, digits, and underscores, but it cannot begin with a digit, contain a hyphen, or be a reserved keyword. The name _total2 satisfies all of these rules.

  2. Question 2Computer Programming and Python Fundamentals

    What is the result of the expression "py" * 3?

    1. py3
    2. py py py
    3. TypeError
    4. pypypy Correct answer.

    Explanation

    Multiplying a string by an integer repeats the string that many times, with no separator inserted. Thus "py" * 3 produces the single string pypypy.

  3. Question 3Computer Programming and Python Fundamentals

    What value does int(3.9) produce?

    1. ValueError
    2. 4
    3. 3.9
    4. 3 Correct answer.

    Explanation

    Calling int() on a float truncates the fractional part toward zero rather than rounding it. Therefore int(3.9) returns the integer 3.

  4. Question 4Computer Programming and Python Fundamentals

    What is the value of this expression: 2 + 3 * 4 ** 2 // 8?

    1. 10
    2. 14
    3. 5
    4. 8 Correct answer.

    Explanation

    Exponentiation is evaluated first, giving 4 ** 2 = 16. Then multiplication and floor division are evaluated left to right: 3 * 16 = 48 and 48 // 8 = 6, and finally 2 + 6 = 8.

  5. Question 5Computer Programming and Python Fundamentals

    What is the value of the expression 17 // 5 + 17 % 5?

    1. 6
    2. 5 Correct answer.
    3. 3
    4. 7

    Explanation

    The // operator gives the floor quotient 3, and the % operator gives the remainder 2. Adding those results produces 5.

  6. Question 6Computer Programming and Python Fundamentals

    A program runs name = input("Name: ") and the user types Ada. What type does the variable name hold?

    1. bool
    2. int
    3. float
    4. str Correct answer.

    Explanation

    The input() function always returns a string containing the characters the user typed. Numeric-looking input must be converted explicitly with int() or float() before arithmetic is performed.

  7. Question 7Computer Programming and Python Fundamentals

    What does this program print? x = 5 if x > 0: x = x + 10 elif x == 5: x = x + 20 print(x)

    1. 25
    2. 15 Correct answer.
    3. 5
    4. 20

    Explanation

    The first condition x > 0 is true, so x becomes 15. Because an if/elif chain stops after the first true branch, the elif test is skipped even though x was originally 5.

  8. Question 8Computer Programming and Python Fundamentals

    What output does this code produce? print("a", "b", sep="-", end="!") print("c")

    1. a-b!c Correct answer.
    2. a-b!\nc
    3. a-b! c
    4. a b!c

    Explanation

    The sep argument places a hyphen between the two printed values, and end="!" replaces the usual newline with an exclamation mark. The second print then continues on the same line and appends c.

  9. Question 9Computer Programming and Python Fundamentals

    What does this program print? n = 0 while n < 5: n += 1 if n == 3: break else: print("done") print(n)

    1. done
    2. done\n3
    3. 3 Correct answer.
    4. 5

    Explanation

    The loop stops with break when n reaches 3. A while loop's else clause runs only when the loop ends normally, so the break skips it and only the final print executes.

  10. Question 10Computer Programming and Python Fundamentals

    What is the value of this expression: not 5 % 2 or 3 ** 2 < 10?

    1. False
    2. 9
    3. 1
    4. True Correct answer.

    Explanation

    Exponentiation and modulo are evaluated before comparison, so 3 ** 2 < 10 is True and 5 % 2 is 1. The not operator turns 1 into False, and False or True evaluates to True.

  11. Question 11Computer Programming and Python Fundamentals

    Which of the following built-in Python types is immutable, meaning its contents cannot be changed after the object is created?

    1. tuple Correct answer.
    2. dict
    3. set
    4. list

    Explanation

    A tuple is immutable: once it is created, its elements cannot be replaced, added, or removed. Lists, dictionaries, and sets are mutable container types whose contents can be modified in place. Attempting to assign to a tuple element raises a TypeError.

  12. Question 12Computer Programming and Python Fundamentals

    Which of these values is treated as false when used as a condition in Python?

    1. [0]
    2. 0 Correct answer.
    3. "0"
    4. -1

    Explanation

    Python treats numeric zero, empty containers, empty strings, None, and False as falsy. The string "0" is non-empty, the list [0] contains one element, and -1 is a nonzero integer, so all three are truthy.

  13. Question 13Computer Programming and Python Fundamentals

    What is the result of evaluating the expression "3" + 3 in Python?

    1. 6
    2. "3 3"
    3. "33"
    4. TypeError Correct answer.

    Explanation

    The + operator requires operands of compatible types. A string and an integer cannot be added, so Python raises a TypeError instead of converting automatically. An explicit conversion such as "3" + str(3) would be required.

  14. Question 14Computer Programming and Python Fundamentals

    What does this program print? a = [1, 2, 3] b = a b.append(4) print(a)

    1. [1, 2, 3]
    2. [1, 2, 3, 4] Correct answer.
    3. [1, 2, 3, 4, 4]
    4. [4]

    Explanation

    Assigning b = a copies the reference to the list, not the list itself, so both names refer to the same object. Calling append through b modifies that shared list. Printing a therefore shows the updated contents [1, 2, 3, 4].

  15. Question 15Computer Programming and Python Fundamentals

    What does this program print? s = "programming" print(s[3:7])

    1. "gram" Correct answer.
    2. "pro"
    3. "ram"
    4. "ogra"

    Explanation

    Slicing uses a start index that is included and a stop index that is excluded, with indices counted from 0. In "programming", index 3 is g and index 6 is m, so s[3:7] returns "gram". The character at index 7 is not included.

  16. Question 16Computer Programming and Python Fundamentals

    Which list is produced by list(range(1, 10, 3))?

    1. [1, 4, 7, 10]
    2. [1, 2, 3]
    3. [1, 4, 7] Correct answer.
    4. [3, 6, 9]

    Explanation

    range(start, stop, step) begins at 1, stops before 10, and increments by 3. The generated values are 1, 4, and 7; the next value, 10, is not less than the stop value. Converting the range with list() materializes those values.

  17. Question 17Computer Programming and Python Fundamentals

    What does this program print? d = {"a": 1} print(d.get("b", 0))

    1. 0 Correct answer.
    2. None
    3. KeyError
    4. 1

    Explanation

    The dict.get method returns the supplied default when the key is absent instead of raising an exception. Because "b" is not in the dictionary, the default 0 is printed. The existing key "a" would have returned 1.

  18. Question 18Computer Programming and Python Fundamentals

    What list is produced by this expression? [x * 2 for x in range(4) if x % 2]

    1. [2, 4, 6]
    2. [0, 2, 4, 6]
    3. [2, 6] Correct answer.
    4. [1, 3]

    Explanation

    The comprehension iterates over 0, 1, 2, and 3 and keeps only values for which x % 2 is nonzero. Those values are 1 and 3, and each is multiplied by 2. The resulting list is [2, 6].

  19. Question 19Computer Programming and Python Fundamentals

    What does this program print? def add(item, bag=[]): bag.append(item) return bag print(add(1)) print(add(2))

    1. first [1], then [1, 2] Correct answer.
    2. first [], then [1, 2]
    3. first [1], then [2]
    4. first [2], then [1, 2]

    Explanation

    Default argument values are evaluated once when the function is defined, so the same list object is reused on every call. The first call appends 1 and returns [1]. The second call appends 2 to that same list, returning [1, 2].

  20. Question 20Computer Programming and Python Fundamentals

    What does this program print? nums = [3, 1, 2] result = nums.sort() print(result)

    1. [1, 2, 3]
    2. sorted [1, 2, 3]
    3. [3, 1, 2]
    4. None Correct answer.

    Explanation

    The list.sort method sorts the list in place and returns None rather than a new list. The variable result therefore receives None. The built-in sorted function would instead return a new sorted list.

  21. Question 21Computer Programming and Python Fundamentals

    What is the type of the value produced by the expression 7 / 2 in Python 3?

    1. integer
    2. string
    3. boolean
    4. float Correct answer.

    Explanation

    In Python 3, the / operator performs true division, so it always returns a float. Even though 7 divided by 2 has no fractional remainder, the result is 3.5 with type float.

  22. Question 22Computer Programming and Python Fundamentals

    What does this program print? x = 10 x -= 3 print(x)

    1. 13 Correct answer.
    2. 3
    3. 10
    4. 7

    Explanation

    The augmented assignment x -= 3 subtracts 3 from the current value of x and rebinds x to the result. Starting from 10, the new value is 7.

  23. Question 23Computer Programming and Python Fundamentals

    What does this program print? word = "Python" print(word[1])

    1. y Correct answer.
    2. P
    3. o
    4. t

    Explanation

    String indexing is zero-based, so word[0] is 'P' and word[1] is the second character, 'y'. The print call displays only that single character.

  24. Question 24Computer Programming and Python Fundamentals

    What does this program print? x = 5 def change(): x = 10 change() print(x)

    1. 15
    2. 10
    3. 5 Correct answer.
    4. NameError

    Explanation

    Assigning x inside change creates a new local variable named x because there is no global declaration. The module-level x remains 5, so the final print shows 5.

  25. Question 25Computer Programming and Python Fundamentals

    What does this program print? nums = [1, 2] nums.extend([3, 4]) print(nums)

    1. [1, 2, [3, 4]]
    2. [3, 4, 1, 2]
    3. [1, 2, 3, 4] Correct answer.
    4. [[1, 2], 3, 4]

    Explanation

    list.extend adds each element of the iterable to the end of the list, so the numbers 3 and 4 become separate items. The original list is mutated to [1, 2, 3, 4].

  26. Question 26Computer Programming and Python Fundamentals

    What does this program print? d = {"a": 1, "b": 2} print(list(d))

    1. ['a', 'b'] Correct answer.
    2. [1, 2]
    3. {'a', 'b'}
    4. [('a', 1), ('b', 2)]

    Explanation

    Iterating over a dictionary yields its keys, not its values or key-value pairs. Wrapping the iteration in list produces a list of the keys in insertion order, ['a', 'b'].

  27. Question 27Computer Programming and Python Fundamentals

    What happens when this code runs? s = "abc" s[0] = "A"

    1. The string becomes 'A' and drops the rest
    2. A TypeError is raised Correct answer.
    3. The string becomes 'abcA' in place
    4. The string becomes 'Abc' in place

    Explanation

    Strings are immutable, so assigning to a single character position is not allowed. The statement s[0] = 'A' raises TypeError before any change can occur.

  28. Question 28Computer Programming and Python Fundamentals

    What does this program print? for i, ch in enumerate("ab", start=1): print(i, ch)

    1. a 1 b 2
    2. 1 a 1 b
    3. 1 a 2 b Correct answer.
    4. 0 a 1 b

    Explanation

    enumerate yields pairs of an index and the corresponding item. With start=1, the first pair is (1, 'a') and the second is (2, 'b'), and print displays each pair with a space.

  29. Question 29Computer Programming and Python Fundamentals

    What does this program print? def f(a, b=2, *args): return a + b + len(args) print(f(1, 3, 4, 5))

    1. 5
    2. 10
    3. 6 Correct answer.
    4. 7

    Explanation

    The first positional argument 1 binds to a, the second argument 3 binds to b, and the remaining arguments 4 and 5 are collected in args. Thus len(args) is 2, and a + b + len(args) equals 1 + 3 + 2 = 6.

  30. Question 30Computer Programming and Python Fundamentals

    What does this program print? a = [1, 2] b = [1, 2] print(a == b, a is b)

    1. True False Correct answer.
    2. False True
    3. True True
    4. False False

    Explanation

    The == operator compares list contents, and both lists contain 1 and 2, so the first result is True. The is operator compares object identity; a and b are two distinct list objects, so the second result is False.

  31. Question 31Computer Programming and Python Fundamentals

    Which identifier is accepted by the Python interpreter as a variable name?

    1. user-name
    2. total_sum Correct answer.
    3. class
    4. 2nd_place

    Explanation

    Python variable names must start with a letter or underscore and may contain letters, digits, and underscores. They cannot begin with a digit, use keywords such as class, or include hyphens.

  32. Question 32Computer Programming and Python Fundamentals

    What does print(-7 // 2) output?

    1. -4 Correct answer.
    2. -3
    3. -3.5
    4. 3

    Explanation

    The // operator performs floor division, so -7 divided by 2 is -3.5 and is rounded down to the next lower integer, -4. It does not truncate toward zero.

  33. Question 33Computer Programming and Python Fundamentals

    What does this program print? a, b = 1, 2 a, b = b, a print(a, b)

    1. 2 1 Correct answer.
    2. 2 2
    3. 1 1
    4. 1 2

    Explanation

    In a multiple assignment, the right-hand side is evaluated first as a tuple and then unpacked. The values b and a are therefore read before either variable is rebound, producing 2 1.

  34. Question 34Computer Programming and Python Fundamentals

    What does print(0.1 + 0.2 == 0.3) output?

    1. False Correct answer.
    2. Error
    3. True
    4. None

    Explanation

    Binary floating-point cannot represent 0.1, 0.2, and 0.3 exactly, so 0.1 + 0.2 is slightly different from 0.3. The comparison therefore evaluates to False, and print displays False.

  35. Question 35Control Flow: Conditional Blocks and Loops

    What is printed by this code? x = 10 if x > 5: print("A") elif x > 8: print("B") else: print("C")

    1. A then B
    2. C
    3. B
    4. A Correct answer.

    Explanation

    An if/elif chain tests conditions in order and executes only the first branch whose condition is true. Since 10 > 5 is true, the elif and else branches are skipped entirely, so only A is printed.

  36. Question 36Control Flow: Conditional Blocks and Loops

    What output does this loop produce? for i in range(2, 10, 3): print(i, end=" ")

    1. 3 6 9
    2. 2 4 6 8
    3. 2 5 8 Correct answer.
    4. 2 3 4 5 6 7 8 9

    Explanation

    range(start, stop, step) begins at start and adds step until it reaches or passes stop, excluding stop itself. Starting at 2 with step 3 gives 2, 5, and 8, so the loop prints those values.

  37. Question 37Control Flow: Conditional Blocks and Loops

    What is printed by this code? n = 0 while n < 5: n += 2 print(n)

    1. 4
    2. 7
    3. 6 Correct answer.
    4. 5

    Explanation

    The condition is checked before each iteration. n takes the values 0, 2, 4, and then 6; when n becomes 6, 6 < 5 is false and the loop stops, leaving n equal to 6.

  38. Question 38Control Flow: Conditional Blocks and Loops

    What is printed by this code? for i in range(4): if i == 2: break else: print("else") print(i)

    1. 0
    2. 2 Correct answer.
    3. else 2
    4. else

    Explanation

    A loop's else clause runs only when the loop terminates normally, not when break exits it. The break occurs when i is 2, so the else block is skipped and the final value of i, 2, is printed.

  39. Question 39Control Flow: Conditional Blocks and Loops

    What output does this code produce? i = 0 while i < 5: i += 1 if i == 3: continue print(i, end=" ")

    1. 1 2 4 5 Correct answer.
    2. 1 3 4 5
    3. 1 2 4 5 6
    4. 1 2 3 4 5

    Explanation

    The increment happens before the if, so the counter still advances when continue skips printing. The printed values are 1, 2, then 4 and 5 after 3 is skipped, and the loop ends when i reaches 6.

  40. Question 40Control Flow: Conditional Blocks and Loops

    What is printed by this code? x = 4 if x > 0: if x % 2 == 0: print("even") else: print("non-positive")

    1. even Correct answer.
    2. non-positive
    3. even then non-positive
    4. nothing is printed

    Explanation

    Python binds an else to the nearest if at the same indentation level, and here that is the outer if. The outer condition is true, the inner condition prints even, and the outer else is skipped.

  41. Question 41Control Flow: Conditional Blocks and Loops

    What is printed by this code? values = [0, 1, "", "0", [], [0]] count = 0 for v in values: if v: count += 1 print(count)

    1. 2
    2. 6
    3. 3 Correct answer.
    4. 4

    Explanation

    A condition is true for non-zero numbers and non-empty containers, including strings and lists. The truthy values are 1, '0', and [0], giving a count of 3.

  42. Question 42Control Flow: Conditional Blocks and Loops

    What is printed by this code? total = 0 for i in range(1, 6): if i % 2 == 0: continue total += i print(total)

    1. 3
    2. 9 Correct answer.
    3. 6
    4. 15

    Explanation

    continue skips the rest of the current iteration, so even values are not added. The odd values from 1 through 5 are 1, 3, and 5, whose sum is 9.

  43. Question 43Control Flow: Conditional Blocks and Loops

    What is printed by this code? count = 0 for i in range(3): for j in range(3): if j == i: break count += 1 print(count)

    1. 3 Correct answer.
    2. 0
    3. 6
    4. 9

    Explanation

    break exits only the innermost loop that contains it, so the outer for loop continues with its next value. Counting increments before each inner break gives 0 + 1 + 2 = 3.

  44. Question 44Control Flow: Conditional Blocks and Loops

    What is printed by this code? x = 5 y = 0 if x > 3 and y != 0 or x == 5: print("yes") else: print("no")

    1. yes only if y is nonzero
    2. a TypeError is raised
    3. no
    4. yes Correct answer.

    Explanation

    The and operator has higher precedence than or, so the expression groups as (x > 3 and y != 0) or (x == 5). The first part is false, but x == 5 is true, so the if block runs and prints yes.

  45. Question 45Control Flow: Conditional Blocks and Loops

    What is printed by this code? if "False": print("truthy") else: print("falsy")

    1. truthy Correct answer.
    2. falsy
    3. nothing is printed
    4. False

    Explanation

    A non-empty string is truthy in Python, and the text inside it does not change that. Because "False" contains characters, the if condition succeeds and the program prints truthy.

  46. Question 46Control Flow: Conditional Blocks and Loops

    What output does this loop produce? for i in range(6, 1, -2): print(i, end=" ")

    1. 6 5 4 3 2
    2. 2 4 6
    3. 6 4 2 Correct answer.
    4. 6 4 2 0

    Explanation

    range(6, 1, -2) starts at 6 and stops before 1, decreasing by 2 each time. The generated values are 6, 4, and 2, printed with spaces.

  47. Question 47Control Flow: Conditional Blocks and Loops

    What is printed by this code? x = 7 if x > 10: pass print("end")

    1. 7
    2. nothing
    3. end Correct answer.
    4. pass

    Explanation

    pass is a null statement: it satisfies Python's need for an indented block but performs no action. The condition 7 > 10 is false, so that block is skipped anyway, and print("end") runs because it is outside the if.

  48. Question 48Control Flow: Conditional Blocks and Loops

    What is printed by this code? n = 5 while n < 3: n += 1 else: print("else", n)

    1. nothing
    2. else 3
    3. else 8
    4. else 5 Correct answer.

    Explanation

    The while condition is checked before the first iteration; since 5 < 3 is false, the loop body never runs. A while loop's else block runs when the loop ends without a break, so it prints else 5 with n unchanged.

  49. Question 49Control Flow: Conditional Blocks and Loops

    What is printed by this code? i = 0 while i < 3: i += 1 if i == 2: break else: print("else") print(i)

    1. else 2
    2. 2 Correct answer.
    3. 3
    4. else 3

    Explanation

    The loop increments i to 1, then to 2 and breaks. break skips the loop's else block, and the final print outputs the current value 2.

  50. Question 50Control Flow: Conditional Blocks and Loops

    What output does this code produce? x = 10 if x > 5: print("A") if x > 8: print("B")

    1. only A
    2. A then B Correct answer.
    3. B then A
    4. only B

    Explanation

    These are two separate if statements, not an if/elif chain. For x = 10 both conditions are true, so A prints first and B prints second.

  51. Question 51Control Flow: Conditional Blocks and Loops

    What is printed by this code? x = 4 if 1 < x < 3: print("A") elif 2 <= x <= 4: print("B") else: print("C")

    1. A
    2. no output
    3. C
    4. B Correct answer.

    Explanation

    Python evaluates 1 < x < 3 as 1 < x and x < 3. With x = 4 the first chained comparison is false, so execution moves to elif, where 2 <= 4 <= 4 is true and B is printed.

  52. Question 52Control Flow: Conditional Blocks and Loops

    What is printed by this code? def check(): print("called") return True if False and check(): print("yes") else: print("no")

    1. called yes
    2. called no
    3. yes
    4. no Correct answer.

    Explanation

    The and operator short-circuits: if its left operand is false, the right operand is not evaluated at all. Therefore check() is never called, "called" is not printed, and the else branch prints no.

  53. Question 53Control Flow: Conditional Blocks and Loops

    What is printed by this code? for i in range(2): for j in range(2): if j == 1: break else: print("inner-else") else: print("outer-else")

    1. no output
    2. outer-else Correct answer.
    3. inner-else
    4. inner-else outer-else

    Explanation

    The inner break exits only the inner for loop, so the inner else is skipped on both outer iterations. The outer loop itself never encounters a break and finishes normally, which runs the outer else and prints outer-else.

  54. Question 54Control Flow: Conditional Blocks and Loops

    What is printed by this code? a = 0 b = 1 result = "A" if a else "B" if b else "C" print(result)

    1. C
    2. B Correct answer.
    3. A
    4. B C

    Explanation

    Conditional expressions associate from right to left, so the code groups as "A" if a else ("B" if b else "C"). Since a is 0 and therefore falsy, evaluation goes to the nested expression, where b is 1 and therefore truthy, producing B.

  55. Question 55Control Flow: Conditional Blocks and Loops

    What is printed by this code? score = 72 if score >= 90: grade = 'A' elif score >= 70: grade = 'B' elif score >= 60: grade = 'C' else: grade = 'D' print(grade)

    1. B Correct answer.
    2. A
    3. C
    4. D

    Explanation

    Python checks an if/elif/else chain from top to bottom and executes only the first block whose condition is true. Here 72 fails score >= 90, succeeds at score >= 70, so grade becomes B and later branches are skipped.

  56. Question 56Control Flow: Conditional Blocks and Loops

    What is printed by this code? count = 3 while count > 0: print(count, end=' ') count -= 1 print('done')

    1. 3 2 1 0 done
    2. 3 2 1 done Correct answer.
    3. done
    4. 0 1 2 3 done

    Explanation

    The while loop prints count and then decreases it by one as long as count is greater than zero. It prints 3, 2, and 1; when count becomes 0 the condition is false, and the final print outputs done.

  57. Question 57Control Flow: Conditional Blocks and Loops

    What is printed by this code? for n in range(3): if n == 1: pass print(n, end=' ')

    1. 0 1
    2. 0 2
    3. 0 1 2 3
    4. 0 1 2 Correct answer.

    Explanation

    pass is a no-op statement: it does not skip the rest of the loop body, break the loop, or print anything. Therefore the print call runs for every value produced by range(3), which are 0, 1, and 2.

  58. Question 58Control Flow: Conditional Blocks and Loops

    What is printed by this code? for value in [2, 4, 6]: if value % 2 != 0: break else: print('all even') print('done')

    1. all even
    2. all even / done Correct answer.
    3. all even / break
    4. done

    Explanation

    A for-else block runs its else suite only when the loop finishes without executing break. Every value in the list is even, so the break never runs; all even is printed, and the separate print then outputs done.

  59. Question 59Control Flow: Conditional Blocks and Loops

    What is printed by this code? total = 0 for i in range(1, 4): for j in range(1, 4): if i == j: continue total += i * j print(total)

    1. 18
    2. 24
    3. 12
    4. 22 Correct answer.

    Explanation

    The inner loop adds i * j for every pair except the diagonal pairs where i equals j, because continue skips only those iterations. The added products are 2, 3, 2, 6, 3, and 6, which sum to 22.

  60. Question 60Control Flow: Conditional Blocks and Loops

    What is printed by this code? temperature = 15 status = 'cold' if temperature < 10 else 'mild' if temperature < 20 else 'warm' print(status)

    1. None
    2. cold
    3. mild Correct answer.
    4. warm

    Explanation

    A nested conditional expression groups from the inside out: cold if temperature < 10, otherwise mild if temperature < 20, otherwise warm. Since 15 is not below 10 but is below 20, status becomes mild.

  61. Question 61Control Flow: Conditional Blocks and Loops

    What is printed by this code? def touch(): print('touch', end=' ') return False if touch() or True: print('body')

    1. touch body Correct answer.
    2. body
    3. touch False body
    4. touch

    Explanation

    The or operator evaluates its left operand first. touch() prints touch and returns False, so Python evaluates True, the condition succeeds, and the if body prints body.

  62. Question 62Control Flow: Conditional Blocks and Loops

    What is printed by this code? result = [] for k in range(3, 15, 4): result.append(k) print(result)

    1. [3, 6, 9, 12]
    2. [7, 11]
    3. [3, 7, 11] Correct answer.
    4. [3, 7, 11, 15]

    Explanation

    range(3, 15, 4) starts at 3, stops before 15, and steps by 4, producing 3, 7, and 11. The stop value 15 is never included, and the start value 3 is included because it is below the stop.

  63. Question 63Control Flow: Conditional Blocks and Loops

    What is printed by this code? a = 0 b = 5 if a and b / a: print('A') elif b > 3 or a: print('B') else: print('C')

    1. B Correct answer.
    2. C
    3. ZeroDivisionError
    4. A

    Explanation

    Python evaluates and/or left to right and short-circuits. Since a is 0, which is falsy, a and b / a stops before division and is false; then b > 3 is true, so the elif branch prints B.

  64. Question 64Control Flow: Conditional Blocks and Loops

    What is printed by this code? for i in range(2): for j in range(3): if i + j == 2: break else: print('inner else', end=' ') print('done')

    1. inner else inner else done
    2. inner else done
    3. done Correct answer.
    4. inner else

    Explanation

    A break exits only the nearest enclosing loop, so the else attached to the inner for is skipped whenever that inner loop breaks. Both outer iterations break the inner loop, so no inner else text is printed; after the outer loop finishes, done is printed.

  65. Question 65Control Flow: Conditional Blocks and Loops

    In a Python loop, what is the effect of executing a `continue` statement?

    1. It ends the entire loop immediately and skips the loop's `else` block.
    2. It restarts the loop from the first statement without re-evaluating the condition.
    3. It pauses the loop and resumes it only after the loop's `else` block runs.
    4. It skips the rest of the current iteration and goes to the next iteration. Correct answer.

    Explanation

    The `continue` statement ends the current iteration only. In a `for` loop, control moves to the next item; in a `while` loop, the condition is tested again before the next iteration. It does not terminate the loop, so a loop `else` can still run if no `break` occurs.

  66. Question 66Control Flow: Conditional Blocks and Loops

    What is printed by this code? for value in range(1, 4): print(value * 2, end="-")

    1. 2-4-6- Correct answer.
    2. 0-2-4-
    3. 2-4-6-8-
    4. 1-2-3-

    Explanation

    `range(1, 4)` yields 1, 2, and 3, stopping before 4. Multiplying each by 2 gives 2, 4, and 6, and `end="-"` appends a hyphen after each value. The printed result is therefore `2-4-6-`.

  67. Question 67Control Flow: Conditional Blocks and Loops

    Which statement correctly describes an `elif` clause in a Python `if` statement?

    1. It must be followed by an `else` clause.
    2. It is tested even when a preceding `if` condition is true.
    3. It can appear only after an `else` clause.
    4. It is tested only when all preceding conditions in the same chain are false. Correct answer.

    Explanation

    An `if`/`elif`/`else` chain checks conditions from top to bottom and stops at the first true condition. An `elif` is evaluated only when every earlier condition in that chain was false. Once a branch runs, later `elif` and `else` clauses are skipped.

  68. Question 68Control Flow: Conditional Blocks and Loops

    What is printed by this code? n = 0 while n < 5: n += 1 if n == 3: continue print(n, end=",")

    1. 0,1,2,4,5,
    2. 1,2,4,5, Correct answer.
    3. 1,2,4,5,6,
    4. 1,2,3,4,5,

    Explanation

    The loop increments `n` before testing it. When `n` becomes 3, `continue` skips the `print` for that iteration, but the loop condition is checked again. The values printed are 1, 2, 4, and 5, each followed by a comma.

  69. Question 69Control Flow: Conditional Blocks and Loops

    What is printed by this code? i = 1 while i <= 5: if i == 4: break i += 1 print(i)

    1. 4 Correct answer.
    2. 1
    3. 3
    4. 5

    Explanation

    The `while` condition remains true while `i` is at most 5. The loop increments `i` until it reaches 4, then the `if` condition is true and `break` exits the loop immediately. Because `break` occurs before the increment for that iteration, the final value printed is 4.

  70. Question 70Control Flow: Conditional Blocks and Loops

    What is printed by this code? for i in range(2, 5): pass print(i)

    1. 5
    2. 2
    3. 4 Correct answer.
    4. NameError

    Explanation

    In Python, a `for` loop variable is not scoped to the loop body. After `range(2, 5)` finishes, `i` retains the last value it received, which is 4. The `pass` statement does nothing, so the printed value is 4.

  71. Question 71Control Flow: Conditional Blocks and Loops

    What is printed by this code? x = 12 if x % 3 == 0 and x % 4 == 0: print("A") elif x % 3 == 0: print("B") else: print("C")

    1. B
    2. A Correct answer.
    3. No output
    4. C

    Explanation

    12 is divisible by both 3 and 4, so the compound condition in the `if` is true. The first matching branch prints `A`, and the `elif` is not evaluated. The `else` would run only if both conditions were false.

  72. Question 72Control Flow: Conditional Blocks and Loops

    When does the `else` suite attached to a `for` or `while` loop run?

    1. Only when the loop body never executes.
    2. Only when the loop contains a `continue` statement.
    3. Each time the loop condition becomes false, even if a `break` occurred.
    4. When the loop finishes normally, without a `break` ending it. Correct answer.

    Explanation

    A loop's `else` suite is tied to normal termination, not to the loop body running at least once. It runs when the loop finishes because its condition becomes false or its iterable is exhausted. A `break` skips the `else` suite.

  73. Question 73Control Flow: Conditional Blocks and Loops

    What is printed by this code? for a in range(3): if a == 1: continue for b in range(3): if b == 2: break print(a, b, end=";")

    1. 0 0;0 1;2 0;2 1; Correct answer.
    2. 0 0;0 1;1 0;1 1;2 0;2 1;
    3. 0 0;0 1;2 0;2 1;2 2;
    4. 0 0;1 0;2 0;

    Explanation

    When `a` is 1, `continue` skips the inner loop for that value of `a`. For `a` equal to 0 and 2, `b` takes values 0 and 1; when `b` reaches 2, `break` exits only the inner loop. The printed sequence is `0 0;0 1;2 0;2 1;`.

  74. Question 74Control Flow: Conditional Blocks and Loops

    What is printed by this code? count = 3 while count: count -= 1 if count == 1: continue print(count, end="-")

    1. 2-1-0-
    2. 3-2-0-
    3. 0-2-
    4. 2-0- Correct answer.

    Explanation

    The `while` condition uses the integer `count` directly, so it is true while `count` is nonzero. After the first decrement `count` is 2 and prints; after the second it is 1 and `continue` skips the print; after the third it is 0 and prints. The next condition test sees 0 and ends the loop, producing `2-0-`.

  75. Question 75Control Flow: Conditional Blocks and Loops

    Which output does this program produce? for ch in "abcd": if ch == "b": continue print(ch, end="")

    1. abd
    2. bcd
    3. abcd
    4. acd Correct answer.

    Explanation

    The `continue` statement ends the current iteration of the `for` loop before `print` runs, so the character `b` is skipped. Every other character in the string is printed with no separator, giving `acd`.

  76. Question 76Control Flow: Conditional Blocks and Loops

    What does this loop display? for i in range(1, 10, 3): print(i, end=",")

    1. 0,3,6,
    2. 1,4,7, Correct answer.
    3. 0,3,6,9,
    4. 1,4,7,10,

    Explanation

    `range(1, 10, 3)` starts at 1, stops before 10, and adds 3 each time, so the values are 1, 4, and 7. The trailing comma comes from `end=","` after every value, including the last.

  77. Question 77Control Flow: Conditional Blocks and Loops

    What is the output of this snippet? i = 0 while i < 3: i += 1 else: print("done", i)

    1. done 4
    2. done 2
    3. no output
    4. done 3 Correct answer.

    Explanation

    A `while` loop's `else` suite runs when the loop ends because its condition becomes false, which happens after `i` reaches 3. Since there is no `break`, `print` executes once with `i` equal to 3.

  78. Question 78Control Flow: Conditional Blocks and Loops

    What output does this nested loop produce? for i in range(2): for j in range(2): if j == 1: break print(i, j, end="|")

    1. 0 1|1 0|
    2. 0 0|0 1|1 0|1 1|
    3. 0 0|1 1|
    4. 0 0|1 0| Correct answer.

    Explanation

    The `break` exits only the inner `j` loop when `j` is 1, then the outer `i` loop continues. Thus the inner body prints only for `j == 0`, once for `i == 0` and once for `i == 1`, giving `0 0|1 0|`.

  79. Question 79Control Flow: Conditional Blocks and Loops

    What does this snippet print? for i in range(4): if i % 2 == 0: continue print(i, end=" ") else: print("end")

    1. 1 3
    2. 0 2 end
    3. 1 2 3 end
    4. 1 3 end Correct answer.

    Explanation

    `continue` skips the rest of the loop body for even values, so only 1 and 3 are printed by the `print` inside the loop. The loop ends normally without `break`, so its `else` suite also runs and prints `end`.

  80. Question 80Control Flow: Conditional Blocks and Loops

    Which lines does this program print? for i in range(3): for j in range(3): if i == j: continue if j > i: break print(i, j)

    1. 1 0 2 0 2 1 Correct answer.
    2. 1 0 1 1 2 1
    3. 0 0 2 0 2 1
    4. 1 0 2 0 2 2

    Explanation

    For each `i`, `continue` skips the diagonal pair, and `break` stops the inner loop once `j` exceeds `i`. The inner print therefore runs only for pairs below the diagonal: `1 0`, `2 0`, and `2 1`.

  81. Question 81Data Collections: Lists, Tuples, Sets, Dictionaries, and Strings

    Given `nums = [10, 20, 30, 40, 50]`, what does `nums[1:4]` evaluate to?

    1. [10, 20, 30, 40]
    2. [20, 30, 40, 50]
    3. [10, 20, 30]
    4. [20, 30, 40] Correct answer.

    Explanation

    A list slice uses the form start:stop, where the start index is included and the stop index is excluded. With nums[1:4] Python returns the elements at indices 1, 2 and 3, which are 20, 30 and 40. The value 50 at index 4 is not included because the stop bound is always exclusive.

  82. Question 82Data Collections: Lists, Tuples, Sets, Dictionaries, and Strings

    For the tuple `t = (1, 2, 3)`, which of these statements raises a TypeError?

    1. `t[0] = 9` Correct answer.
    2. `t[0]`
    3. `t + (4,)`
    4. `t.count(2)`

    Explanation

    Tuples are immutable sequences, so item assignment such as t[0] = 9 is rejected with a TypeError. Reading items, concatenating two tuples into a new one, and calling read-only methods like count or index are all permitted. To change a tuple you must build a new tuple and rebind the name to it.

  83. Question 83Data Collections: Lists, Tuples, Sets, Dictionaries, and Strings

    With `d = {'a': 1, 'b': 2}`, what does `d.get('c', 0)` return?

    1. It raises a KeyError
    2. 'c'
    3. None
    4. 0 Correct answer.

    Explanation

    dict.get(key, default) returns the value stored under the key, or the supplied default when the key is absent. Because 'c' is not present in d, the call returns 0 instead of raising an exception. This is the key difference from square-bracket access, which raises KeyError for a missing key.

  84. Question 84Data Collections: Lists, Tuples, Sets, Dictionaries, and Strings

    `values = [3, 1, 2]` and then `result = values.sort()`. What are `values` and `result` afterwards?

    1. values is [3, 1, 2] and result is None
    2. values is [3, 1, 2] and result is [1, 2, 3]
    3. values is [1, 2, 3] and result is None Correct answer.
    4. values is [1, 2, 3] and result is [1, 2, 3]

    Explanation

    list.sort() sorts the list in place and returns None, which is a frequent source of bugs when the call is assigned or chained. After the call, values itself is reordered to [1, 2, 3] while result holds the return value None. The built-in sorted(values) is the version that returns a new sorted list.

  85. Question 85Data Collections: Lists, Tuples, Sets, Dictionaries, and Strings

    After `a = {1, 2}` and `b = {2, 3}`, what is the value of `a | b`?

    1. {1, 3}
    2. {2}
    3. {1, 2, 2, 3}
    4. {1, 2, 3} Correct answer.

    Explanation

    The | operator on sets returns a new set containing every element that appears in either operand, with duplicates collapsed. Combining {1, 2} with {2, 3} therefore gives {1, 2, 3}. Use & for intersection, - for difference and ^ for symmetric difference.

  86. Question 86Data Collections: Lists, Tuples, Sets, Dictionaries, and Strings

    What does `'red,green,blue'.split(',')` return?

    1. ['red,green,blue']
    2. ('red', 'green', 'blue')
    3. ['red', 'green', 'blue'] Correct answer.
    4. 'red green blue'

    Explanation

    str.split(sep) cuts the string at every occurrence of the separator and returns the pieces as a list. Splitting 'red,green,blue' on commas yields three separate strings collected in a list. Because an explicit separator is given, no whitespace-based splitting behaviour applies either.

  87. Question 87Data Collections: Lists, Tuples, Sets, Dictionaries, and Strings

    `a = [1, 2, 3]`, then `b = a[:]`, then `b.append(4)`. What is `a` after this code runs?

    1. [1, 2, 3] Correct answer.
    2. [1, 2, 3, 4]
    3. [4, 1, 2, 3]
    4. It raises an IndexError

    Explanation

    Slicing a list with [:] creates a shallow copy, so a and b refer to two separate list objects. Appending to b only lengthens the copy and leaves a unchanged at [1, 2, 3]. Rebinding with b = a instead would make both names refer to the same object, so the append would be visible through a.

  88. Question 88Data Collections: Lists, Tuples, Sets, Dictionaries, and Strings

    Starting from `d = {}`, which of these assignments completes without raising an error?

    1. `d[(1, 2)] = 'x'` Correct answer.
    2. `d[{1, 2}] = 'x'`
    3. `d[{'a': 1}] = 'x'`
    4. `d[[1, 2]] = 'x'`

    Explanation

    Dictionary keys must be hashable, which in practice means immutable types such as numbers, strings, and tuples built from hashable items. A tuple holding two integers is therefore a valid key. Lists, sets, and dicts are mutable and unhashable, so using one as a key raises TypeError.

  89. Question 89Data Collections: Lists, Tuples, Sets, Dictionaries, and Strings

    What does `'abcdef'[::-2]` evaluate to?

    1. 'fedcba'
    2. 'ace'
    3. 'fdec'
    4. 'fdb' Correct answer.

    Explanation

    A negative step reverses the direction of the slice: the default start becomes the last character and the default stop lies before the first. With a step of -2, Python takes every second character backwards from 'f', landing on f, d, and b. The result is the string 'fdb'.

  90. Question 90Data Collections: Lists, Tuples, Sets, Dictionaries, and Strings

    Given `d = {'a': 1, 'b': 2}`, what does `print('a' in d, 1 in d)` display?

    1. False False
    2. True True
    3. True False Correct answer.
    4. False True

    Explanation

    The in operator applied to a dictionary tests keys, not values. Since 'a' is a key of d the first expression is True, while 1 exists only as a value, making the second expression False. To test values you would need a call such as 1 in d.values().

  91. Question 91Data Collections: Lists, Tuples, Sets, Dictionaries, and Strings

    What does `'banana'.count('na')` evaluate to?

    1. 0
    2. 2 Correct answer.
    3. 3
    4. 1

    Explanation

    The count method returns the number of non-overlapping occurrences of a substring. In `'banana'`, `'na'` starts at indices 2 and 4, so the count is 2. It does not count overlapping matches.

  92. Question 92Data Collections: Lists, Tuples, Sets, Dictionaries, and Strings

    After `nums = [10, 20, 30]` and `x = nums.pop()`, what are `x` and `nums`?

    1. x is 30 and nums is [10, 20] Correct answer.
    2. x is None and nums is [10, 20]
    3. x is 30 and nums is [10, 20, 30]
    4. x is 10 and nums is [20, 30]

    Explanation

    `list.pop()` with no argument removes and returns the last element. The original list is mutated, so `nums` becomes `[10, 20]` and `x` receives 30. Passing an index would remove a different position.

  93. Question 93Data Collections: Lists, Tuples, Sets, Dictionaries, and Strings

    What is the type of `t` after `t = (5)`?

    1. tuple
    2. int Correct answer.
    3. list
    4. set

    Explanation

    Parentheses around a single value only group an expression; they do not create a tuple. The comma is what makes a tuple, so `(5,)` is a tuple while `(5)` is an int. Here `t` is bound to the integer 5.

  94. Question 94Data Collections: Lists, Tuples, Sets, Dictionaries, and Strings

    After `lst = [1, 2, 3, 4]` and `lst[1:3] = [9]`, what is `lst`?

    1. [1, 9, 3, 4]
    2. [1, 9, 4] Correct answer.
    3. [9, 3, 4]
    4. [1, 2, 9, 4]

    Explanation

    Slice assignment replaces the target slice with the elements of the right-hand iterable. The slice `lst[1:3]` covers values 2 and 3, and it is replaced by the single value 9. The resulting list is `[1, 9, 4]`.

  95. Question 95Data Collections: Lists, Tuples, Sets, Dictionaries, and Strings

    What does `sorted((3, 1, 2))` return?

    1. [1, 2, 3] Correct answer.
    2. None
    3. the tuple (3, 1, 2)
    4. the tuple (1, 2, 3)

    Explanation

    `sorted()` accepts any iterable, including a tuple, and returns a new list of sorted elements. It does not mutate the original tuple. Therefore the result is `[1, 2, 3]`, not a tuple.

  96. Question 96Data Collections: Lists, Tuples, Sets, Dictionaries, and Strings

    Given `s = {1, 2}`, what happens when `s.discard(3)` is executed?

    1. s remains {1, 2} Correct answer.
    2. It raises KeyError
    3. It returns 3
    4. It adds 3 to s

    Explanation

    `set.discard(x)` removes `x` if it is present and does nothing if it is absent. It never raises an error for a missing element. Since 3 is not in `s`, the set remains `{1, 2}`.

  97. Question 97Data Collections: Lists, Tuples, Sets, Dictionaries, and Strings

    Given `d = {'a': 1}` and then `d.setdefault('a', 9)`, what is `d['a']`?

    1. 9
    2. KeyError
    3. None
    4. 1 Correct answer.

    Explanation

    `dict.setdefault(key, default)` returns the existing value when the key is already present. It only inserts the default when the key is missing. Because `'a'` already maps to 1, the call returns 1 and does not replace it with 9.

  98. Question 98Data Collections: Lists, Tuples, Sets, Dictionaries, and Strings

    After `a = [[1], [2]]`, `b = a[:]`, and `b[0].append(9)`, what is `a`?

    1. [[1], [2, 9]]
    2. [[1], [2]]
    3. [[9], [2]]
    4. [[1, 9], [2]] Correct answer.

    Explanation

    Slicing a list with `a[:]` creates a shallow copy: the outer list is new, but the inner list objects are shared. Appending to `b[0]` therefore mutates the same inner list that `a[0]` references. The result is `[[1, 9], [2]]`.

  99. Question 99Data Collections: Lists, Tuples, Sets, Dictionaries, and Strings

    What does `'abcdef'[4:1:-1]` evaluate to?

    1. 'dcb'
    2. 'edcb'
    3. 'edc' Correct answer.
    4. 'fed'

    Explanation

    In a slice with a negative step, the start index is 4 (`'e'`) and the stop index 1 is excluded while moving backward. The visited indices are 4, 3, and 2, producing `'edc'`. The stop index itself is not included.

  100. Question 100Data Collections: Lists, Tuples, Sets, Dictionaries, and Strings

    Given `d = {'a': 1, 'b': 2}`, what does `list(d)` return?

    1. [1, 2]
    2. [('a', 1), ('b', 2)]
    3. ['a', 'b'] Correct answer.
    4. ['a', 1, 'b', 2]

    Explanation

    Iterating over a dictionary yields its keys in insertion order. Passing the dictionary to `list()` therefore collects the keys into a list. To get values or pairs you would call `d.values()` or `d.items()`.

  101. Question 101Data Collections: Lists, Tuples, Sets, Dictionaries, and Strings

    What happens when the following code is executed? s = 'python' s[0] = 'P'

    1. A TypeError is raised; strings are immutable. Correct answer.
    2. s becomes 'Ppython' because the character is inserted.
    3. s becomes 'Python' and execution continues normally.
    4. A ValueError is raised because the index is out of range.

    Explanation

    Strings are immutable in Python, so assigning to a position such as s[0] is not allowed. The attempt raises TypeError rather than changing the value or inserting characters. To change the first character, build a new string, for example 'P' + s[1:].

  102. Question 102Data Collections: Lists, Tuples, Sets, Dictionaries, and Strings

    After this code runs, what is the value of a? a = [1, 2] a.extend([3, 4]) a.append([5])

    1. [1, 2, 3, 4, [5]] Correct answer.
    2. [1, 2, [3, 4, 5]]
    3. [1, 2, [3, 4], [5]]
    4. [1, 2, 3, 4, 5]

    Explanation

    extend adds each element of the iterable to the end of the list, so 3 and 4 become separate items. append adds its whole argument as one element, so the list [5] is nested. That produces [1, 2, 3, 4, [5]].

  103. Question 103Data Collections: Lists, Tuples, Sets, Dictionaries, and Strings

    What is the result of the expression `'-'.join(['a', 'b', 'c'])`?

    1. 'a-b-c-'
    2. 'a-b-c' Correct answer.
    3. 'abc'
    4. ['a-b-c']

    Explanation

    join is a string method that inserts the separator between items of an iterable of strings. The separator is '-', so the three items are connected as 'a-b-c'. join returns a single string, not a list.

  104. Question 104Data Collections: Lists, Tuples, Sets, Dictionaries, and Strings

    What happens when this code runs? d = {} d[[1, 2]] = 'x'

    1. A TypeError is raised because a list cannot be a dictionary key. Correct answer.
    2. d becomes {'[1, 2]': 'x'} because the list is converted to text.
    3. A KeyError is raised because [1, 2] is not yet in d.
    4. d becomes {[1, 2]: 'x'}.

    Explanation

    Dictionary keys must be hashable, and lists are mutable, so Python raises TypeError when a list is used as a key. Tuples containing only hashable items can be used as keys. Assigning a new key to an empty dictionary does not raise KeyError; the problem is the key type.

  105. Question 105Data Collections: Lists, Tuples, Sets, Dictionaries, and Strings

    After `a = {1, 2, 3}` and `b = {2, 3, 4}`, what is the value of `a ^ b`?

    1. {1, 4} Correct answer.
    2. {1, 2, 3, 4}
    3. {2, 3}
    4. {1}

    Explanation

    The ^ operator computes the symmetric difference: items that appear in exactly one of the two sets. The shared values 2 and 3 are removed, leaving 1 from a and 4 from b. The result is {1, 4}.

  106. Question 106Data Collections: Lists, Tuples, Sets, Dictionaries, and Strings

    What are `nums` and `result` after this code runs? nums = [1, 2, 1, 3] result = nums.remove(1)

    1. nums is [2, 1, 3] and result is None. Correct answer.
    2. nums is [1, 2, 3] and result is 1.
    3. nums is [2, 1, 3] and result is 1.
    4. nums is [1, 2, 1, 3] and result is None.

    Explanation

    list.remove deletes the first matching value and returns None. In [1, 2, 1, 3], the first 1 is removed, leaving [2, 1, 3]. Because the method's return value is None, result is None.

  107. Question 107Data Collections: Lists, Tuples, Sets, Dictionaries, and Strings

    Given `d = {'a': 1}`, what is the value of `d.pop('b', 0)` and what remains in `d`?

    1. The expression returns 0, and d remains {'a': 1}. Correct answer.
    2. The expression raises KeyError, and d remains unchanged.
    3. The expression returns 0, and d becomes {}.
    4. The expression returns None, and d becomes {'b': 0}.

    Explanation

    dict.pop removes the given key if it exists and returns its value. When the key is missing, the second argument is returned instead of raising KeyError. Since 'b' is absent and the default is 0, the call returns 0 and does not change d.

  108. Question 108Data Collections: Lists, Tuples, Sets, Dictionaries, and Strings

    What does this code display? s = 'banana' t = s.replace('a', 'o') print(s, t)

    1. banana banana
    2. bonana bonono
    3. banana bonono Correct answer.
    4. bonono bonono

    Explanation

    str.replace returns a new string with every occurrence of the substring replaced; it does not modify the original string. Therefore t becomes 'bonono' while s stays 'banana'. The print call shows both values separated by a space.

  109. Question 109Data Collections: Lists, Tuples, Sets, Dictionaries, and Strings

    What does this code display? d = {'a': 1} keys = d.keys() d['b'] = 2 print(list(keys))

    1. [1]; the view contains dictionary values
    2. ['b']; the view contains only the newest key
    3. ['a', 'b']; the view is dynamic Correct answer.
    4. ['a']; the view was captured before 'b' was added

    Explanation

    dict.keys returns a dynamic view object, not a frozen list. When 'b' is added to d, that view reflects the new key. Converting the view with list at print time gives ['a', 'b'] in insertion order.

  110. Question 110Data Collections: Lists, Tuples, Sets, Dictionaries, and Strings

    What is the value of `t` after this code runs? t = ([1, 2], 3) t[0].append(4)

    1. ([1, 2], 3); the tuple cannot be changed
    2. A TypeError; tuples cannot contain lists
    3. ([1, 2, 4], 3, 4); append extends the tuple
    4. ([1, 2, 4], 3); the inner list changed Correct answer.

    Explanation

    A tuple is immutable with respect to which objects it references, but it does not make those objects immutable. The first element is a list, and calling append on that list is allowed. Only the list changes, so t becomes ([1, 2, 4], 3).

  111. Question 111Data Collections: Lists, Tuples, Sets, Dictionaries, and Strings

    What does `len({1, 2, 2, 3})` evaluate to?

    1. 2
    2. 4
    3. 3 Correct answer.
    4. It raises a ValueError

    Explanation

    A set stores only unique elements, so the duplicate `2` is discarded when the literal is created. The resulting set is `{1, 2, 3}`, which has three elements.

  112. Question 112Data Collections: Lists, Tuples, Sets, Dictionaries, and Strings

    What is the value of `' exam '.strip()`?

    1. ' exam'
    2. 'exam '
    3. ' exam '
    4. 'exam' Correct answer.

    Explanation

    `str.strip()` removes whitespace from both ends of the string. It does not remove characters from the middle, and the original string is unchanged. The result is `'exam'`.

  113. Question 113Data Collections: Lists, Tuples, Sets, Dictionaries, and Strings

    After `nums = [1, 3]` and `nums.insert(1, 2)`, what is `nums`?

    1. [1, 3, 2]
    2. [1, 2, 3] Correct answer.
    3. [2, 1, 3]
    4. [1, 3]

    Explanation

    `list.insert(index, value)` places `value` before the element currently at `index`. Index `1` is the position of `3`, so `2` is inserted before it. The list becomes `[1, 2, 3]`.

  114. Question 114Data Collections: Lists, Tuples, Sets, Dictionaries, and Strings

    After `d = {'a': 1, 'b': 2}` and `d.update({'b': 9, 'c': 3})`, what is `d`?

    1. {'a': 1, 'b': 9}
    2. {'a': 1, 'b': 2, 'b': 9, 'c': 3}
    3. {'a': 1, 'b': 2, 'c': 3}
    4. {'a': 1, 'b': 9, 'c': 3} Correct answer.

    Explanation

    `dict.update()` adds new keys and overwrites the values of existing keys. The existing key `'b'` gets value `9`, and the new key `'c'` is added with value `3`. The key `'a'` is unchanged.

  115. Question 115Data Collections: Lists, Tuples, Sets, Dictionaries, and Strings

    What is the value of `'PCEP exam'.find('cert')`?

    1. 0
    2. It raises a ValueError
    3. 4
    4. -1 Correct answer.

    Explanation

    `str.find()` returns the starting index of the substring, or `-1` if the substring is absent. The substring `'cert'` does not occur in `'PCEP exam'`, so the result is `-1`. Unlike `index()`, `find()` does not raise an exception when the substring is missing.

  116. Question 116Data Collections: Lists, Tuples, Sets, Dictionaries, and Strings

    Given `s = {1, 2, 3, 4}` and `s.intersection_update({2, 4, 6})`, what is `s`?

    1. {1, 2, 3, 4, 6}
    2. {1, 3}
    3. {2, 4, 6}
    4. {2, 4} Correct answer.

    Explanation

    `intersection_update()` keeps only the elements that are present in both sets. The common elements of `{1, 2, 3, 4}` and `{2, 4, 6}` are `2` and `4`. The method updates `s` in place to `{2, 4}`.

  117. Question 117Data Collections: Lists, Tuples, Sets, Dictionaries, and Strings

    What does `[x * 2 for x in range(3)]` evaluate to?

    1. [2, 4]
    2. [0, 1, 2]
    3. [2, 4, 6]
    4. [0, 2, 4] Correct answer.

    Explanation

    `range(3)` produces `0`, `1`, and `2` in order. The list comprehension multiplies each value by 2 and collects the results. The resulting list is `[0, 2, 4]`.

  118. Question 118Data Collections: Lists, Tuples, Sets, Dictionaries, and Strings

    What is the result of `sorted(['bbb', 'a', 'cc'], key=len)`?

    1. ['a', 'cc', 'bbb'] Correct answer.
    2. ['a', 'bbb', 'cc']
    3. ['bbb', 'cc', 'a']
    4. ['cc', 'a', 'bbb']

    Explanation

    The `key=len` argument tells `sorted()` to compare string lengths rather than alphabetical order. The lengths are 1, 2, and 3, so the shortest string comes first. The sorted list is `['a', 'cc', 'bbb']`.

  119. Question 119Data Collections: Lists, Tuples, Sets, Dictionaries, and Strings

    What is the value of `d` after this code runs? d = {1: 'one', True: 'true', 1.0: 'float'}

    1. {1: 'true'}
    2. {1: 'one'}
    3. {1: 'one', True: 'true', 1.0: 'float'}
    4. {1: 'float'} Correct answer.

    Explanation

    In Python, `1`, `True`, and `1.0` compare equal and have the same hash, so they are treated as the same dictionary key. Each assignment updates the value for that one key rather than adding a separate entry. The last assignment gives the key the value `'float'`.

  120. Question 120Data Collections: Lists, Tuples, Sets, Dictionaries, and Strings

    What is the value of `d` after this code runs? d = {x % 2: x for x in range(4)}

    1. {0: 2, 1: 1}
    2. {0: 3, 1: 2}
    3. {0: 0, 1: 1}
    4. {0: 2, 1: 3} Correct answer.

    Explanation

    The comprehension iterates over `0`, `1`, `2`, and `3`. The keys are the remainders modulo 2, so the key `0` is assigned twice and the key `1` is assigned twice. Later assignments overwrite earlier ones, leaving `{0: 2, 1: 3}`.

  121. Question 121Data Collections: Lists, Tuples, Sets, Dictionaries, and Strings

    What is the value of the expression `'abcdef'[1:5:2]`?

    1. 'bdf'
    2. 'bcde'
    3. 'bcd'
    4. 'bd' Correct answer.

    Explanation

    A slice takes start, stop and step values, so this slice begins at index 1 and stops before index 5, moving forward two characters at a time. That selects only indices 1 and 3, which hold 'b' and 'd', so the result is 'bd'. Characters at indices 2 and 4 are skipped because of the step of 2.

  122. Question 122Data Collections: Lists, Tuples, Sets, Dictionaries, and Strings

    Which statement binds `t` to a tuple that contains exactly one element, the integer 1?

    1. t = (1)
    2. t = tuple(1)
    3. t = [1]
    4. t = (1,) Correct answer.

    Explanation

    A one-element tuple must be written with a trailing comma, because it is the comma rather than the parentheses that builds the tuple. Writing `(1)` just groups the integer 1 and binds `t` to an int, not a tuple. `tuple(1)` is invalid at runtime because integers are not iterable.

  123. Question 123Data Collections: Lists, Tuples, Sets, Dictionaries, and Strings

    Given `s = {1, 2, 3}`, which of these statements raises a `KeyError`?

    1. s.remove(4) Correct answer.
    2. 4 in s
    3. s.add(4)
    4. s.discard(4)

    Explanation

    `set.remove` demands that the element exists and raises KeyError when it is missing, and 4 is not in the set. `set.discard` performs the same removal attempt but fails silently instead. The membership test and `add` never raise for a missing value, since membership simply returns False and add inserts the element.

  124. Question 124Data Collections: Lists, Tuples, Sets, Dictionaries, and Strings

    What is the value of `parts` after this code runs? parts = 'a,b,c,d'.split(',', 2)

    1. ['a', 'b,c,d']
    2. ['a,b', 'c,d']
    3. ['a', 'b', 'c,d'] Correct answer.
    4. ['a', 'b', 'c', 'd']

    Explanation

    The second argument of `str.split` is the maximum number of splits, not the number of resulting pieces. Here only the first two commas are used as separators, so the remainder 'c,d' stays together as one final element. The result is therefore a three-element list: ['a', 'b', 'c,d'].

  125. Question 125Data Collections: Lists, Tuples, Sets, Dictionaries, and Strings

    What does this code display? d = {'a': 1, 'b': 2} print('a' in d, 1 in d)

    1. False True
    2. True False
    3. True True Correct answer.
    4. False False

    Explanation

    For a dictionary, the `in` operator inspects keys only and never looks at the stored values. Since 'a' is a key, the first expression is True, and because the integer 1 is only a value here it is not found among the keys, so the second expression is False. The output is therefore `True False`.

  126. Question 126Data Collections: Lists, Tuples, Sets, Dictionaries, and Strings

    What does this code display? s = {1, 2} t = s t.add(3) print(s, t)

    1. {1, 2} {1, 2}
    2. {1, 2, 3} {1, 2, 3} Correct answer.
    3. {1, 2} {1, 2, 3}
    4. {1, 2, 3} {1, 2}

    Explanation

    Assignment never copies a mutable collection; it only binds a second name to the same set object. Consequently `s` and `t` refer to one shared set, and `t.add(3)` is visible through both names. The output is `{1, 2, 3} {1, 2, 3}`, and a real copy would require `set(s)` or `s.copy()`.

  127. Question 127Data Collections: Lists, Tuples, Sets, Dictionaries, and Strings

    What does this code display? d = {'a': {'b': [10, 20, 30]}} print(d['a']['b'][-2])

    1. 10
    2. KeyError
    3. 30
    4. 20 Correct answer.

    Explanation

    Each subscript peels off one layer: `d['a']` yields the inner dict, `['b']` yields the list, and `[-2]` counts backwards from the end of that list. The second-to-last item of [10, 20, 30] is 20. No KeyError occurs because both 'a' and 'b' are valid keys.

  128. Question 128Data Collections: Lists, Tuples, Sets, Dictionaries, and Strings

    What does this code display? d = {'a': 1, 'b': 2, 'c': 3} r = {k: v * 2 for k, v in d.items() if v % 2 == 1} print(r)

    1. {'a': 2, 'b': 4, 'c': 6}
    2. {'b': 4}
    3. {'a': 1, 'c': 3}
    4. {'a': 2, 'c': 6} Correct answer.

    Explanation

    The comprehension iterates over key/value pairs and keeps only those whose value is odd, that is the 1 and the 3. The kept values are then doubled, so 'a' maps to 2 and 'c' to 6. Because 'b' has the even value 2, it is filtered out before the multiplication happens.

  129. Question 129Data Collections: Lists, Tuples, Sets, Dictionaries, and Strings

    What does this code display? a = [[1, 2], [3, 4]] b = list(a) b[0][0] = 9 print(a)

    1. [[1, 2], [3, 4]]
    2. [[9, 2], [9, 4]]
    3. [[1, 2], [3, 4], [9, 2]]
    4. [[9, 2], [3, 4]] Correct answer.

    Explanation

    `list(a)` builds a shallow copy: the outer list is new, but its slots still point at the very same inner lists. Assigning `b[0][0] = 9` therefore mutates the shared inner list, which is also reachable through `a`. Only the first inner list changes, so `a` becomes [[9, 2], [3, 4]]; the second inner list is untouched.

  130. Question 130Data Collections: Lists, Tuples, Sets, Dictionaries, and Strings

    What does this code display? data = [('b', 2), ('a', 3), ('b', 1)] print(sorted(data))

    1. [('a', 3), ('b', 2), ('b', 1)]
    2. [('b', 1), ('a', 3), ('b', 2)]
    3. [('b', 1), ('b', 2), ('a', 3)]
    4. [('a', 3), ('b', 1), ('b', 2)] Correct answer.

    Explanation

    Tuples are compared position by position, so the first elements decide the order and the second elements break ties. 'a' is smallest, and of the two 'b' tuples the one holding 1 comes before the one holding 2. The sorted list is therefore [('a', 3), ('b', 1), ('b', 2)].

  131. Question 131Data Collections: Lists, Tuples, Sets, Dictionaries, and Strings

    What does this code display? a = [1, 2, 3] x = a.pop(0) print(a, x)

    1. [2, 3] 1 Correct answer.
    2. [1, 2] 3
    3. [2, 3] 0
    4. [1, 2, 3] 1

    Explanation

    The method `pop(0)` removes the element at index 0 and returns that element. Here it removes 1 from the front of the list, so `a` becomes `[2, 3]` and `x` is `1`. The `print` call shows the list first, then the returned value.

  132. Question 132Data Collections: Lists, Tuples, Sets, Dictionaries, and Strings

    What is the value of the expression `'xyxzy'.strip('xy')`?

    1. 'xz'
    2. 'z' Correct answer.
    3. 'zy'
    4. ''

    Explanation

    `strip` with an argument treats the argument as a set of characters, not as a substring. It removes any of those characters from the left and right ends until it meets a character that is not in the set. Leading `x`, `y`, `x` and trailing `y` are removed, leaving only `z`; interior characters are never touched.

  133. Question 133Functions and Exceptions

    Which keyword is used to start the definition of a named function in Python?

    1. function
    2. def Correct answer.
    3. define
    4. func

    Explanation

    A named function definition starts with the def keyword, followed by the function name, a parameter list in parentheses, and a colon. Python does not use func, function, or define as keywords for defining functions, so those spellings would cause a SyntaxError at that position.

  134. Question 134Functions and Exceptions

    When a function parameter has a default value, where must that parameter appear in the parameter list?

    1. Only as the first parameter in the list
    2. At any position, because Python reorders parameters automatically
    3. Before every parameter without a default value
    4. After every parameter without a default value Correct answer.

    Explanation

    Parameters that have default values must come after all parameters that do not have defaults. This ordering lets Python bind required positional arguments first and then apply defaults without ambiguity.

  135. Question 135Functions and Exceptions

    What value is stored in result after this code runs? def f(): pass result = f()

    1. None Correct answer.
    2. False
    3. 0
    4. An empty string

    Explanation

    When a function finishes without executing a return statement, or executes a bare return, its call evaluates to None. The pass statement only acts as a placeholder and does not change that result.

  136. Question 136Functions and Exceptions

    What is printed by this code? def total(*nums): return sum(nums) print(total(1, 2, 3))

    1. A tuple (1, 2, 3)
    2. 6 Correct answer.
    3. TypeError: sum() accepts one argument
    4. A list [1, 2, 3]

    Explanation

    The *nums parameter collects positional arguments into a tuple, so nums is (1, 2, 3). Passing that tuple to sum returns 6, and print displays 6.

  137. Question 137Functions and Exceptions

    What does this code print? x = 10 def show(): x = 20 return x print(show(), x)

    1. 10 10
    2. 20 20
    3. 20 10 Correct answer.
    4. 10 20

    Explanation

    Assigning x inside show creates a local variable named x, and the return statement uses that local value 20. The global x remains 10, so the two printed values are 20 and 10.

  138. Question 138Functions and Exceptions

    Consider a try statement that includes except, else, and finally blocks. When the try block completes without raising an exception, which blocks execute?

    1. Only the else block
    2. The except block and the finally block
    3. The else block and the finally block Correct answer.
    4. Only the finally block

    Explanation

    The else block runs only if the try block finishes without an exception. The finally block always runs, so it also executes in this case, while except blocks are skipped.

  139. Question 139Functions and Exceptions

    What is printed? try: number = int('abc') except ValueError: print('value error') except Exception: print('general error')

    1. Nothing is printed
    2. general error
    3. value error then general error
    4. value error Correct answer.

    Explanation

    The call int('abc') raises ValueError. The first matching except clause handles it and prints 'value error'; after a handler runs, the remaining handlers are skipped.

  140. Question 140Functions and Exceptions

    An exception is raised inside a function and is not caught there. The caller also does not catch it. What happens when the exception reaches the top level of the program?

    1. Python terminates the program and prints a traceback Correct answer.
    2. Python restarts the function that raised the exception
    3. Python converts the exception into a warning and exits normally
    4. Python ignores the exception and continues with the next statement

    Explanation

    An exception that is not caught in the function propagates to its caller and continues outward. If no handler catches it before it leaves the top level, the interpreter terminates the program and prints a traceback.

  141. Question 141Functions and Exceptions

    What is printed by this code? def add(item, bucket=[]): bucket.append(item) return bucket print(add(1)) print(add(2))

    1. [1] [1, 2] Correct answer.
    2. TypeError on the second call
    3. [1] [2]
    4. [1] [1]

    Explanation

    Default argument values are evaluated once, when the def statement executes. The same list object is therefore reused on every call: the first call returns [1], and the second appends 2 to that same list, returning [1, 2].

  142. Question 142Functions and Exceptions

    What is printed by this code? def f(): try: return 1 finally: return 2 print(f())

    1. A SyntaxError is raised
    2. 1 then 2
    3. 2 Correct answer.
    4. 1

    Explanation

    A finally block executes before the function actually returns, even when the try block contains a return. A return statement inside finally replaces the earlier return value, so the function returns 2.

  143. Question 143Functions and Exceptions

    What is printed by this code? def double(n): return n * 2 result = double(5) + 1 print(result)

    1. 6
    2. 10
    3. 12
    4. 11 Correct answer.

    Explanation

    The function returns 10 for the argument 5, and the caller adds 1 to that returned value. The call expression is replaced by 10 before the addition, so the final printed value is 11.

  144. Question 144Functions and Exceptions

    What is printed by this code? def subtract(a, b): return a - b print(subtract(b=2, a=7))

    1. 14
    2. -5
    3. 9
    4. 5 Correct answer.

    Explanation

    Keyword arguments are matched to parameters by name, not by the order in which they appear in the call. Here a receives 7 and b receives 2, so the function returns 7 - 2, which is 5.

  145. Question 145Functions and Exceptions

    What is printed by this code? try: print(10 / 0) except ZeroDivisionError: print("cannot divide")

    1. 0
    2. nothing is printed
    3. cannot divide Correct answer.
    4. ZeroDivisionError

    Explanation

    Dividing an integer by zero raises ZeroDivisionError, so the expression inside try does not produce a printed number. The matching except block runs and prints its message instead.

  146. Question 146Functions and Exceptions

    What happens when this code runs? x = 5 def show(): print(x) x = 10 show()

    1. It prints 5 and then continues normally
    2. It prints nothing and exits
    3. It raises UnboundLocalError Correct answer.
    4. It prints 10 and leaves x global

    Explanation

    An assignment to x anywhere inside the function makes x a local name for the whole function. Because print(x) runs before that local name has been assigned, Python raises UnboundLocalError instead of reading the global x.

  147. Question 147Functions and Exceptions

    What is printed by this code? def count(**data): return len(data) print(count(name="Ana", age=30))

    1. A TypeError is raised
    2. 1
    3. 0
    4. 2 Correct answer.

    Explanation

    A parameter written with two asterisks collects all extra keyword arguments into a dictionary. The call supplies two keyword arguments, so data has two entries and len(data) returns 2.

  148. Question 148Functions and Exceptions

    What is printed by this code? def label(n): if n > 0: return "positive" return "not positive" print("after") print(label(0))

    1. It prints not positive Correct answer.
    2. It prints after
    3. It prints positive and then returns
    4. It prints None

    Explanation

    The condition n > 0 is false for 0, so the first return is skipped and the second return executes. A return statement ends the function immediately, so the later print call is never reached.

  149. Question 149Functions and Exceptions

    What is printed by this code? def greet(name, greeting="Hello"): return greeting + ", " + name print(greet("Ana"))

    1. Hello
    2. Hello, Ana Correct answer.
    3. A TypeError is raised
    4. Ana

    Explanation

    When the caller omits an argument for a parameter that has a default, Python uses the default value. Here name is "Ana" and greeting falls back to "Hello", producing "Hello, Ana".

  150. Question 150Functions and Exceptions

    What is printed by this code? try: raise ValueError("bad value") except ValueError as err: print(type(err).__name__)

    1. ValueError Correct answer.
    2. The message bad value
    3. err
    4. Exception

    Explanation

    The raise statement creates a ValueError object with the message "bad value", and the except clause binds that object to err. type(err).__name__ returns the name of the exception class, which is ValueError.

  151. Question 151Functions and Exceptions

    What is printed by this code? try: raise KeyError("missing") except LookupError: print("lookup") except KeyError: print("key")

    1. missing
    2. lookup Correct answer.
    3. KeyError
    4. key

    Explanation

    KeyError is a subclass of LookupError, and Python checks except clauses from top to bottom. The first handler that matches the raised exception is LookupError, so it runs and the later KeyError handler is skipped.

  152. Question 152Functions and Exceptions

    What is printed by this code? def f(): try: raise ValueError("x") finally: return "done" print(f())

    1. done Correct answer.
    2. ValueError is raised
    3. None
    4. x

    Explanation

    A return inside a finally block replaces any pending return value and also suppresses an exception that is propagating. The ValueError raised in try is therefore discarded, and f returns "done".

  153. Question 153Functions and Exceptions

    What is printed by this code? double = lambda n: n * 2 print(double(4))

    1. 4
    2. TypeError
    3. n * 2
    4. 8 Correct answer.

    Explanation

    A lambda expression creates an anonymous function whose body is the expression after the colon. Calling double(4) evaluates n * 2 with n bound to 4, so the function returns 8.

  154. Question 154Functions and Exceptions

    What is printed by this code? count = 1 def bump(): global count count = count + 1 bump() print(count)

    1. 2 Correct answer.
    2. UnboundLocalError
    3. 1
    4. NameError

    Explanation

    The global statement tells Python that count inside bump refers to the module-level variable. The function updates that same variable from 1 to 2, so print(count) shows 2.

  155. Question 155Functions and Exceptions

    What is printed by this code? def pair(): return 3, 5 a, b = pair() print(a + b)

    1. TypeError
    2. (3, 5)
    3. 8 Correct answer.
    4. 35

    Explanation

    Returning two comma-separated values creates a tuple, so pair() returns (3, 5). The assignment unpacks that tuple into a and b, and a + b adds the two integers to produce 8.

  156. Question 156Functions and Exceptions

    What is printed by this code? base = 10 def add_base(n, amount=base): return n + amount base = 100 print(add_base(5))

    1. 15 Correct answer.
    2. NameError
    3. 5
    4. 105

    Explanation

    Default argument values are evaluated once when the def statement executes, not when the function is called. The default amount is therefore locked to 10 at definition time, and add_base(5) returns 15 even though base is later rebound to 100.

  157. Question 157Functions and Exceptions

    What is printed by this code? def first_plus(a, *rest): return a + sum(rest) print(first_plus(2, 3, 4))

    1. 5
    2. 9 Correct answer.
    3. TypeError
    4. 24

    Explanation

    The parameter a captures the first positional argument, 2, while *rest collects the remaining arguments into the tuple (3, 4). sum(rest) is 7, so the function returns 2 + 7, which is 9.

  158. Question 158Functions and Exceptions

    What is printed by this code? try: raise TypeError("bad") except (ValueError, TypeError): print("handled") except Exception: print("other")

    1. nothing is printed
    2. other
    3. bad
    4. handled Correct answer.

    Explanation

    An except clause can list several exception classes in parentheses, and it matches if the raised exception is an instance of any listed class. TypeError is included in the first tuple, so the first handler runs and prints handled.

  159. Question 159Functions and Exceptions

    What is printed by this code? def change(items): items.append(9) items = [0] return items data = [1] result = change(data) print(data, result)

    1. [0] [0]
    2. [1] [0]
    3. [1, 9] [0] Correct answer.
    4. [1, 9] [1, 9]

    Explanation

    The parameter items initially refers to the same list object as data, so append(9) mutates that shared list to [1, 9]. The later assignment items = [0] only rebinds the local parameter name; it does not change data, which remains [1, 9] while result is [0].

  160. Question 160Functions and Exceptions

    What is printed by this code? def run(): try: raise KeyError("x") finally: print("cleanup") try: run() except KeyError: print("caught")

    1. caught only
    2. caught then cleanup
    3. cleanup only
    4. cleanup then caught Correct answer.

    Explanation

    The finally block executes while the exception is unwinding, before control leaves run, so cleanup is printed first. The KeyError then propagates to the caller and is caught by the outer except block, which prints caught.

  161. Question 161Functions and Exceptions

    What is printed by this code? try: raise SystemExit(1) except Exception: print("Exception") except BaseException: print("BaseException")

    1. TypeError
    2. Exception
    3. no output and the process exits with code 1
    4. BaseException Correct answer.

    Explanation

    SystemExit inherits from BaseException but not from Exception, so the first except clause does not catch it. The second clause catches BaseException and prints BaseException.

  162. Question 162Functions and Exceptions

    What is printed by this code? def check(value): try: if value < 0: raise ValueError("negative") return "ok" except ValueError: raise try: check(-1) except ValueError as err: print(err)

    1. None
    2. TypeError
    3. ok
    4. negative Correct answer.

    Explanation

    Inside the except block, a bare raise re-raises the exception currently being handled, so the ValueError with message negative propagates to the outer try. The outer handler catches it and prints the exception message, negative.

  163. Question 163Functions and Exceptions

    In Python, what value is returned by a function that finishes executing without a return statement?

    1. False
    2. 0
    3. None Correct answer.
    4. an empty string

    Explanation

    A Python function always returns a value. If execution reaches the end of the function body without a return statement, or if a bare return is used, the returned value is None. None is a distinct singleton object and is not the same as False, 0, or an empty string.

  164. Question 164Functions and Exceptions

    What is printed by this code? def total(*nums): return sum(nums) print(total(2, 4, 6))

    1. TypeError
    2. 12 Correct answer.
    3. 246
    4. 6

    Explanation

    The parameter *nums collects all extra positional arguments into a tuple, so nums becomes (2, 4, 6). The built-in sum function adds the tuple elements and returns 12. A single * parameter can accept any number of positional arguments, including none.

  165. Question 165Functions and Exceptions

    Which built-in exception is raised when the call int('12x') is executed?

    1. ValueError Correct answer.
    2. SyntaxError
    3. TypeError
    4. NameError

    Explanation

    The int() constructor raises ValueError when a string has the right type but an invalid literal form, such as '12x'. TypeError is reserved for a wrong type, NameError for an undefined name, and SyntaxError for malformed source code.

  166. Question 166Functions and Exceptions

    What is printed by this code? def add_item(item, basket=[]): basket.append(item) return basket print(add_item('a')) print(add_item('b'))

    1. ['a'] then ['a', 'b'] Correct answer.
    2. ['a', 'b'] then ['a', 'b']
    3. ['a'] then ['b']
    4. ['b'] then ['a']

    Explanation

    Default argument values are evaluated once when the def statement runs, so the same list object is reused on every call. The first call appends 'a' and returns ['a']; the second call appends 'b' to that same list and returns ['a', 'b']. A fresh default is not created for each call.

  167. Question 167Functions and Exceptions

    What is printed by this code? def parse(text): try: value = int(text) except ValueError: return 'invalid' else: return value * 2 print(parse('7')) print(parse('x'))

    1. 14 then invalid Correct answer.
    2. 14 then 0
    3. invalid then 14
    4. invalid and invalid

    Explanation

    The else block of a try statement runs only when the try block finishes without raising an exception. For '7', int() succeeds, so the else block returns 14; for 'x', int() raises ValueError, so the except block returns 'invalid'. The else block is skipped whenever the except block handles an error.

  168. Question 168Functions and Exceptions

    What happens when this code runs? def area(width, height): return width * height print(area(3))

    1. It prints 0 because height is missing.
    2. It raises TypeError because height is required. Correct answer.
    3. It prints 3.
    4. It raises NameError because height is undefined.

    Explanation

    Every parameter without a default value must receive an argument when the function is called. The call area(3) supplies width but omits height, so Python raises TypeError before the function body can execute. Missing arguments are not silently replaced with 0 or None.

  169. Question 169Functions and Exceptions

    What is printed by this code? def combine(a, b, c): return a + b + c values = [1, 2] extra = {'c': 3} print(combine(*values, **extra))

    1. 123
    2. 6 Correct answer.
    3. TypeError
    4. 3

    Explanation

    The *values syntax unpacks the list [1, 2] into positional arguments a and b. The **extra syntax unpacks the dictionary {'c': 3} into the keyword argument c. The function then adds 1 + 2 + 3 and returns 6.

  170. Question 170Functions and Exceptions

    What is printed by this code? def outer(): count = 0 def inner(): nonlocal count count += 1 return count return inner() + inner() print(outer())

    1. 3 Correct answer.
    2. 2
    3. UnboundLocalError
    4. 1

    Explanation

    The nonlocal declaration lets inner rebind count in the enclosing outer scope instead of creating a local variable. The first inner() call increments count to 1 and returns 1; the second increments it to 2 and returns 2. The final addition is 1 + 2, which is 3.

  171. Question 171Functions and Exceptions

    What is printed by this code? class AppError(Exception): pass class InputError(AppError): pass try: raise InputError('bad input') except AppError: print('app') except InputError: print('input')

    1. Nothing
    2. AppError: bad input
    3. app Correct answer.
    4. input

    Explanation

    Python checks except clauses from top to bottom and runs the first handler whose exception class matches. Because InputError is a subclass of AppError, the except AppError clause matches first and prints 'app'. The later except InputError clause is never reached, even though it is more specific.

  172. Question 172Functions and Exceptions

    What is printed by this code? try: raise ValueError('missing value') except ValueError as err: print(str(err))

    1. err
    2. ValueError
    3. missing value Correct answer.
    4. ValueError: missing value

    Explanation

    The as err clause binds the caught exception instance to the name err. Calling str(err) returns only the exception message, which is 'missing value'. The class name and repr formatting are not included by str().

  173. Question 173File Handling and Module Imports

    In Python, which open() mode opens an existing text file for reading only and places the file pointer at the beginning of the file?

    1. a
    2. x
    3. w
    4. r Correct answer.

    Explanation

    The mode 'r' opens a file for reading only. It is the default mode for open() and positions the pointer at the start. If the file does not exist, this mode raises FileNotFoundError.

  174. Question 174File Handling and Module Imports

    When a file is opened with a with statement, what happens when the block finishes or an exception is raised inside it?

    1. The file is reopened in binary mode for safety.
    2. The file stays open until the Python interpreter exits.
    3. The file is closed automatically when the block ends. Correct answer.
    4. The file contents are printed to standard output.

    Explanation

    A with statement uses the file object as a context manager, and its exit method closes the file when the block ends. This cleanup happens during normal completion and also when an exception propagates out of the block. Therefore a separate close() call is not required.

  175. Question 175File Handling and Module Imports

    Which import statement brings only the sqrt function from the math module into the current namespace?

    1. from math import sqrt Correct answer.
    2. import math.sqrt
    3. import sqrt from math
    4. from math.sqrt import *

    Explanation

    The form 'from module import name' imports the named object directly into the current namespace. After 'from math import sqrt', the function can be called as sqrt() without the math prefix. The other forms are invalid Python import syntax or import the wrong object.

  176. Question 176File Handling and Module Imports

    A text file contains exactly two lines, written as 'alpha\n' and 'beta\n'. After f = open('data.txt') and lines = f.readlines(), what does lines contain?

    1. ('alpha\n', 'beta\n')
    2. 'alpha\nbeta\n'
    3. ['alpha', 'beta']
    4. ['alpha\n', 'beta\n'] Correct answer.

    Explanation

    readlines() reads all lines and returns a list of strings, keeping the newline character at the end of each line. Thus the result is a list with two string elements. It is not a tuple and not a single concatenated string.

  177. Question 177File Handling and Module Imports

    A file named data.txt currently contains the text old. The code f = open('data.txt', 'w'); f.write('new'); f.close() is executed. What is the content of data.txt afterward?

    1. newold
    2. oldnew
    3. new Correct answer.
    4. old

    Explanation

    Mode 'w' opens a file for writing and truncates it to zero length if it already exists. The subsequent write replaces the previous content, so only new remains. Use mode 'a' to append instead.

  178. Question 178File Handling and Module Imports

    After executing 'import statistics as stats', which name is bound in the current namespace for accessing the module?

    1. both statistics and stats
    2. stats only Correct answer.
    3. neither; the module must be accessed as statistics.stats
    4. statistics only

    Explanation

    The as clause in an import statement binds the module to the alias instead of its original name. Only stats is added to the namespace. The name statistics is not bound unless it is imported separately.

  179. Question 179File Handling and Module Imports

    A file named helper.py contains only the statement print(__name__) at module level. Another script executes import helper. What is printed?

    1. helper Correct answer.
    2. helper.py
    3. __main__
    4. None

    Explanation

    When a module is imported, Python sets its __name__ attribute to the module name without the .py extension. The value '__main__' is used only for the script that starts the program. Imported modules therefore see their own module name.

  180. Question 180File Handling and Module Imports

    For a file object f opened in read mode, what does f.seek(0) do?

    1. Moves the file pointer to offset zero Correct answer.
    2. Returns the first line as a string
    3. Closes and then immediately reopens the file
    4. Deletes the first byte of the file

    Explanation

    seek() changes the position of the file pointer. Passing 0 moves it to offset zero, the start of the file, so the next read begins at the first byte. It does not return file content or alter the stored data.

  181. Question 181File Handling and Module Imports

    Which statement correctly describes sys.path during a typical Python import?

    1. It contains only the current working directory and cannot be changed.
    2. It is an ordered list of directories searched for modules. Correct answer.
    3. It is a dictionary mapping module names to their source code.
    4. It stores the bytecode of every module already imported.

    Explanation

    sys.path is initialized from the script directory, PYTHONPATH entries, and installation defaults. Python checks its entries in order when resolving an import. Because it is a normal list, programs can append or remove entries at runtime.

  182. Question 182File Handling and Module Imports

    What is displayed by the following code? f = open('data.txt', 'w+'); f.write('abc'); print(repr(f.read())); f.close()

    1. '' Correct answer.
    2. raises an io.UnsupportedOperation
    3. 'abc'
    4. None

    Explanation

    In mode 'w+', the file is opened for both writing and reading, but after write('abc') the file pointer is at the end of the data. Reading from that position returns an empty string. Calling seek(0) before read would return 'abc'.

  183. Question 183File Handling and Module Imports

    An existing text file log.txt contains one line. A program executes f = open('log.txt', 'a') and then writes two new lines before closing the file. How does mode 'a' affect the file content?

    1. The existing line is erased before the first new write.
    2. The existing line is kept and the new text is added after it. Correct answer.
    3. The file is opened read-only, so writes raise an error.
    4. The new text is inserted at the start of the file.

    Explanation

    Mode 'a' opens the file for appending. If the file already exists, its current contents remain, and every write is placed at the end; if it does not exist, Python creates it.

  184. Question 184File Handling and Module Imports

    For a text file opened as f, which statement describes the result of f.readlines()?

    1. It returns a list of remaining lines, with newline characters kept. Correct answer.
    2. It returns an iterator that yields one character at a time from the file.
    3. It returns a tuple of words created by splitting the remaining text on whitespace.
    4. It returns a single string that contains all remaining characters in the file.

    Explanation

    readlines() reads all remaining lines and returns them as a list. Each list element is a string that includes its trailing newline when the source line has one.

  185. Question 185File Handling and Module Imports

    A file is opened with f = open('photo.bin', 'rb'). What type of object does f.read() return?

    1. A list of integers.
    2. A string decoded with UTF-8.
    3. A file path string.
    4. A bytes object. Correct answer.

    Explanation

    The 'b' in 'rb' selects binary mode, so Python does not decode the data. read() therefore returns a bytes object rather than a str.

  186. Question 186File Handling and Module Imports

    Consider the code f = open('data.txt', 'r'); f.close(); f.read(). What happens when f.read() is called?

    1. It automatically reopens data.txt and then reads the entire file.
    2. It returns an empty string because the data has already been read.
    3. It raises a ValueError because the file is closed. Correct answer.
    4. It returns None to show that no data is available.

    Explanation

    Closing a file object invalidates it for further I/O. Calling read() on the closed object raises ValueError with a message about an I/O operation on a closed file; it does not reopen the file.

  187. Question 187File Handling and Module Imports

    A text file contains the characters abcdefgh. After f = open('data.txt', 'r'), the call f.read(4) returns which value?

    1. ['abcd']
    2. 'abcdefgh'
    3. 'abcd' Correct answer.
    4. 4

    Explanation

    The argument to read(n) is a character count in text mode, not a byte count or line count. It reads at most four characters from the current position, so 'abcd' is returned.

  188. Question 188File Handling and Module Imports

    For a text-mode file object f, what does the expression f.write('hello') return if the write succeeds?

    1. None
    2. The file object f
    3. 5 Correct answer.
    4. True

    Explanation

    In Python 3, write() returns an integer: the number of characters written to a text stream. It does not return None, True, or the file object.

  189. Question 189File Handling and Module Imports

    Two separate runs of a program both call random.seed(7) before calling random.randint(1, 100) once. What is the expected result?

    1. The second call raises an error because the seed is already set.
    2. The call always returns 7.
    3. The two runs produce the same number. Correct answer.
    4. The two runs produce different numbers because random is unpredictable.

    Explanation

    random.seed() initializes the pseudorandom generator. With the same seed and the same sequence of calls, the generated values repeat, so both runs produce the same integer.

  190. Question 190File Handling and Module Imports

    What is the value of math.floor(-2.1)?

    1. -3 Correct answer.
    2. -2.0
    3. -2
    4. 2

    Explanation

    math.floor(x) returns the largest integer less than or equal to x. For -2.1 that value is -3, not -2, because -3 is the next lower integer.

  191. Question 191File Handling and Module Imports

    Which statement correctly describes opening an existing file with mode 'r+'?

    1. The file is created when missing, and any existing content is erased before writing.
    2. The file must exist and opens for reading and writing without truncation. Correct answer.
    3. The file opens for writing only, and the file pointer starts at the end of the file.
    4. The file opens in binary mode, so every read call returns a bytes object.

    Explanation

    Mode 'r+' requires the file to already exist and opens it for both reading and writing. It does not truncate the file and does not force binary mode.

  192. Question 192File Handling and Module Imports

    After the single statement from math import sqrt, a program calls print(math.sqrt(16)). What is the outcome?

    1. It prints 4.0 because importing sqrt also imports the math module automatically.
    2. It raises NameError because the name math is not bound. Correct answer.
    3. It raises ImportError because sqrt was imported instead of the whole math module.
    4. It prints 16 because sqrt is applied to the module object rather than a number.

    Explanation

    A from-import binds only the requested name, here sqrt. It does not bind the module name math, so math.sqrt(16) raises NameError unless import math is also executed.

  193. Question 193File Handling and Module Imports

    A program executes open('report.txt', 'x') while a file named report.txt already exists in the current directory. What is the outcome?

    1. The existing file is opened for appending without truncation.
    2. The existing file is deleted and replaced by a new empty file.
    3. FileExistsError is raised; the existing file is unchanged. Correct answer.
    4. The existing file is truncated and then opened for writing.

    Explanation

    Mode 'x' requests exclusive creation: it succeeds only when the path does not already exist. If the file exists, Python raises FileExistsError instead of opening or modifying it. The existing file is therefore left untouched.

  194. Question 194File Handling and Module Imports

    For an open text file object f, what does the method f.tell() return?

    1. The entire remaining contents of the file as one string.
    2. The total number of lines in the file.
    3. An integer giving the current position in the file. Correct answer.
    4. The next complete line, including its newline character.

    Explanation

    f.tell() reports the file object's current position, which is an integer offset used by seek(). It does not read data or count lines; reading methods such as read(), readline(), and readlines() return file content.

  195. Question 195File Handling and Module Imports

    A file object f is opened in text write mode. The statement f.writelines(['one', 'two']) is executed on an empty file. What does the file contain afterward, assuming no other writes occur?

    1. A TypeError is raised because writelines accepts only strings.
    2. 'onetwo' Correct answer.
    3. 'one\ntwo\n'
    4. ['one', 'two']

    Explanation

    writelines() writes each item from the iterable in sequence, but it does not insert separators between items. Because the strings themselves contain no newline characters, the file receives exactly 'onetwo'. To get separate lines, the caller must include newline characters in the strings.

  196. Question 196File Handling and Module Imports

    A program has written data to an open text file object f and then calls f.flush(). Which statement describes the guaranteed effect of f.flush()?

    1. Unwritten data is discarded from the buffer without being saved.
    2. The file pointer is reset to the beginning of the file.
    3. Buffered data is passed to the OS; the file stays open. Correct answer.
    4. The file is closed and can no longer be written to.

    Explanation

    flush() forces any buffered output to be handed to the operating system, which is useful when another process needs to see the data. It does not close the file object, so further writes are allowed. Closing the file also flushes buffers, but flush() alone does not release the file.

  197. Question 197File Handling and Module Imports

    A module named config.py contains the top-level statement print('config loaded') and has no __name__ guard. A script executes the two separate statements import config and import config again. How many times is 'config loaded' printed?

    1. A SyntaxError occurs on the second import statement.
    2. Exactly twice, because each import statement runs the module code.
    3. Zero times, because print is not allowed at module level.
    4. Exactly once, because the module is cached after the first import. Correct answer.

    Explanation

    On the first import, Python loads config.py and stores the resulting module object in sys.modules. Later import statements with the same name find that cached object and do not re-execute the module body. Therefore the top-level print runs only once.

  198. Question 198File Handling and Module Imports

    A text file is opened with f = open('data.txt', 'r'). Which method call reads exactly one line from the current position and returns it as a string, including the trailing newline if present?

    1. f.read(0)
    2. f.read()
    3. f.readline() Correct answer.
    4. f.readlines()

    Explanation

    readline() reads from the current position up to and including the next newline, or to the end of the file if no newline remains. It returns a single string; an empty string means end of file. read() consumes the whole remainder, readlines() returns a list of all remaining lines, and read(0) reads no characters.

  199. Question 199File Handling and Module Imports

    A text file contains exactly three lines: 'a\n', 'b\n', and 'c\n'. The code is: f = open('data.txt', 'r'); first = f.readline(); rest = list(f); f.close(). What are the values of first and rest?

    1. first is ''; rest is ['a\n', 'b\n', 'c\n']
    2. first is 'a'; rest is ['b', 'c']
    3. first is 'a\n'; rest is ['a\n', 'b\n', 'c\n']
    4. first is 'a\n'; rest is ['b\n', 'c\n'] Correct answer.

    Explanation

    readline() advances the file position past the first line and returns that line with its newline. Iterating over a file object resumes at the current position, so list(f) collects only the lines that have not yet been consumed: 'b\n' and 'c\n'. The newline characters are retained by both readline() and file iteration.

  200. Question 200File Handling and Module Imports

    A package directory named pkg contains an __init__.py file and a module file named mod.py. After a script executes import pkg.mod, which name is bound in the script's namespace?

    1. pkg Correct answer.
    2. Both pkg and mod are bound as separate names.
    3. pkg.mod
    4. mod

    Explanation

    The statement import pkg.mod loads the package and its submodule, but it binds only the top-level package name pkg in the importing namespace. The submodule is then reachable as pkg.mod. To bind mod directly, the script would need from pkg import mod.

PCEP flashcards

32 cards. Read the term and the definition here. The deck at the top of this page is optional.

Return type of input()
input() always returns a string, even when the user types digits. Convert with int() or float() before arithmetic, otherwise + concatenates text and comparisons behave as string comparisons.
Floor division operator
The // operator divides and rounds the result down to the nearest integer, returning a float if either operand is a float. For example, 7 // 2 is 3 and -7 // 2 is -4.
None value
None is a singleton of type NoneType representing the absence of a value. Functions without a return statement produce None, and the correct test is 'x is None', not equality.
print() sep and end
The sep keyword sets the string inserted between printed arguments and defaults to one space. The end keyword sets what follows the last argument and defaults to a newline.
Integer literal prefixes
The prefix 0b marks a binary literal, 0o an octal literal and 0x a hexadecimal literal. Underscores may separate digits for readability, as in 1_000_000.
Python identifier rules
An identifier may contain letters, digits and underscores but cannot begin with a digit. Identifiers are case-sensitive, and keywords such as class, for or None cannot be used as names.
Exponentiation associativity
The ** operator is right-associative, so 2 ** 3 ** 2 is evaluated as 2 ** (3 ** 2) and gives 512. It also binds tighter than unary minus, so -2 ** 2 equals -4.
Loop else clause
The optional else block of a for or while loop runs after the loop finishes normally, but is skipped entirely if the loop exits early through a break statement.
range() stop value
range(start, stop, step) generates integers from start up to but never including stop. A negative step counts downward, and a step of zero raises ValueError.
Falsy values in Python
Zero of any numeric type, empty strings, empty lists, tuples, dictionaries and sets, None and False all evaluate as false in a conditional. Every other object is truthy.
break versus continue
break terminates the innermost enclosing loop immediately and skips its else block. continue skips the remaining statements of the current iteration and moves to the next one.
Chained comparisons
An expression such as 0 <= x < 10 is evaluated as 0 <= x and x < 10, with the middle operand evaluated only once. Chains may combine any of the comparison operators.
Conditional expression syntax
The form A if condition else B evaluates condition first, then yields A when it is true and B when it is false. It is an expression, so it must produce a value.
Single-element tuple syntax
A one-item tuple requires a trailing comma, written as (1,) or 1,. Without that comma, (1) is simply an integer wrapped in parentheses and not a tuple at all.
dict get() method
d.get(key, default) returns the value stored for key, or default when the key is absent; default is None if omitted. Unlike d[key], it never raises KeyError.
Empty set creation
The literal {} creates an empty dictionary, not an empty set. Use set() to build an empty set; braces containing elements, such as {1, 2}, do create a set.
Slice expression
sequence[start:stop:step] returns a new sequence from start up to but excluding stop. Negative indices count from the end, and omitted bounds default to the sequence ends.
append versus extend
append(x) adds the single object x as one new element, while extend(iterable) adds each item of that iterable individually, increasing the list length by the number of items.
String immutability
Strings cannot be modified in place: methods such as upper(), replace() and strip() return new strings. Assigning to an index, as in s[0] = 'x', raises TypeError.
Set operators
The operator | gives union, & intersection, - difference and ^ symmetric difference, and all require sets on both sides. The named methods like union() accept any iterable instead.
Mutable default argument
Default parameter values are evaluated once, when the def statement runs. A mutable default such as a list is therefore shared across calls, so appended items accumulate unexpectedly.
LEGB name resolution
Python looks a name up in local, then enclosing function, then global, then built-in scope. Assignment inside a function creates a local name unless global or nonlocal is declared.
finally block purpose
A finally block always executes, whether the try block completed normally, raised an exception, or executed a return statement. It is used for cleanup such as closing files.
try else block
The else clause of a try statement runs only when the try block raised no exception, and it runs before finally. Exceptions raised inside else are not caught by that try's handlers.
lambda expression
lambda parameters: expression creates an anonymous function whose body is a single expression whose value is returned. It cannot contain statements such as assignments or return.
IndexError versus KeyError
IndexError is raised when a sequence index falls outside the valid range, while KeyError is raised when a dictionary is indexed with a key that is not present in it.
File mode w
Opening a file with mode 'w' truncates it to zero length if it already exists and creates it otherwise. Writing begins at the start, so previous contents are lost.
with statement for files
The with statement relies on a context manager to close the file automatically, even when an exception is raised inside the block, replacing a manual try/finally close.
readline() behaviour
readline() reads one line from the file and returns it including the trailing newline character, or returns an empty string once the end of the file has been reached.
Append mode a
Mode 'a' opens the file for writing at the end, creating it if it is missing and never truncating existing content. Mode 'a+' additionally permits reading from the file.
Module caching on import
An import statement executes a module's top-level code only the first time. Later imports reuse the cached module object that Python stores in sys.modules.
random.randint bounds
random.randint(a, b) returns a random integer n satisfying a <= n <= b, so both endpoints are included. It is equivalent to randrange(a, b + 1).

PCEP study guide

Computer Programming and Python Fundamentals

What this domain covers

PCEP's first domain checks whether you can read and write short Python snippets built from literals, variables, operators and built-in I/O. Questions are usually single-line expressions where precedence, type or a subtle naming rule decides the answer.

Core rules

  • Identifiers are case-sensitive, may contain letters, digits and underscores, but cannot begin with a digit. Keywords such as class, def and None are reserved. myVar, _x2 and 总量 are legal; 2x and my-var are not.
  • Literals include integers (0, 1_000), floats (2.0, 1e3), strings, booleans (True, False) and None.
  • Operators: + - * / // % **. / always returns a float; // floors toward negative infinity, so -7 // 2 == -4; % follows the sign of the divisor, so -7 % 2 == 1; ** binds tighter than unary minus, so -2 ** 2 == -4.
  • Precedence roughly: **, unary, * / // %, + -, comparisons, not, and, or. Parentheses override it.
  • input() always returns a str; convert with int() or float() before arithmetic. print(a, b, sep=",", end="") controls separators and line endings.

Worked example

x = input() and the user types 3; then y = 2; print(x * y) outputs 33, not 6. x is the string "3", and str * int repeats the string. Fix it with x = int(input()).

Traps

  • = assigns, == compares; using = in an if is a SyntaxError.
  • 1 + 2.0 yields 3.0; mixing int and float promotes to float.
  • bool("") is False, but bool("0") is True.
  • round(2.5) is 2 (banker's rounding), and int("2.5") raises ValueError.

Control Flow: Conditional Blocks and Loops

What this domain covers

Control flow is the largest PCEP domain. You must trace if/elif/else, while, for over range(), and break/continue, including nested and loop-else constructs.

Core rules

  • Only the first true branch of an if/elif chain runs. Conditions are tested top to bottom; else is optional.
  • range(stop) starts at 0; range(start, stop, step) excludes stop. Negative steps count down: list(range(5, 0, -2)) == [5, 3, 1].
  • while checks its condition before every iteration; if initially false, the body never runs.
  • break exits the nearest loop immediately. continue skips to the next iteration.
  • A loop's else runs only when the loop ends normally, that is, without break.
  • pass is a no-op placeholder. The conditional expression a if cond else b is an expression, not a statement.

Worked example

for i in range(1, 4): if i == 2: continue; print(i) prints 1 then 3. range(1, 4) yields 1, 2, 3; when i is 2, continue jumps to the next value, so print is skipped only for 2. Replacing continue with break would print only 1, because the loop would terminate at i == 2.

Traps

  • while x > 0: with no change to x inside creates an infinite loop.
  • Indentation defines blocks; a wrongly indented print may sit outside the loop.
  • for i in range(3): finishes with i == 2; the loop variable persists afterwards.
  • if x = 1: is invalid. Chained comparisons like 0 < x < 10 mean 0 < x and x < 10.
  • Appending to a list while iterating over it can skip elements.

Data Collections: Lists, Tuples, Sets, Dictionaries, and Strings

What this domain covers

This domain tests the four built-in collections and strings: indexing, slicing, mutability, core methods, and which operations raise errors. Expect "what is the output" questions involving aliasing and in-place methods.

Core rules

  • Lists are ordered and mutable: a[i], a[i:j], negative indices, len(), in. Methods include append, extend, insert, pop, remove, sort, reverse. sort() modifies in place and returns None.
  • Tuples are ordered and immutable. A one-element tuple needs a comma: (5,). Unpacking: a, b = 1, 2.
  • Sets hold unique, hashable elements and are unordered. {} is an empty dict; set() is an empty set. Operators: | union, & intersection, - difference, ^ symmetric difference; add, discard (no error if absent), remove (raises KeyError).
  • Dictionaries map hashable keys to values, preserve insertion order, and support d[k], get(k, default), keys(), values(), items(), and in (checks keys). d[k] on a missing key raises KeyError.
  • Strings are immutable sequences: s[0], slicing, in, +, *, and methods such as upper, strip, split, join, replace, find. Every method returns a new string.

Worked example

a = [3, 1, 2]; b = a; b.sort(); print(a) prints [1, 2, 3]. b = a copies the reference, not the list, so both names point to the same object. For an independent list use b = a[:], a.copy() or list(a).

Traps

  • a = b aliases; slicing copies.
  • x = a.sort() makes x equal to None.
  • Negative indices count from the end; slices never raise IndexError.
  • s[0] = "H" fails because strings are immutable.
  • Adding a list to a set raises TypeError because lists are unhashable.

Functions and Exceptions

What this domain covers

PCEP checks function definition and calls, argument passing, variable scope, return values, and basic exception handling with try/except/else/finally.

Core rules

  • Define with def name(params):; call with positional or keyword arguments. Defaults must follow non-default parameters. return without a value, or no return, yields None.
  • Arguments are assigned to parameters in order; keyword arguments can be given in any order. A function can return any object, including a tuple.
  • Scope follows LEGB: Local, Enclosing, Global, Built-in. Assigning to a name inside a function makes it local unless declared global (or nonlocal for an enclosing function).
  • try runs protected code. except SomeError: catches that class and its subclasses. else runs if no exception occurred; finally always runs.
  • raise ValueError("bad") raises deliberately. Built-ins to know: ZeroDivisionError, ValueError, TypeError, IndexError, KeyError, NameError.

Worked example

def f(a, b=2): return a / b try: print(f(6, 0)) except ZeroDivisionError: print("div0") finally: print("done") Output: div0 then done. f(6, 0) overrides the default b with 0, division raises ZeroDivisionError, the handler prints, and finally always executes.

Traps

  • A mutable default such as def f(x, acc=[]) is created once and shared across calls.
  • Catching Exception before a more specific handler makes the specific one unreachable.
  • Code after raise in the same block does not run.
  • Exceptions raised in the else block are not caught by the preceding except.
  • A SyntaxError from malformed source is not caught by a runtime try.

File Handling and Module Imports

What this domain covers

The smallest PCEP domain covers opening, reading and writing text files, and importing modules from the standard library.

Core rules

  • open(path, mode) returns a file object. Modes: "r" read (default, file must exist), "w" write (creates or truncates), "a" append, "r+" read/write, plus "b" for binary and "t" for text.
  • Use a context manager: with open("data.txt") as f: closes the file automatically, even if an exception occurs.
  • Reading: f.read() returns the whole file as one string; f.readline() returns one line including \n; f.readlines() returns a list of lines. Iterating over f yields lines.
  • Writing: f.write(s) writes a string and returns the character count; f.writelines(seq) writes an iterable of strings. No newline is added automatically.
  • Import forms: import math then math.sqrt(9); from math import sqrt then sqrt(9); import numpy as np aliases. Importing executes the module's top-level code once, then caches it in sys.modules.

Worked example

with open("out.txt", "w") as f: f.write("a\nb") with open("out.txt") as f: print(f.read().splitlines()) Output: ['a', 'b']. The first with creates or truncates the file and writes two lines; the second opens for reading and read() returns "a\nb", which splitlines() turns into a list.

Traps

  • "w" erases existing content; use "a" to preserve it.
  • f.write(5) raises TypeError; convert with str(5).
  • Reading twice returns "" the second time because the position is at end-of-file; use f.seek(0) to rewind.
  • from math import * pollutes the namespace and can hide names.
  • Importing a missing module raises ModuleNotFoundError.

PCEP cheat sheet

Quick reference

Computer Programming and Python Fundamentals

  • Python is interpreted and dynamically typed: no declaration is needed before a name is assigned, and a name can later be rebound to an object of a different type.

  • input() always returns a str, even when the user types digits; convert with int() or float() before arithmetic, otherwise + concatenates text.

  • print() separates arguments with a space and ends with a newline by default; the keyword arguments sep and end override those two behaviours.

  • Identifiers may contain letters, digits and underscores but cannot start with a digit; they are case-sensitive and cannot be keywords such as for, class or None.

  • Operators: / is true division and always returns float, // is floor division, % returns a remainder whose sign follows the divisor, ** is exponentiation and is right-associative.

  • Integer literal prefixes: 0b binary, 0o octal, 0x hexadecimal; underscores may separate digits (1_000_000) and do not affect the value.

  • None is a singleton of type NoneType meaning the absence of a value; identity test is 'x is None', not 'x == None'.

  • Precedence from highest: ** then unary + and -, then * / // %, then + and -, then comparisons, then not, then and, then or.

  • Comments begin with # and run to end of line; Python has no block comment syntax, though a triple-quoted string is often used as a stand-in.

Quick reference

Control Flow: Conditional Blocks and Loops

  • if/elif/else tests conditions top to bottom and executes only the first true branch; elif conditions are not evaluated once an earlier branch has run.

  • Blocks are defined by indentation (conventionally 4 spaces); inconsistent indentation raises IndentationError, and mixing tabs with spaces raises TabError.

  • Falsy values: 0, 0.0, 0j, '', [], (), {}, set(), None and False; every other object, including non-empty containers, evaluates as true.

  • range(stop) starts at 0, range(start, stop) and range(start, stop, step) exclude stop; a negative step counts downward and step=0 raises ValueError.

  • break exits the innermost enclosing loop immediately; continue skips the rest of the current iteration; pass is a no-op placeholder statement.

  • The else block of a for or while loop runs only when the loop ends without executing break.

  • Chained comparisons such as 0 <= x < 10 mean 0 <= x and x < 10, with the middle operand evaluated only once.

  • Conditional expression: value_if_true if condition else value_if_false; it is an expression and must yield a value, unlike an if statement.

Quick reference

Data Collections: Lists, Tuples, Sets, Dictionaries, and Strings

  • Lists are mutable and ordered and allow duplicates: index with list[i], negative indices count from the end, and slicing [start:stop:step] returns a new list.

  • Tuples are immutable sequences; a one-element tuple needs a trailing comma - (1,) is a tuple while (1) is an int.

  • Sets are unordered collections of unique hashable elements: create an empty one with set(), because {} builds an empty dict, and indexing is not supported.

  • Dicts map hashable keys to values and preserve insertion order; d[key] raises KeyError when absent, while d.get(key, default) returns default instead.

  • Strings are immutable: upper(), lower(), strip(), replace(), split() and join() return new objects; assigning to s[0] raises TypeError.

  • List mutation methods: append(x) adds one element, extend(iterable) adds each item, insert(i, x) shifts the rest, pop() removes by index, remove() removes the first matching value.

  • Set operators: | union, & intersection, - difference, ^ symmetric difference; the operators require sets on both sides, while the named methods accept any iterable.

  • len(), in and not in work for lists, tuples, sets, dicts (key membership) and strings (substring membership); sorted() returns a new list from any iterable.

  • Repeating a nested list with [[0]*3]*3 creates three references to one inner list, so use a comprehension such as [[0]*3 for _ in range(3)] instead.

Quick reference

Functions and Exceptions

  • def name(parameters): defines a function; return without a value, or falling off the end of the body, both return None.

  • Default parameter values are evaluated once when the def statement executes, so a mutable default like [] is shared across every call.

  • Positional arguments must precede keyword arguments; *args collects extra positional arguments into a tuple and **kwargs collects extra keyword arguments into a dict.

  • Name resolution follows LEGB: Local, Enclosing function, Global, Built-in; assigning a name inside a function makes it local unless global or nonlocal is declared.

  • try/except/else/finally: except runs on a matching exception, else runs only if no exception occurred, and finally always runs.

  • except SomeError as e binds the exception object; a bare except: also catches KeyboardInterrupt and SystemExit, so naming the exception type is safer.

  • raise ValueError('message') raises an exception; uncaught exceptions propagate up the call stack until a matching handler is found.

  • Frequent built-ins: ValueError, TypeError, KeyError, IndexError, ZeroDivisionError, NameError, FileNotFoundError, AttributeError.

  • lambda parameters: expression builds an anonymous function whose body is a single expression whose value is returned; it cannot contain statements.

Quick reference

File Handling and Module Imports

  • open(path, mode) modes: 'r' read (default), 'w' truncate or create, 'a' append, 'x' exclusive create that fails if the file exists, plus 'b' binary, 't' text and '+' read/write.

  • with open(path) as f: closes the file automatically, even if an exception is raised inside the block, replacing a manual try/finally close.

  • Reading: f.read() returns the whole file as one string, f.readline() returns one line including '\n' (or '' at end of file), f.readlines() returns a list of lines, and iterating over f yields lines.

  • f.write(s) writes a string and returns the number of characters written; it adds no newline, and writelines() writes each string of an iterable without adding separators.

  • Text mode returns str, binary mode ('rb') returns bytes; a file opened for writing with 'w' must be closed or flushed before its content is guaranteed on disk.

  • Import styles: import math then math.sqrt(16); from math import sqrt then sqrt(16); import math as m then m.sqrt(16); from math import * imports all public names.

  • An import executes the module's top-level code only the first time; later imports reuse the cached module object held in sys.modules.

  • if name == 'main': guards code that should run only when the file is executed directly, not when it is imported as a module.

  • The random module provides random(), randint(a, b) with both bounds included, randrange(), choice() and seed() for reproducible sequences.

PCEP key terms

Interpreter

A program that reads source code and executes it directly, translating it statement by statement at runtime rather than producing a separate compiled executable file first.

Related: Variable, Keyword
Variable

A named reference that points to a value stored in memory. In Python you create one by assigning a value with the equals sign; no type declaration is required.

Related: Identifier, Type casting
Identifier

A name you give to a variable, function, class, or module. It must start with a letter or underscore, may contain digits, and cannot be a keyword.

Related: Variable, Keyword
Keyword

A word reserved by the Python language for a fixed purpose, such as if, for, def, or None. You cannot use it as an identifier.

Related: Identifier
Type casting

Converting a value from one data type to another using constructor functions such as int(), float(), or str(). Some conversions succeed silently while others raise an error at runtime.

Related: Exception, Variable
Operator precedence

The rules that decide which operator in an expression is evaluated first. Multiplication and division bind tighter than addition and subtraction, and parentheses override the default order.

Related: Modulo operator, Floor division
Floor division

The // operator, which divides two numbers and rounds the result down to the nearest whole number. With negative operands it rounds toward negative infinity, not toward zero.

Related: Modulo operator, Operator precedence
Modulo operator

The % operator, which returns the remainder left after integer division. It is often used to test whether a number is even or odd.

Related: Floor division
Truthiness

The rule that any object can be tested as a condition. Empty collections, zero numbers, None, and empty strings count as false; most other values count as true.

Related: if-elif-else, while loop
Escape sequence

A backslash followed by a character inside a string literal that stands for a special character, such as \n for a newline or \t for a tab.

if-elif-else

A conditional block that runs one of several branches. Python tests each condition in order and executes only the first branch whose condition is true.

Related: Truthiness, while loop
while loop

A loop that repeats a block as long as its condition remains true. The condition is checked before each pass, so the body may never run at all.

Related: for loop, break
for loop

A loop that visits each item of an iterable, such as a list, string, or range, and runs the body once per item.

Related: while loop, range()
range()

A built-in function that produces a sequence of integers. It accepts a stop value, or start and stop, plus an optional step, and never includes the stop value.

Related: for loop
break

A statement that immediately ends the innermost loop, skipping any remaining iterations and the loop's else block if one is present.

Related: continue, Loop else clause
continue

A statement that skips the rest of the current loop iteration and jumps straight to the next one, without ending the loop itself.

Related: break
Loop else clause

An optional else block attached to a for or while loop. It runs only when the loop finished normally, not when the loop was exited with break.

Related: break, while loop
List

An ordered, mutable collection written with square brackets. It can hold items of mixed types, allows duplicates, and supports indexing, slicing, and many in-place methods.

Related: Tuple, Indexing
Tuple

An ordered, immutable collection written with parentheses. Once created it cannot be changed, and it is often used to return several values from a function.

Related: List, Mutability
Dictionary

A mutable collection of key-value pairs written with curly braces. Keys must be unique and hashable; values can be any object. Lookup is done by key, not by position.

Related: Set, List
Set

An unordered, mutable collection of unique hashable items written with curly braces or set(). Duplicates are removed, and sets support union, intersection, and difference.

Related: Dictionary, Mutability
Indexing

Accessing a single item of a sequence by its position in square brackets. Python counts from zero, and negative indexes count backward from the end.

Related: Slicing, List
Slicing

Extracting a subsequence with the start:stop:step syntax. The start is included, the stop is excluded, and omitted values default to the beginning, the end, and a step of one.

Related: Indexing, List
Mutability

The property of an object that allows its contents to be changed after creation. Lists, dictionaries, and sets are mutable; tuples, strings, and numbers are not.

Related: List, Tuple
List comprehension

A compact expression that builds a new list by applying an operation to each item of an iterable, optionally keeping only items that satisfy an if condition.

Related: List, for loop
Membership operator

The in and not in operators, which test whether a value appears in a collection or a substring occurs in a string, returning True or False.

Related: Set, List
Function definition (def)

A block introduced by the def keyword that names a function, lists its parameters, and contains the code that runs when the function is called.

Related: Parameter and argument, Default parameter
Parameter and argument

A parameter is the name listed in a function definition; an argument is the actual value passed in when the function is called.

Related: Function definition (def), Default parameter
Default parameter

A parameter given a value in the function definition. If the caller omits that argument the default is used; defaults must come after parameters that have none.

Related: Parameter and argument, Function definition (def)
Scope

The region of a program where a name can be accessed. Python resolves names through local, enclosing, global, and built-in scopes, in that order.

Related: Function definition (def)
Exception

An event that interrupts normal execution, such as dividing by zero or converting an invalid string. Unhandled exceptions stop the program and print a traceback.

Related: try-except-finally, raise statement
try-except-finally

A block for handling errors: try holds risky code, except catches matching exceptions, and the optional finally always runs whether or not an error occurred.

Related: Exception, raise statement
raise statement

A statement that deliberately triggers an exception, either re-raising the current one or creating a new one with a message.

Related: Exception, try-except-finally
open()

A built-in function that opens a file and returns a file object used for reading or writing. It takes a path plus an optional mode and encoding.

Related: File mode, with statement
File mode

A short string passed to open() that says how the file is used: r for reading, w for writing and truncating, a for appending, b for binary, + for updating.

Related: open(), with statement
with statement

A context manager block that opens a file, runs its body, and closes the file automatically afterwards, even if an exception is raised inside.

Related: open(), File mode
import statement

The statement that loads a module and binds it to a name, giving access to its functions, classes, and variables through dot notation.

Related: from-import statement, __name__ guard
from-import statement

A form of import that brings specific names from a module directly into the current namespace, optionally renaming them with the as keyword.

Related: import statement
__name__ guard

The idiom if name == "main": used to run code only when the file is executed directly, not when it is imported as a module.

Related: import statement

PCEP study plan

8 weeks · About 6 hours per week

Week 1

Computer Programming and Python Fundamentals & Data Collections: Lists, Tuples, Sets, Dictionaries, and Strings

  • Write and run 20 short scripts mixing int, float, bool and str literals with + - * / // % **, predicting every result before execution and logging any mismatch.

  • Convert values between int, float, str and bool, and state which values are falsy (0, 0.0, '', [], (), {}, None, False).

  • Build a single-file script that reads two values with input(), casts them, and prints a formatted result using print() with sep and end arguments.

  • Complete 30 index and slice predictions on lists and strings, including negative indices, step values and out-of-range cases, marking which raise IndexError.

  • Identify and fix 10 deliberately broken snippets involving unterminated strings, wrong indentation and mismatched operators.

Your checkpoint

One commented .py file containing the 30 index/slice predictions with predicted vs actual output, plus a 10-entry error log naming each exception type you triggered and its cause.

Week 2

Data Collections: Lists, Tuples, Sets, Dictionaries, and Strings

  • Apply list methods append, insert, extend, remove, pop, sort, reverse, index and count across 20 scenarios, stating for each whether the method mutates in place or returns a new object.

  • Demonstrate aliasing versus copying by writing snippets using b = a, a[:], list(a) and a.copy(), and showing where a shared reference changes observable behavior.

  • Build a word-frequency counter over a 300-word text using a dictionary with get, setdefault, keys, values, items, update and pop.

  • Use at least 15 string methods (split, join, strip, replace, find, rfind, startswith, endswith, upper, lower, isdigit, isalpha, isspace, title, center) and slice strings with negative steps.

  • Solve three deduplication and overlap problems with set operators | & - ^ and explain why a set cannot contain a list.

  • Pack and unpack tuples in assignment, function returns and swap statements, and explain why tuple immutability prevents item assignment.

Your checkpoint

A 60-question self-made collections quiz with answer key, scored at 80% or higher, plus a one-page cheat sheet classifying every method you used as in-place versus returning a new object.

Week 3

Control Flow: Conditional Blocks and Loops

  • Write 20 if/elif/else blocks covering comparison chaining, in, not in, is, is not and truthiness, predicting the branch taken before running each one.

  • Trace short-circuit evaluation of and, or and not across 15 expressions that call side-effecting functions, recording exactly which calls execute.

  • Rewrite 10 nested if statements as flat elif chains or conditional expressions and justify each rewrite.

  • Diagnose 10 snippets that raise IndentationError or SyntaxError, fix them, and state the PEP 8 rule that was violated.

Your checkpoint

Hand-drawn decision trees for five branching problems, plus a 30-question conditional quiz scored at 85% or higher with every miss re-explained in writing.

Week 4

Control Flow: Conditional Blocks and Loops

  • Write for loops over range() with start, stop and step, and over strings, lists and dictionaries (keys, values, items), stating the iteration order for each.

  • Use while loops for eight accumulating and searching tasks, and write down the exact condition that terminates each loop.

  • Control loop flow with break, continue and the loop else clause across 12 exercises, predicting whether else executes in each case.

  • Build a nested-loop multiplication table and a pattern printer, then rewrite the multiplication table using a single loop.

  • Debug five infinite loops by adding a counter, a state print or a corrected condition.

Your checkpoint

A timed 45-minute set of 12 loop tasks that all run correctly, plus a written trace table for five tricky break/else cases showing each iteration's variable values.

Week 5

Functions and Exceptions

  • Define and call 20 functions covering positional arguments, keyword arguments and default values, including a demonstration of the mutable default argument trap.

  • Explain return semantics by writing functions with no return, an early return, and a return of multiple values as a tuple.

  • Trace name resolution across 12 nested-scope snippets using the local, enclosing, global, built-in order, then rewrite one using the global keyword and argue why that is usually avoidable.

  • Write five recursive functions (factorial, Fibonacci, digit sum, list length, binary search) and print the recursion depth for each.

Your checkpoint

A small module of 10 documented functions plus a separate test script that prints expected versus actual for 15 cases and finishes with a pass count.

Week 6

Functions and Exceptions

  • Use try/except/else/finally in 12 snippets and predict exactly which blocks execute for success, handled error and unhandled error outcomes.

  • Catch specific exceptions (ValueError, ZeroDivisionError, TypeError, KeyError, IndexError, FileNotFoundError) instead of a bare except, and justify each choice.

  • Raise and re-raise exceptions with raise, and validate inputs with assert while noting that the -O flag disables assertions.

  • Place 10 built-in exceptions into the standard hierarchy and state which base class a broad handler should target.

Your checkpoint

A crash-proof input-validation function that handles bad input gracefully, accompanied by a 20-case test matrix listing the exception type, message and recovery path for each case.

Week 7

File Handling and Module Imports

  • Open, read (read, readline, readlines), write and append text files in modes 'r', 'w', 'a', 'r+', 'rb', predicting file contents after each operation and verifying with a hex or repr dump.

  • Refactor eight file snippets to use the with statement so files close even when an exception is raised, and confirm closure by inspecting the file object.

  • Import modules with import x, from x import y and import x as z, and use functions from math, random and platform in 10 working snippets.

  • Diagnose six runtime failures involving FileNotFoundError, ModuleNotFoundError, a wrong open mode and a file used after close.

Your checkpoint

A command-line program that reads a text file, counts characters, words and lines, and writes a formatted report file, plus a table of 10 file-mode outcomes you verified empirically.

Week 8

Computer Programming and Python Fundamentals & Control Flow: Conditional Blocks and Loops & Data Collections: Lists, Tuples, Sets, Dictionaries, and Strings & Functions and Exceptions & File Handling and Module Imports

  • Re-attempt every entry in your error log and confirm each mistake is now explainable in one sentence.

  • Complete two 45-question timed mocks spanning all five domains and score 85% or higher on both.

  • Drill the 20 weakest objectives surfaced by the mocks until each is answered correctly twice in a row without notes.

  • Compress operator precedence, mutable versus immutable types, and the exception hierarchy onto a single reference page you can redraw from memory.

Your checkpoint

Two timed mock scores at 85% or higher, a one-page final cheat sheet, and a ranked list of remaining weak spots with a fix for each.

Milestones

Week 2: Without notes, correctly predict the output of 20 mixed list, string, tuple, set and dict operations, including method return values and mutation side effects, scoring at least 80%.

Week 4: Score 80% or higher on a 40-question, 50-minute mock covering domains 1, 2 and 3, with every wrong answer rewritten as a corrected snippet in your error log.

Week 6: Write from scratch, in under 20 minutes, a function that validates user input using try/except/else/finally and raise, then demonstrate it surviving five different bad inputs without crashing.

Week 8: Pass two full timed mocks at 85% or higher with no domain below 70%, and explain aloud the cause of every error you made in week 1.

PCEP exam day

Your checklist

Government-issued photo ID

Bring the original ID you used at registration; the name on it must match your registration exactly. Confirm accepted ID types with the provider before exam day.

Secondary ID if required

needs_review - Some test centers or online proctoring vendors require a second ID. Check your appointment instructions and confirm with the provider; do not assume it is optional.

Appointment confirmation and registration number

Have the confirmation email, order number, date and time with time zone, and either the test-center address or the online login link ready. Confirm whether anything must be printed.

Computer and browser system check

Run the provider's system test on the same machine and network you will use. Update the browser and operating system, and close VPNs if instructed. needs_review - exact technical requirements vary by delivery vendor, so confirm them in advance.

Webcam, microphone, and speakers or headset

For online proctoring, test audio and video before check-in. Use a wired headset if allowed and confirm any Bluetooth restrictions with the provider.

Stable internet connection with a backup

Prefer wired Ethernet over Wi-Fi. Keep a phone with a mobile hotspot as a backup, but do not switch networks unless the proctor tells you to.

Private room and clear desk

Use a quiet, well-lit room with a door you can close. Remove papers, phones, smartwatches, notes, books, and extra monitors unless the provider explicitly permits them.

Scratch paper or whiteboard only if permitted

needs_review - Delivery rules may allow a small whiteboard or blank paper for tracing code. Confirm the exact rule and allowed size before the exam; never bring prepared notes.

Power adapter and charger

Plug in the laptop and keep the charger connected throughout the exam. At a test center, bring only what the center allows and confirm where belongings must be stored.

Bathroom and water before check-in

Use the bathroom and drink water before the exam starts. Breaks during the 45-minute test may not be allowed; confirm the provider's break policy before exam day.

Candidate handbook and support contact

Read the current candidate handbook and save the proctor or support phone number and chat link. Know how to report a disconnection or technical problem immediately.

Plan the day

Final 72 hours

Confirm the appointment date, time zone, delivery method, and the exact name on your registration. Run the system test on the machine you will use. Take one timed practice set and write down your weak syllabus areas rather than reviewing everything equally.

Final 48 hours

Do targeted review of PCEP-level Python: operators and precedence, strings, lists, tuples, dictionaries, sets, loops and range, function arguments, return values, exceptions, and indentation. Trace short code snippets by hand and predict the output before running them.

Final 24 hours

Stop learning new topics. Do a light review of your own error list, prepare the room and desk, charge devices, confirm travel or login details, and sleep a full night. Cramming new syntax the night before usually costs more in focus than it gains in knowledge.

Morning of the exam

Eat a normal meal, hydrate, and use the bathroom. Check that your ID and appointment details are ready. For online proctoring, close all non-essential applications, silence notifications, and keep your phone out of reach unless it is your documented backup.

15 to 30 minutes before start

Join check-in early if the provider recommends it; confirm the exact early-arrival window with the provider. Do a final desk check, test audio and video, and read the proctor instructions without rushing.

During the first few minutes

Read the instructions and note the time limit. PCEP is 40 questions in 45 minutes, so aim for roughly one minute per question and leave time to review flagged items. Do not spend several minutes on one code snippet early in the exam.

During code-tracing questions

Trace line by line instead of guessing from the overall shape of the code. Watch indentation, loop boundaries, integer division, operator precedence, short-circuit evaluation, mutable default arguments, and the order of exception handling. Use scratch materials only if the provider permits them.

When a question blocks you

If the platform allows marking for review, flag the question and move on. Answer every question if there is no penalty for guessing, but confirm the scoring rule with the provider. Return to flagged items after you have seen the rest of the exam.

Last 10 minutes

Check for unanswered questions, review flagged items, and confirm that your selections are saved. Submit before the timer expires; do not keep changing answers without a concrete reason.

After submission

Note the score report and any next-step instructions. If the provider issues a digital badge or certificate, confirm how to access it. If you did not pass, review the score report and confirm the retake policy with the provider.

Rules to check

  • Bring the original government-issued photo ID used at registration and make sure the name matches exactly. If a second ID is required, confirm that requirement with the provider before exam day.

  • Do not use notes, books, phones, smartwatches, or other unauthorized materials. Keep only permitted items on the desk; confirm the scratch-paper or whiteboard rule in advance.

  • Stay visible and audible for online proctoring, do not talk to anyone, and do not leave the camera view. Follow the proctor's instructions immediately if asked to adjust the camera or show the room.

  • The PCEP exam is commonly 40 questions in 45 minutes, and breaks are generally not allowed once the exam starts. Confirm the current timing and break policy with the provider, and use the bathroom before check-in.

  • The passing score is commonly 70 percent. Confirm the current exam version, scoring, and score-report timing with the provider rather than relying on older candidate reports.

  • If the connection drops or the platform freezes, contact the proctor or support immediately and follow their instructions. Do not refresh, restart, or troubleshoot alone unless told to do so.

  • Do not share, reproduce, or discuss exam questions after the test. Certification exams are protected by confidentiality rules; violating them can affect your certification status.

  • At a test center, arrive within the provider's recommended early-arrival window, follow staff instructions, and store belongings where directed. Confirm the exact arrival time and locker policy with the test center.

PCEP FAQ

How many PCEP (30-03) practice questions are available?

The practice set has 200 PCEP (30-03) questions. Each one includes the choices, the correct answer, and an explanation, and the set is free to read with no signup.

How many PCEP (30-03) flashcards are available?

The flashcard set has 32 PCEP (30-03) cards. Each card shows the term and its definition.

Which topics does the PCEP (30-03) study material cover?

The PCEP (30-03) study material has 5 sections, including Computer Programming and Python Fundamentals, Control Flow: Conditional Blocks and Loops, and Data Collections: Lists, Tuples, Sets, Dictionaries, and Strings.

What format facts does the catalog list for the PCEP (30-03) exam?

The catalog lists a duration of 50 minutes and these item types: single-select, multiple-select, interactive, and scenario-based for the PCEP (30-03) exam.