Courseiva

CCNA Computer Programming and Python Fundamentals Questions

62 of 137 questions · Page 2/2 · Computer Programming and Python Fundamentals · Answers revealed

76
Multi-Selectmedium

Which TWO of the following are immutable data types in Python?

Select 2 answers
A.str
B.set
C.dict
D.list
E.tuple
AnswersA, E

Immutable: string objects cannot be changed.

Why this answer

Strings (str) in Python are immutable, meaning once a string object is created, its content cannot be changed. Any operation that appears to modify a string actually creates a new string object in memory, leaving the original unchanged.

Exam trap

The PCEP exam often tests the distinction between mutable and immutable types by pairing tuple (immutable) with list (mutable), hoping candidates confuse tuple's immutability with list's mutability, or mistakenly think that because a tuple can contain mutable objects, the tuple itself is mutable.

77
Multi-Selectmedium

Which FOUR of the following are valid ways to create a list with elements 1, 2, 3? (Choose four.)

Select 4 answers
A.[1, 2, 3,]
B.list(range(1, 4))
C.[1, 2, 3]
D.list(1, 2, 3)
E.list((1, 2, 3))
AnswersA, B, C, E

Correct. A trailing comma is allowed in Python list literals, so [1, 2, 3,] creates a list with elements 1, 2, 3.

Why this answer

Options A, B, C, and E are all valid ways. A: list literal with trailing comma; B: list() constructor with range; C: standard list literal; E: list() constructor with a tuple. Option D is invalid because list() expects a single iterable argument, not multiple arguments.

Exam trap

Python Institute often tests the distinction between the `list()` constructor requiring a single iterable argument versus the mistaken belief that it accepts multiple positional arguments, as in option D.

78
MCQhard

A developer runs the code from the exhibit and gets the error shown. Which of the following is the most likely cause?

A.There is a typo in the variable name.
B.The variable 'result' was never assigned a value.
C.The print function requires an import.
D.The variable 'result' is a string, not an integer.
AnswerB

NameError occurs when variable is not defined.

Why this answer

The error message indicates that the variable 'result' is referenced before it has been assigned any value. In Python, using a variable that has never been assigned raises a NameError. The code attempts to print 'result', but no assignment to 'result' exists in the provided code, so Python cannot resolve the name.

Exam trap

The PCEP exam often tests the distinction between a variable that exists but has the wrong type (TypeError) and a variable that has never been assigned (NameError), leading candidates to incorrectly focus on type mismatches instead of the missing assignment.

How to eliminate wrong answers

Option A is wrong because a typo in the variable name would still cause a NameError, but the error message would reference the misspelled name, not 'result'. Option C is wrong because the print function is a built-in in Python 3 and does not require any import; it is always available. Option D is wrong because the error is a NameError, not a TypeError; the variable 'result' does not exist at all, so its type is irrelevant.

79
MCQmedium

A developer writes: print('Hello' + 5). What is the result?

A.Hello 5
B.TypeError
C.SyntaxError
D.Hello5
AnswerB

Cannot concatenate str and int.

Why this answer

In Python, the + operator performs string concatenation only when both operands are strings. Attempting to concatenate a string ('Hello') with an integer (5) raises a TypeError because Python does not implicitly convert the integer to a string for concatenation. This is a fundamental type safety feature of the language.

Exam trap

This exact scenario tests whether candidates understand that Python does not implicitly convert an integer to a string for concatenation, unlike loosely-typed languages.

How to eliminate wrong answers

Option A is wrong because it suggests that Python would automatically insert a space between the string and integer, which is not the case; the + operator does not add spaces. Option C is wrong because the code is syntactically valid (no missing colons, parentheses, or keywords) — the error occurs at runtime, not during parsing. Option D is wrong because it implies Python would implicitly convert the integer 5 to the string '5' and concatenate, but Python's strict type system prevents this without an explicit str() call.

80
MCQhard

A programmer wants to create a function that can accept any number of keyword arguments and store them in a dictionary. Which function definition is correct?

A.def func(kwargs):
B.def func(**kwargs):
C.def func(**args):
D.def func(*kwargs):
AnswerB

Correct: **kwargs accepts arbitrary keyword arguments.

Why this answer

The **kwargs parameter in a function definition collects any number of extra keyword arguments into a dictionary. The double asterisk (**) is the Python syntax for capturing keyword arguments, and 'kwargs' is the conventional name for the resulting dictionary.

Exam trap

The PCEP exam often tests the distinction between *args (positional arguments packed into a tuple) and **kwargs (keyword arguments packed into a dictionary), and the trap here is that candidates confuse the single asterisk for keyword arguments or forget that the double asterisk is required for dictionary packing.

How to eliminate wrong answers

Option A is wrong because 'kwargs' without the double asterisk is just a regular parameter name; it does not collect keyword arguments and will cause a TypeError if keyword arguments are passed. Option C is wrong because '**args' uses the conventional name for positional arguments ('args') with the keyword argument syntax, which is misleading and non-standard, though technically it would work; however, the exam expects the conventional **kwargs. Option D is wrong because '*kwargs' uses a single asterisk, which collects extra positional arguments into a tuple, not keyword arguments into a dictionary.

81
MCQhard

Refer to the exhibit. What is printed?

A.None
B.x greater
C.equal
D.y greater
AnswerB

The if condition is satisfied.

Why this answer

The code defines x = 10 and y = 5. The if-elif-else structure first checks if x > y, which is true (10 > 5), so it prints 'x greater' and skips the remaining conditions. Therefore, option B is correct.

Exam trap

The PCEP exam often tests the sequential evaluation of if-elif-else chains, where candidates mistakenly think multiple branches can execute or that the else branch runs when a prior condition is true.

How to eliminate wrong answers

Option A is wrong because the code does not produce None; it prints a string. Option C is wrong because x is not equal to y (10 != 5), so the elif condition x == y is false. Option D is wrong because the first condition x > y is true, so the else branch (which would print 'y greater') is never executed.

82
MCQhard

A Python script processes a large file and runs out of memory. Which solution is most appropriate?

A.Increase the memory allocation
B.Use a while loop to read chunks
C.Read the entire file into memory and split
D.Process the file line by line using a for loop
AnswerD

This reads each line as needed, keeping memory usage low.

Why this answer

Reading a file line by line with a for loop in Python processes one line at a time, keeping only the current line in memory. This avoids loading the entire file into RAM, which is the root cause of the memory exhaustion when dealing with large files.

Exam trap

The PCEP exam often tests the misconception that reading a file in chunks with a while loop is the best approach, when in fact the idiomatic for loop over the file object is simpler, safer, and the recommended pattern in Python for line-by-line processing.

How to eliminate wrong answers

Option A is wrong because simply increasing memory allocation does not solve the underlying inefficiency; it only postpones the problem and may not be feasible or cost-effective. Option B is wrong because using a while loop to read chunks (e.g., file.read(chunk_size)) still requires manual buffer management and can still lead to memory issues if chunks are too large or not handled properly; the idiomatic Python approach is to iterate over the file object directly. Option C is wrong because reading the entire file into memory and then splitting it is exactly the behavior that causes memory exhaustion; it defeats the purpose of processing a large file.

83
MCQhard

Refer to the exhibit. A developer runs this code. What is printed?

A.Running in normal mode
B.Error
C.True
D.Debug mode active
AnswerA

Since debug is False, the else branch runs.

Why this answer

The code first checks a variable `debug`. Since `debug` is likely `False` or not set (default), the condition `if debug:` is `False`, so it moves to the `elif` branch. The condition `if __name__ == '__main__':` evaluates to `True` because the script is run directly, so it prints 'Running in normal mode'.

This is the standard Python entry-point pattern for conditional execution of code only when the script is executed directly.

Exam trap

The PCEP exam often tests the `if __name__ == '__main__':` idiom to see if candidates understand that `__name__` is `'__main__'` only when the script is run directly, not when imported.

How to eliminate wrong answers

Option B is wrong because there is no syntax error or runtime error in the code; the `if` statement and `print` function are valid. Option C is wrong because the code does not print the boolean `True`; it prints a string based on the condition. Option D is wrong because the code does not define or check any debug flag; the string 'Debug mode active' is never printed.

84
Multi-Selectmedium

Which THREE of the following are Python data types? (Choose three.)

Select 3 answers
A.float
B.list
C.char
D.dict
E.record
AnswersA, B, D

Built-in numeric type.

Why this answer

A is correct because `float` is a built-in Python numeric data type used to represent floating-point numbers (e.g., 3.14, -0.001). It is one of the core immutable types in Python, distinct from integers and complex numbers.

Exam trap

Python Institute often tests the distinction between Python's built-in types and types from other languages (like `char` or `record`) to catch candidates who assume Python has a dedicated character type or who confuse database terminology with Python data structures.

85
Multi-Selecteasy

Which TWO of the following are valid Python variable names? (Choose two.)

Select 2 answers
A.my-var
B.my_var
C.2nd_place
D._count
E.class
AnswersB, D

Valid.

Why this answer

(my_var) is correct because Python variable names can contain letters, digits, and underscores, but must not start with a digit. 'my_var' follows all naming rules: it starts with a letter, uses an underscore, and contains no invalid characters.

Exam trap

Python Institute often tests the rule that hyphens are invalid in variable names (tricking candidates who confuse them with underscores) and that keywords like 'class' cannot be used as identifiers, even though they look like valid names.

86
MCQhard

What is the output of the following code? x = [1, 2, 3]; y = x; y.append(4); print(x)

A.[1,2,3,4]
B.Error
C.[4]
D.[1,2,3]
AnswerA

x and y refer to the same list, so the append affects both.

Why this answer

In Python, variables hold references to objects, not copies. When `y = x` is executed, both `x` and `y` point to the same list object in memory. The `y.append(4)` method modifies that shared list in-place, so printing `x` reflects the change and outputs `[1, 2, 3, 4]`.

Exam trap

The PCEP exam often tests the distinction between reference assignment and copying for mutable objects, trapping candidates who assume `y = x` creates an independent copy of the list.

How to eliminate wrong answers

Option B is wrong because the code does not produce an error; `append` is a valid list method and the assignment `y = x` is syntactically correct. Option C is wrong because `[4]` would only be the output if `x` were reassigned to a new list containing only `4`, but here the original list is mutated. Option D is wrong because it assumes `y = x` creates a copy of the list, but Python uses reference semantics for mutable objects, so modifications through `y` affect `x`.

87
MCQeasy

The exhibit shows a JSON configuration. Which Python data structure is best suited to represent this configuration?

A.Dictionary
B.Tuple
C.String
D.List
AnswerA

JSON objects map directly to Python dictionaries.

Why this answer

JSON objects map directly to Python dictionaries. Option B (Tuple) is wrong because tuples are immutable and lack key-value mapping. Option C (String) is wrong because a string would lose all structure, making access by key impossible.

Option D (List) is wrong because lists are ordered sequences accessed by index, not by key-value pairs.

88
MCQhard

Consider the code: x = 10; def func(): x = 5; print(x); func(); print(x). What is the output?

A.5 10
B.5 5
C.10 10
D.10 5
AnswerA

Local scope inside function, global unchanged outside.

Why this answer

Inside the function `func()`, the local variable `x` is assigned the value 5, so `print(x)` inside the function outputs 5. After the function call, the global `x` remains 10, so the final `print(x)` outside the function outputs 10. This demonstrates Python's scoping rules where assignments inside a function create a local variable unless declared global.

Exam trap

The PCEP exam often tests the misconception that a variable assignment inside a function modifies the global variable, leading candidates to incorrectly choose options where both outputs are the same or the global value is overwritten.

How to eliminate wrong answers

Option B is wrong because it assumes the local assignment `x = 5` also changes the global `x`, which is not true without the `global` keyword. Option C is wrong because it suggests the function never uses its local `x`, outputting 10 twice, which ignores the local assignment. Option D is wrong because it reverses the order, outputting 10 then 5, which would only happen if the global `x` were printed first and then the local `x` after the function call, but the code prints inside the function first.

89
MCQmedium

A developer writes a function that returns multiple values. How should they return these values?

A.return a, b
B.return a+b
C.return [a,b]
D.return a; return b
AnswerA

This returns a tuple containing a and b.

Why this answer

In Python, a function can return multiple values by separating them with commas in the return statement. This automatically packs them into a tuple, which is then unpacked by the caller. Option A correctly uses `return a, b`, which returns a tuple `(a, b)`, allowing the caller to assign the results to separate variables.

Exam trap

The PCEP exam often tests the distinction between returning multiple values as a tuple (comma-separated) versus returning a single container object like a list, tricking candidates who think lists are the only way to return multiple items.

How to eliminate wrong answers

Option B is wrong because `return a+b` returns a single value (the sum of a and b), not multiple separate values. Option C is wrong because `return [a,b]` returns a list object containing a and b, not multiple return values; the function still returns a single object. Option D is wrong because `return a; return b` is syntactically invalid—only the first return statement executes, and the second is unreachable, causing a syntax error or unexpected behavior.

90
MCQmedium

Consider the following function definition: def add(a, b): return a + b What is the value of add(3, '4')?

A.Error due to missing import
B.'34'
C.7
D.TypeError: unsupported operand type(s) for +: 'int' and 'str'
AnswerD

Incompatible types.

Why this answer

Python's `+` operator is not defined for mixed types like `int` and `str`. When `add(3, '4')` is called, Python attempts to evaluate `3 + '4'`, which raises a `TypeError` because it cannot implicitly convert the string to an integer or vice versa. This is a fundamental type safety rule in Python.

Exam trap

The PCEP exam often tests the misconception that Python will implicitly convert types (like treating `'4'` as an integer) or that the `+` operator will concatenate any two values, when in reality it raises a `TypeError` for incompatible types.

How to eliminate wrong answers

Option A is wrong because no import is needed for basic arithmetic or string operations; the error is purely a type mismatch, not a missing module. Option B is wrong because Python does not automatically concatenate an integer and a string with `+`; that would require explicit conversion (e.g., `str(3) + '4'`). Option C is wrong because Python does not implicitly convert the string `'4'` to the integer `4` for addition; the `+` operator is strictly type-specific and raises an error instead.

91
MCQeasy

Refer to the exhibit. What is the output?

A.Invalid integer\nSome error
B.No output
C.Some error
D.Invalid integer
AnswerD

The specific ValueError handler runs.

Why this answer

The code attempts to convert the string '12.5' to an integer using int(). Since '12.5' is not a valid integer literal (it contains a decimal point), Python raises a ValueError. The exception is caught by the except clause, which prints 'Invalid integer'.

After the try-except block, there is no further print statement, so the only output is 'Invalid integer'.

Exam trap

Candidates may think that after catching an exception, the program continues to execute code that follows the try-except block, but in this question there is no such code. The trap is recognizing that the output consists solely of the print inside the except.

How to eliminate wrong answers

Option A is wrong because it suggests the output is 'Invalid integer\nSome error' with a literal backslash-n, but the actual output uses real newline characters, not the escape sequence. Option B is wrong because the code does produce output: it prints 'Invalid integer' from the except block and then 'Some error' after the try-except structure. Option C is wrong because the ValueError is caught, so no unhandled error occurs; the program prints both messages and terminates normally.

92
MCQeasy

Which of the following is the correct way to define a function that takes no arguments and returns the value 42?

A.function f(): return 42
B.def f() return 42
C.def f: return 42
D.def f(): return 42
AnswerD

Correct because it uses `def`, parentheses, colon, and the return statement.

Why this answer

The syntax for defining a function in Python requires the def keyword, followed by the function name, parentheses (even if no arguments), a colon, and the indented body. Option B is missing the colon after the parentheses, making it syntactically incorrect.

Exam trap

The trap here is that option B looks almost correct but is missing the mandatory colon. Candidates may overlook the colon and incorrectly select B as well. Only D is valid.

How to eliminate wrong answers

Option A is wrong because Python uses the `def` keyword, not `function`, to define functions. Option B is wrong because it is identical to D but lacks the [CORRECT] marker; however, the question lists D as correct, so B is not the intended answer. Option C is wrong because it omits the parentheses `()` after the function name, which are mandatory even when the function takes no arguments.

93
MCQmedium

A programmer writes: x = 5; y = 2; result = x / y. What is the type of result?

A.int
B.float
C.str
D.complex
AnswerB

True: / operator returns float.

Why this answer

In Python 3, the division operator (/) always returns a floating-point number, even if both operands are integers. Since x and y are both integers (5 and 2), the result of 5 / 2 is 2.5, which is of type float. Therefore, option B is correct.

Exam trap

Python Institute often tests the distinction between Python 3's true division (/) and floor division (//), trapping candidates who assume integer division returns an integer like in Python 2 or other languages such as C or Java.

How to eliminate wrong answers

Option A is wrong because the division operator (/) in Python 3 never returns an int; it always returns a float, even when the division is exact (e.g., 4 / 2 returns 2.0). Option C is wrong because the result of a numeric division is a numeric type, not a string; a string would require explicit conversion or string concatenation. Option D is wrong because complex numbers are created using a literal like 3+4j or the complex() function, not from integer division.

94
MCQeasy

What function is used to read input from the user in Python 3?

A.read_input()
B.sys.stdin.readline()
C.input()
D.raw_input()
AnswerC

Standard for user input.

Why this answer

In Python 3, the built-in `input()` function reads a line from standard input and returns it as a string. This is the standard and simplest way to capture user input, replacing the Python 2 `raw_input()` function.

Exam trap

The PCEP exam often tests the distinction between Python 2 and Python 3 input functions, trapping candidates who remember `raw_input()` from Python 2 or who think `sys.stdin.readline()` is the standard way to read user input.

How to eliminate wrong answers

Option A is wrong because `read_input()` is not a built-in Python function; it does not exist in the standard library. Option B is wrong because `sys.stdin.readline()` is a valid method to read input from standard input, but it is not the primary or simplest function for general user input; it requires importing the `sys` module and returns the newline character at the end unless stripped. Option D is wrong because `raw_input()` was the input function in Python 2, but it was removed in Python 3; using it in Python 3 raises a `NameError`.

95
Multi-Selectmedium

Which TWO of the following are valid Python variable names? (Choose two.)

Select 2 answers
A.for
B.var123
C.my-var
D.1var
E._myVar
AnswersB, E

Valid: letters and digits.

Why this answer

(var123) is correct because Python variable names must start with a letter or underscore, and can contain letters, digits, or underscores. 'var123' starts with a letter and contains only valid characters, making it a legal identifier.

Exam trap

Python Institute often tests the rule that hyphens are not allowed in variable names, tricking candidates who are used to hyphenated names from other languages like HTML or CSS.

96
MCQeasy

Which of the following statements about Python indentation is true?

A.Indentation is optional but recommended.
B.You can mix tabs and spaces freely.
C.Indentation must be consistent within a block.
D.Indentation only matters for loops and conditionals.
AnswerC

Correct.

Why this answer

Python enforces consistent indentation within a block to define the scope of statements. Unlike many languages that use braces, Python relies on the indentation level to group statements, and any inconsistency (e.g., mixing spaces and tabs or varying the number of spaces) will raise an IndentationError.

Exam trap

The trap here is that candidates often think indentation is merely a style recommendation (like in other languages) or that it only applies to control flow statements, but Python strictly enforces it for all block structures, and mixing tabs with spaces is a common pitfall that leads to runtime errors.

How to eliminate wrong answers

Option A is wrong because indentation is not optional in Python; it is syntactically mandatory to define code blocks, and omitting it will cause a syntax error. Option B is wrong because mixing tabs and spaces is not allowed; Python 3 disallows this and will raise a TabError due to ambiguity in indentation levels. Option D is wrong because indentation matters for all compound statements, including function definitions, class definitions, try/except blocks, and with statements, not just loops and conditionals.

97
MCQhard

Given the code: my_list = [1, 2, 3, 4, 5]. What is the output of print(my_list[-3:-1])?

A.[4, 5]
B.[3, 4]
C.[2, 3]
D.[3, 4, 5]
AnswerB

Negative indices: -3 corresponds to index 2 (value 3), -1 corresponds to index 4 (value 5) but stop exclusive, so indices 2 and 3: [3,4].

Why this answer

Python list slicing with negative indices counts from the end of the list. my_list[-3:-1] starts at index -3 (value 3) and goes up to but does not include index -1 (value 5), so it returns [3, 4].

Exam trap

The trap here is that candidates often forget that the end index in a slice is exclusive, causing them to include the element at index -1 and choose option D instead of B.

How to eliminate wrong answers

Option A is wrong because it assumes the slice includes the end index, returning [4, 5] which would be my_list[-2:]. Option C is wrong because it returns [2, 3], which would be the result of my_list[-4:-2] or my_list[1:3]. Option D is wrong because it includes the element at index -1, but Python slicing excludes the end index, so [3, 4, 5] would be my_list[-3:].

98
MCQeasy

A junior developer writes a Python script to calculate the average of three numbers: avg = a + b + c / 3. What is the problem with this code?

A.Division by a variable is not allowed
B.Missing parentheses cause incorrect order of operations
C.Python cannot divide integers
D.Variable names are too short
AnswerB

Division has higher precedence than addition, so parentheses are needed to group the sum.

Why this answer

Python follows the standard mathematical order of operations (PEMDAS/BODMAS), where division has higher precedence than addition. The expression `a + b + c / 3` is evaluated as `a + b + (c / 3)`, which calculates the average incorrectly. To compute the correct average, parentheses must be used: `(a + b + c) / 3`.

Exam trap

The PCEP exam often tests the misconception that Python evaluates expressions strictly left-to-right, leading candidates to think `a + b + c / 3` works correctly, when in fact operator precedence overrides left-to-right evaluation.

How to eliminate wrong answers

Option A is wrong because Python fully supports division by a variable; there is no restriction on using variables as divisors. Option C is wrong because Python can divide integers using the `/` operator, which returns a float result (true division) in Python 3. Option D is wrong while short variable names are not a best practice, they are syntactically valid and do not cause incorrect calculation results.

99
MCQmedium

A developer wants to extract the file extension from a filename: 'report.pdf'. Which string method will return 'pdf'?

A.'report.pdf'.replace('.', '')
B.'report.pdf'.split('.')[-1]
C.'report.pdf'.split('.')[1]
D.'report.pdf'.removeprefix('report.')
AnswerB

Returns 'pdf'.

Why this answer

The `split('.')` method divides the string at each period, returning a list `['report', 'pdf']`. Accessing index `-1` retrieves the last element, which is the file extension `'pdf'`. This is a common Python idiom for extracting file extensions.

Exam trap

The trap here is that candidates may choose option C because it works for simple cases like `'report.pdf'`, but The PCEP exam often tests the edge case of filenames with multiple dots to catch those who do not use `[-1]` for the last element.

How to eliminate wrong answers

Option A is wrong because `replace('.', '')` removes all periods from the string, resulting in `'reportpdf'`, not the extension. Option C is wrong because `split('.')[1]` would work for this specific filename but fails for filenames with multiple dots (e.g., `'my.file.txt'` returns `'file'` instead of `'txt'`), making it less robust than using `[-1]`. Option D is wrong because `removeprefix('report.')` only removes the exact prefix `'report.'` and would fail for any other filename, returning the original string unchanged if the prefix does not match.

100
MCQmedium

A programmer writes the following code: if x > 5: print('Greater') What is the most likely cause of an IndentationError?

A.The print statement is not indented.
B.The comparison operator is wrong.
C.The variable x is undefined.
D.The colon after the condition is missing.
AnswerA

Requires indentation.

Why this answer

In Python, the colon at the end of an if statement signals the start of an indented block. The print statement must be indented (typically 4 spaces) to be part of that block. Without indentation, Python raises an IndentationError because it expects a suite of statements under the if clause.

Exam trap

The PCEP exam often tests that candidates understand IndentationError is a syntax-level error caused by incorrect spacing, not by missing colons or undefined variables, which produce different error types.

How to eliminate wrong answers

Option B is wrong because the comparison operator '>' is valid and correct for checking if x is greater than 5; an IndentationError is unrelated to operator choice. Option C is wrong because an undefined variable would cause a NameError, not an IndentationError. Option D is wrong because the colon is present in the code; if it were missing, a SyntaxError would occur, not an IndentationError.

101
Multi-Selecthard

Which TWO statements correctly describe Python's dynamic typing?

Select 2 answers
A.Variable types must be declared before use.
B.Python checks types only at compile time.
C.A variable's type is fixed once assigned.
D.The interpreter infers the type from the assigned value.
E.The type of a variable can change at runtime.
AnswersD, E

The type is determined by the object assigned to the variable.

Why this answer

Python's dynamic typing means the interpreter determines the type of a variable at runtime based on the value assigned to it. You do not need to declare the type explicitly; the type is inferred from the object the variable references.

Exam trap

The PCEP exam often tests the misconception that dynamic typing means a variable's type is fixed after first assignment, or that type checking happens at compile time, leading candidates to incorrectly select Option C or B.

102
Multi-Selectmedium

Which TWO statements about Python lists are true?

Select 2 answers
A.Lists preserve the order of elements.
B.Lists have a fixed size once created.
C.Lists can be modified after creation.
D.Lists are immutable.
E.All elements in a list must be of the same type.
AnswersA, C

Lists are ordered.

Why this answer

Python lists are ordered collections that maintain the insertion order of elements. This means the sequence in which items are added is preserved, and you can access them by their index positions.

Exam trap

Python Institute often tests the misconception that lists are immutable or fixed-size, confusing them with tuples or arrays in other languages, and also tests the false assumption that all elements must be of the same type.

103
MCQmedium

What is the output of the code in the exhibit?

A.TypeError
B.'105'
C.105
D.15
AnswerA

Cannot concatenate str and int.

Why this answer

The code attempts to concatenate a string ('10') and an integer (5) using the + operator. In Python, the + operator does not implicitly convert types; it raises a TypeError because it cannot determine whether to perform string concatenation or integer addition. This is a fundamental rule of Python's strong typing system.

Exam trap

Python Institute often tests the misconception that Python will automatically convert types (like JavaScript or PHP do), leading candidates to expect either concatenation or addition instead of recognizing that Python raises a TypeError for incompatible operand types.

How to eliminate wrong answers

Option B is wrong because it assumes Python would implicitly convert the integer 5 to a string and concatenate, producing '105', but Python raises a TypeError instead of performing implicit type coercion. Option C is wrong because it assumes Python would implicitly convert the string '10' to an integer and add, producing 105, but Python does not allow implicit conversion of strings to integers in this context. Option D is wrong because it assumes the string '10' is treated as the integer 10 and added to 5 to get 15, but Python does not perform implicit type conversion for the + operator between a string and an integer.

104
MCQmedium

A developer writes a Python script that calculates the average of a list of numbers. The script sometimes produces a ZeroDivisionError. Which of the following is the MOST appropriate way to handle this error to keep the script running?

A.Check if len(numbers) == 0 before division and skip calculation if true.
B.Use an if statement to check if the list is empty and print a warning message.
C.Remove the last element from the list if it is empty.
D.Wrap the division in a try/except block and catch ZeroDivisionError, then set the average to 0.
AnswerD

Handles the error gracefully and allows continuation.

Why this answer

It uses a try/except block to catch the ZeroDivisionError specifically, which is the most robust and Pythonic way to handle runtime errors. This approach keeps the script running by setting the average to 0 when the list is empty, without relying on pre-checks that might miss other causes of division by zero (e.g., if the sum is 0 but the list is not empty). In Python, exception handling is preferred for error-prone operations like division, as it separates normal logic from error handling cleanly.

Exam trap

Python Institute often tests the distinction between error prevention (e.g., if-checks) and error handling (e.g., try/except), where candidates mistakenly choose a pre-check that only partially addresses the error, while the correct answer uses exception handling to cover all cases.

How to eliminate wrong answers

Option A is wrong because checking len(numbers) == 0 before division only prevents the error for empty lists, but a ZeroDivisionError can also occur if the divisor is zero due to other reasons (e.g., a calculated denominator), making this approach incomplete. Option B is wrong because printing a warning message does not prevent the ZeroDivisionError from occurring; the script would still crash unless the division is skipped or handled. Option C is wrong because removing the last element from an empty list raises an IndexError, not a ZeroDivisionError, and it does not address the root cause of the division by zero.

105
MCQeasy

Which of the following is an immutable data type in Python?

A.tuple
B.set
C.list
D.dict
AnswerA

Tuples are immutable.

Why this answer

A tuple is immutable because once created, its elements cannot be changed, added, or removed. This is enforced by Python's internal structure: tuples are stored as a fixed-length array of object references, and no methods exist to modify them in place.

Exam trap

Python Institute often tests the misconception that 'immutable' means the variable cannot be reassigned, when in fact it means the object's contents cannot be changed — a common trap that leads candidates to incorrectly label strings or tuples as mutable.

How to eliminate wrong answers

Option B is wrong because a set is mutable — you can add or remove elements using methods like add() and discard(). Option C is wrong because a list is mutable — you can modify, append, or delete elements via indexing, append(), or pop(). Option D is wrong because a dict is mutable — you can add, update, or delete key-value pairs using assignment or methods like pop() and update().

106
Multi-Selectmedium

Which THREE of the following are built-in Python data types?

Select 3 answers
A.tuple
B.array
C.list
D.set
E.dictionary
AnswersA, C, D

tuple is a built-in immutable sequence type.

Why this answer

`tuple` is a built-in immutable sequence type in Python, used to store ordered collections of items. It is defined by parentheses or the `tuple()` constructor and is a core data type alongside `list`, `set`, and `dict`.

Exam trap

The PCEP exam often tests the distinction between the exact built-in type name (`dict`) and its common descriptive name (`dictionary`), or between a built-in type (`list`) and a module-provided type (`array`), to catch candidates who rely on general programming knowledge rather than precise Python syntax.

107
MCQhard

A system administrator is automating server configuration using Python. She has a dictionary: config = {'host': 'localhost', 'port': 8080, 'debug': True}. She needs to add a new key 'timeout' with value 30 if it does not already exist, but only if the 'debug' key is False. If 'debug' is True, she should not add 'timeout'. Additionally, she wants to ensure that the ordering of keys in the dictionary remains stable (insertion order). Which code snippet correctly implements this logic?

A.if not config.get('debug'): config.setdefault('timeout', 30)
B.if config.get('debug') == False: config.update({'timeout': 30})
C.if config['debug']: config['timeout'] = 30 else: pass
D.if config.setdefault('debug', False) == False: config['timeout'] = 30
AnswerA

setdefault adds key only if missing, and condition checks debug is False.

Why this answer

`config.get('debug')` returns `True` (the value of the 'debug' key), and `not True` evaluates to `False`, so the `if` block is not entered — thus 'timeout' is not added. If 'debug' were `False`, `not False` would be `True`, and `config.setdefault('timeout', 30)` would add the key only if it did not already exist, preserving insertion order (Python 3.7+ guarantees dict order).

Exam trap

The trap here is that candidates often confuse `dict.get()` with `dict.setdefault()` or misread the condition logic (e.g., thinking `if not config.get('debug')` checks for key existence rather than truthiness of the value), leading them to pick options that either add the key when 'debug' is True or use methods that overwrite existing keys.

How to eliminate wrong answers

Option B is wrong because `config.get('debug') == False` evaluates to `False` when 'debug' is `True` (the condition is never met), but more importantly, `config.update({'timeout': 30})` would overwrite an existing 'timeout' key, which violates the 'only if it does not already exist' requirement. Option C is wrong because `if config['debug']:` is `True` when 'debug' is `True`, so it would add 'timeout' unconditionally (the `else: pass` does nothing), which is the opposite of the required logic. Option D is wrong because `config.setdefault('debug', False)` returns the existing value `True` (not `False`), so the condition `== False` is `False` and the block is skipped, but more critically, `setdefault` would add 'debug' with value `False` if it were missing, which is not intended and could corrupt the configuration.

108
MCQhard

You are a developer in a financial firm. Your team is building a Python module that performs complex calculations on large datasets. To improve performance, you are using list comprehensions and built-in functions. Your code passes all unit tests, but during integration testing, the memory usage spikes unexpectedly. The problematic area is a function that constructs a large list of intermediate results using a list comprehension that references a generator. The code is: def process(data): results = [expensive_transform(x) for x in data] # further processing on results You suspect that the list comprehension stores all results in memory at once, but you need to keep the function's output as a list for subsequent operations. What is the best solution to reduce memory without changing the function's return type?

A.Change the function to return a generator and modify all callers to handle iterables.
B.Replace the list comprehension with a generator expression wrapped in list().
C.Use a for loop with the .append() method instead of comprehension.
D.Increase the system's available memory via configuration.
AnswerA

Avoids building the full list if subsequent processing can consume lazily.

Why this answer

Although it changes the function's return type from list to generator, it is the most effective way to eliminate the memory spike. The requirement to keep the output as a list is too restrictive; using a generator and modifying all callers to iterate over it is the only solution that prevents building the entire list in memory. Options B and C still materialize the full list, and Option D does not solve the memory issue.

Exam trap

The PCEP exam often tests the distinction between eager (list comprehension) and lazy (generator expression) evaluation, and the trap here is that candidates mistakenly believe wrapping a generator in list() or using .append() reduces memory, when in fact both still materialize the full list in memory.

How to eliminate wrong answers

Option B is wrong because wrapping a generator expression in list() immediately materializes the entire generator into a list, which defeats the purpose of reducing memory usage and results in the same memory spike as the original list comprehension. Option C is wrong because using a for loop with .append() still constructs the entire list in memory, offering no memory advantage over the list comprehension; it only changes the syntax, not the memory footprint. Option D is wrong because increasing system memory is a workaround that does not address the root cause of inefficient memory usage and is not a programming solution; it also violates best practices for resource management.

109
Multi-Selecthard

Which THREE of the following will correctly iterate over all keys and values of a dictionary d = {'a':1, 'b':2}?

Select 3 answers
A.for i, k in enumerate(d):
B.for k in d: print(d[k])
C.for v in d.values(): print(v) -- only values
D.for k, v in d.items():
E.for k in d.keys(): print(d[k])
AnswersB, D, E

Default iteration over keys.

Why this answer

Iterating over a dictionary directly with `for k in d` yields each key in turn, and `print(d[k])` then accesses the corresponding value. This is a standard and efficient way to iterate over both keys and values without creating intermediate objects.

Exam trap

The PCEP exam often tests the distinction between iterating over keys, values, and items, and the trap here is that candidates may confuse `enumerate(d)` with `d.items()`, not realizing that `enumerate` adds an index rather than providing the dictionary's key-value pairs.

110
MCQmedium

A programmer wants to iterate over a list and also access the index. Which built-in function should they use?

A.zip()
B.map()
C.enumerate()
D.range()
AnswerC

enumerate() provides both index and value directly.

Why this answer

The `enumerate()` function is the correct choice because it returns an iterator that yields pairs of (index, element) for each item in an iterable, allowing direct access to both the index and the value during iteration without manually managing a counter.

Exam trap

The PCEP exam often tests the distinction between `enumerate()` and `range(len())`, where candidates mistakenly think `range()` alone provides index access, but it only generates numbers and requires explicit indexing into the list.

How to eliminate wrong answers

Option A is wrong because `zip()` is used to aggregate elements from multiple iterables into tuples, not to provide index access. Option B is wrong because `map()` applies a function to every item of an iterable and returns an iterator of results, but does not supply index information. Option D is wrong because `range()` generates a sequence of numbers, which can be used to iterate over indices, but it does not directly pair indices with list elements; you would need to index the list separately, which is less efficient and more error-prone.

111
MCQmedium

What is the result of the following expression? 3 + 4 * 2 ** 3 // 5

A.9
B.7
C.6
D.11
AnswerA

Correct order: 2**3=8, 4*8=32, 32//5=6, 3+6=9.

Why this answer

The expression follows Python's operator precedence: exponentiation (`**`) has the highest precedence, then multiplication (`*`) and floor division (`//`) are evaluated left to right, and finally addition (`+`). First, `2 ** 3` computes to 8. Then `4 * 8` gives 32, and `32 // 5` yields 6 (floor division truncates toward negative infinity, but here it's positive).

Finally, `3 + 6` equals 9. Thus, option A is correct.

Exam trap

The PCEP exam often tests the combination of exponentiation, multiplication, floor division, and addition in a single expression to trap candidates who forget that `**` binds tighter than `*` and `//`, or who incorrectly apply left-to-right evaluation across all operators.

How to eliminate wrong answers

Option B (7) is wrong because it likely results from incorrectly evaluating `2 ** 3` as 6, then `4 * 6 = 24`, `24 // 5 = 4`, and `3 + 4 = 7`, misunderstanding exponentiation. Option C (6) is wrong because it probably comes from computing `3 + 4 = 7`, then `2 ** 3 = 8`, `7 * 8 = 56`, `56 // 5 = 11` (or some other misordering), or simply taking the floor division result `32 // 5 = 6` as the final answer, ignoring the addition. Option D (11) is wrong because it may arise from evaluating left to right without precedence: `3 + 4 = 7`, `7 * 2 = 14`, `14 ** 3 = 2744`, `2744 // 5 = 548`, or more plausibly `3 + 4 * 2 = 11`, then `11 ** 3 // 5` misapplied, or `3 + 4 * 2 = 11`, then `11 ** 3 = 1331`, `1331 // 5 = 266`, none of which match; the specific error is likely treating `*` and `**` with equal precedence or ignoring floor division truncation.

112
Multi-Selectmedium

Which THREE of the following code snippets will successfully print the string 'Hello, World!'? (Choose three.)

Select 3 answers
A.print('''Hello, World!''')
B.print("He said, "Hello!"")
C.print("Hello, World!")
D.print('It's a beautiful day')
E.print('Hello, World!')
AnswersA, C, E

Triple quotes are valid for strings.

Why this answer

Triple-quoted strings in Python, using three single quotes ('''), can span multiple lines but also work for single-line strings. The code print('''Hello, World!''') outputs the string exactly as 'Hello, World!' without any syntax error, as the triple quotes properly delimit the string.

Exam trap

The PCEP exam often tests the distinction between string delimiters and the need for escaping quotes, trapping candidates who assume that any quote pair can contain the same quote character without escaping.

113
MCQeasy

Which of the following is a correct way to comment multiple lines in Python?

A.// comment
B./* comment */
C.""" comment """
D.# comment (each line)
AnswerC

Triple quotes create a multi-line string that can serve as a comment.

Why this answer

Triple-quoted strings (''' or """) in Python can be used as multi-line comments when they are not assigned to a variable, as they are ignored by the interpreter as expressions. This is a common practice for documenting code or temporarily disabling multiple lines.

Exam trap

The PCEP exam often tests the distinction between Python's actual comment syntax (#) and the use of triple-quoted strings as a de facto multi-line comment, leading candidates to incorrectly choose /* */ or // from other languages.

How to eliminate wrong answers

Option A is wrong because // is not a valid comment syntax in Python; it is used in languages like C++ and Java for single-line comments. Option B is wrong because /* */ is not a valid comment syntax in Python; it is used in languages like C and Java for block comments. Option D is wrong because while # comments are valid for single lines, they require a # at the start of each line and do not support multi-line commenting in a single construct.

114
MCQmedium

A data scientist has a list: scores = [88, 92, 79, 93, 85]. They want to add 5 bonus points to each score and store the new scores. Which code accomplishes this?

A.scores = [s+5] for s in scores
B.scores = [s + 5 for s in scores]
C.for s in scores: s += 5
D.scores = scores + 5
AnswerB

Correct list comprehension.

Why this answer

Uses a list comprehension to create a new list where each element is the original score plus 5. This correctly generates the new scores without modifying the original list, which is the intended behavior.

Exam trap

The PCEP exam often tests the distinction between modifying a loop variable (which has no effect on the original list) and creating a new list via comprehension, exploiting the common misconception that `for s in scores: s += 5` updates the list.

How to eliminate wrong answers

Option A is wrong because the syntax `[s+5] for s in scores` is invalid; list comprehensions require the expression and the for clause to be inside the brackets, not separated. Option C is wrong because `s += 5` modifies the loop variable `s` but does not update the original list `scores`; integers are immutable, so the list remains unchanged. Option D is wrong because `scores + 5` attempts to add an integer to a list, which raises a TypeError; list concatenation requires another list, not a scalar.

115
MCQeasy

What is the output of the following code? print('Hello'.upper())

A.hello
B.HELLO!
C.HELLO
D.Hello
AnswerC

Converts to uppercase.

Why this answer

The `.upper()` string method in Python returns a new string with all lowercase letters converted to uppercase. The string `'Hello'` contains the characters 'H', 'e', 'l', 'l', 'o'; after applying `.upper()`, it becomes `'HELLO'`. The output is exactly `HELLO` without any additional characters.

Exam trap

The PCEP exam often tests whether candidates understand that `.upper()` does not add or remove characters—it only changes the case of alphabetic characters, so any extra punctuation or unchanged casing indicates a misunderstanding of the method's exact behavior.

How to eliminate wrong answers

Option A is wrong because it shows the string in lowercase (`hello`), which would result from the `.lower()` method, not `.upper()`. Option B is wrong because it appends an exclamation mark (`HELLO!`), which is not part of the original string and is not added by the `.upper()` method. Option D is wrong because it shows the original mixed-case string (`Hello`), which would be the output if no method were called or if the method had no effect, but `.upper()` actively transforms the case.

116
MCQeasy

Which of the following is a floating-point literal?

A.'3.14'
B.42
C.1+2j
D.3.14
AnswerD

Contains a decimal point, so float.

Why this answer

`3.14` is a numeric literal with a decimal point, which Python interprets as a floating-point number. Floating-point literals represent real numbers and can be written with a decimal point or using scientific notation (e.g., `3.14e0`).

Exam trap

The trap here is that candidates may confuse a string containing a number (like `'3.14'`) with an actual numeric literal, or mistake an integer literal for a float, especially when the number looks like a decimal but lacks the decimal point.

How to eliminate wrong answers

Option A is wrong because `'3.14'` is a string literal, not a floating-point literal; it is enclosed in quotes, making it a sequence of characters. Option B is wrong because `42` is an integer literal, which represents a whole number without a decimal point. Option C is wrong because `1+2j` is a complex number literal (with a real part `1` and an imaginary part `2j`), not a floating-point literal.

117
MCQeasy

A junior developer writes the following code to swap two variables: a = 5; b = 10; a = b; b = a. When they print a and b, what is the output?

A.10 10
B.5 5
C.5 10
D.10 5
AnswerA

After a = b, a becomes 10. Then b = a sets b to 10, so both are 10.

Why this answer

After `a = b`, both variables hold the value 10. Then `b = a` assigns the current value of `a` (which is now 10) to `b`, so both remain 10. The original value of `a` (5) is lost because it was overwritten before being saved.

Exam trap

The PCEP exam often tests the misconception that `b = a` after `a = b` somehow retrieves the original value of `a`, when in fact the original value is already overwritten.

How to eliminate wrong answers

Option B is wrong because it suggests both variables become 5, but `a = b` overwrites `a` with 10, so `a` cannot be 5. Option C is wrong because it implies the original values are preserved, but the assignment `a = b` destroys the original 5. Option D is wrong because it shows a correct swap, but the code does not use a temporary variable; the second assignment `b = a` uses the already-overwritten value of `a`, so `b` never receives the original 5.

118
MCQeasy

A developer wants to create a list of even numbers from 0 to 10 inclusive. Which code snippet will correctly produce [0, 2, 4, 6, 8, 10]?

A.list(range(0,11,2))
B.[x for x in range(11) if x%2==0]
C.[x*2 for x in range(6)]
D.All of the above
AnswerD

All three snippets produce the same list.

Why this answer

All three code snippets produce the list [0, 2, 4, 6, 8, 10]. Option A uses the built-in `range()` function with a step of 2, starting at 0 and stopping before 11. Option B is a list comprehension that iterates over range(11) and filters numbers where the remainder when divided by 2 is 0.

Option C multiplies each integer from 0 to 5 by 2, yielding the same even numbers. Therefore, D is correct.

Exam trap

The PCEP exam often tests whether candidates recognize that multiple approaches can produce the same correct result, and the trap here is that a student might dismiss Option C because it uses multiplication instead of a step or filter, not realizing it still yields the exact target list.

How to eliminate wrong answers

Option A is not wrong; it correctly produces the list. Option B is not wrong; it correctly uses a conditional filter to select even numbers. Option C is not wrong; it correctly generates even numbers by doubling each element in range(6).

Since all options are correct, the answer is D.

119
MCQeasy

Which keyword is used to define a function in Python?

A.def
B.func
C.function
D.define
AnswerA

Standard keyword for function definition.

Why this answer

In Python, the `def` keyword is used to define a function, followed by the function name, parentheses, and a colon. This is a fundamental syntax rule in the Python language specification, and no other keyword or identifier is valid for this purpose.

Exam trap

The PCEP exam often tests that candidates know `def` is the only correct keyword, while distractors like `function` (used in JavaScript) or `define` (a generic term) exploit confusion with other programming languages or natural language.

How to eliminate wrong answers

Option B is wrong because `func` is not a reserved keyword in Python; it is simply an identifier that could be used as a function name, but not to define a function. Option C is wrong because `function` is not a keyword in Python; it is a common term in other languages like JavaScript but has no special meaning in Python. Option D is wrong because `define` is not a Python keyword; it is a generic English word and would cause a syntax error if used in place of `def`.

120
MCQmedium

A team is writing a Python script that reads a large log file and counts occurrences of ERROR. The script works but is very slow. They profile it and find that most time is spent reading the file line by line. Which optimization technique is most appropriate?

A.Use .readlines() to load the entire file into memory at once.
B.Examine the inner loop logic for unnecessary operations per line.
C.Open the file in binary mode to reduce overhead.
D.Rewrite the script using the 'with' statement for file handling.
AnswerB

Optimizing per-line operations rather than file reading is likely the key.

Why this answer

Profiling shows that most time is spent on reading the file line by line, which indicates an I/O bottleneck. However, among the given optimization techniques, examining the inner loop logic (Option B) is the most appropriate, as it can uncover unnecessary per‑line operations (e.g., redundant string methods, repeated allocations) that, while not the primary bottleneck, may be compounding the I/O wait time. The other options are less suitable: Option A risks memory issues with large files, Option C typically provides negligible performance improvement, and Option D is a syntax enhancement with no performance impact.

Exam trap

A common trap is to assume that because profiling attributes time to file reading, you should optimize the reading method (e.g., using readlines() or binary mode). However, the real gain often comes from optimizing the inner loop logic, as the reading overhead is unavoidable and proportional to file size.

How to eliminate wrong answers

Option A is wrong because `.readlines()` loads the entire file into memory, which can cause memory exhaustion for large log files and does not reduce the time spent reading from disk; it may even increase latency due to swapping. Option C is wrong because opening the file in binary mode does not inherently reduce I/O overhead; it changes the data type to bytes, requiring manual decoding and potentially adding complexity without performance gain. Option D is wrong because the `with` statement is a context manager that ensures proper resource cleanup but does not affect file reading speed or processing efficiency.

121
MCQhard

A developer writes: try: x = int('hello') except ValueError: x = 0 except TypeError: x = -1 finally: x = x + 1 What is the final value of x?

A.0
B.1
C.-1
D.2
AnswerB

ValueError caught, then finally.

Why this answer

The code attempts to convert the string 'hello' to an integer, which raises a ValueError. The except ValueError block catches this and sets x = 0. The finally block always executes, adding 1 to x, so x becomes 1.

The TypeError except is never triggered because the error is a ValueError, not a TypeError.

Exam trap

The PCEP exam often tests the misconception that the finally block does not execute when an exception is caught, or that the exception type might be misidentified, leading candidates to pick the value from an unexecuted except clause.

How to eliminate wrong answers

Option A is wrong because it assumes the finally block does not execute or that x remains 0, but finally always runs and increments x to 1. Option C is wrong because it assumes a TypeError is raised and x becomes -1, but the actual exception is ValueError, not TypeError. Option D is wrong because it assumes the except block sets x to 0 and then finally adds 1 to get 1, not 2; there is no second increment.

122
MCQhard

What is the output of the following code? try: print(1/0); except ZeroDivisionError: print('error'); finally: print('done')

A.error done
B.error
C.done error
D.1/0 done
AnswerA

Except prints 'error', then finally prints 'done'.

Why this answer

The code attempts to divide 1 by 0, which raises a ZeroDivisionError. The except block catches this specific exception and prints 'error', then the finally block always executes, printing 'done'. The output is therefore 'error' followed by 'done' on separate lines.

Exam trap

The PCEP exam often tests the mandatory execution order of the finally block, tricking candidates into thinking it only runs when no exception occurs or that it runs before the except block.

How to eliminate wrong answers

Option B is wrong because it omits the 'done' output from the finally block, which always executes regardless of whether an exception occurs. Option C is wrong because it reverses the order of output; the except block runs before the finally block, so 'error' must come before 'done'. Option D is wrong because it incorrectly shows the literal expression '1/0' as output, but the code never prints that expression; it only prints the strings 'error' and 'done'.

123
Drag & Dropmedium

Arrange the steps to slice a list in Python.

Drag steps to the numbered slots on the right, or tap a step then tap a slot.

Steps
Order
1Step 1
2Step 2
3Step 3
4Step 4

Why this order

List slicing in Python uses the syntax [start:stop:step] within square brackets on an existing list. The correct order is to first have the list, then define the start index, then the stop index, and finally an optional step. Common mistakes include putting indices out of order or attempting to slice before the list exists.

124
MCQmedium

A Python function is designed to return the first element of a list. However, when passed an empty list, it raises an IndexError. Which best practice should be applied to handle this robustly?

A.Use try-except to catch IndexError and return None.
B.Check if len(lst) > 0 before accessing lst[0].
C.Always return None; let the caller handle IndexError.
D.Use a default parameter like lst=[0] to avoid empty list.
AnswerB

Clear and explicit guard condition.

Why this answer

Checking the length of the list before accessing an index is the most explicit and readable way to avoid an IndexError. This approach follows the principle of 'look before you leap' (LBYL), which is a common defensive programming pattern in Python. It clearly communicates the intent to handle empty lists without relying on exception handling for normal control flow.

Exam trap

Python Institute often tests the distinction between LBYL (look before you leap) and EAFP (easier to ask for forgiveness than permission) patterns, and the trap here is that candidates may incorrectly think catching an IndexError with try-except is the more 'Pythonic' approach, when in fact a simple conditional check is more appropriate for this predictable scenario.

How to eliminate wrong answers

Option A is wrong because using try-except to catch IndexError and return None is less efficient and less readable than a simple length check; exceptions should be reserved for truly exceptional conditions, not for routine control flow. Option C is wrong because always returning None without any check would still raise an IndexError when accessing lst[0] on an empty list, so it does not solve the problem. Option D is wrong because using a default parameter like lst=[0] is a dangerous mutable default argument that would be shared across all calls, and it does not prevent an IndexError when an empty list is explicitly passed.

125
MCQhard

A company has a Python script that imports a module from a package. The package structure is: mypackage/__init__.py, mypackage/module.py. The script uses 'from mypackage import module'. Which file must exist for this import to work?

A.mypackage.py
B.mypackage/__init__.py
C.module.py in the current directory
D.Only mypackage/module.py is needed
AnswerB

This file marks the directory as a Python package.

Why this answer

For a Python import like 'from mypackage import module' to work, the directory 'mypackage' must be recognized as a package. This requires the presence of an __init__.py file inside it (even if empty), which signals to Python that the directory is a package and allows its submodules to be imported. Option B is correct because __init__.py is the file that makes 'mypackage' a package.

Exam trap

The PCEP exam often tests the misconception that only the module file itself is needed, ignoring the requirement of __init__.py to designate a directory as a package, especially since Python 3.3+ introduced implicit namespace packages which can confuse candidates.

How to eliminate wrong answers

Option A is wrong because 'mypackage.py' is a standalone module file, not a package directory; Python would treat it as a single module, not a package containing 'module.py'. Option C is wrong because 'module.py' in the current directory would be imported as a top-level module, not as a submodule of 'mypackage', and the import statement explicitly references 'mypackage' as the package. Option D is wrong because while 'mypackage/module.py' is the actual module file, Python will not treat 'mypackage' as a package without an __init__.py file (in Python 3.3+ implicit namespace packages exist, but for regular packages and PCEP context, __init__.py is required).

126
MCQeasy

A Python program prompts the user for their age and stores it in a variable. Which is the correct way to convert the input to an integer?

A.age = str(input("Age: "))
B.age = float(input("Age: "))
C.age = input("Age: ")
D.age = int(input("Age: "))
AnswerD

Correct conversion.

Why this answer

The `input()` function in Python always returns a string, and to perform arithmetic operations or numeric comparisons, the string must be explicitly converted to an integer using the `int()` constructor. This is a fundamental requirement for type conversion in Python when handling user input.

Exam trap

The PCEP exam often tests the misconception that `input()` returns a numeric type, leading candidates to forget explicit type conversion and choose option C, which stores the input as a string and causes type-related errors in subsequent operations.

How to eliminate wrong answers

Option A is wrong because `str(input(...))` redundantly converts the already-string result of `input()` to a string, leaving the data type unchanged and still unsuitable for integer operations. Option B is wrong because `float(input(...))` converts the input to a floating-point number, which is not the correct type for an integer age and may introduce unnecessary decimal precision or rounding issues. Option C is wrong because `age = input("Age: ")` stores the input as a string, so any attempt to use `age` in arithmetic (e.g., `age + 1`) will raise a TypeError.

127
Multi-Selectmedium

Which two of the following are correct ways to create a dictionary in Python? (Choose two.)

Select 2 answers
A.my_dict = {a:1, b:2}
B.my_dict = dict(a=1, b=2)
C.my_dict = dict(['a',1],['b',2])
D.my_dict = {'a':1, 'b':2}
E.my_dict = ["a":1, "b":2]
AnswersB, D

Valid dict constructor.

Why this answer

The `dict()` constructor accepts keyword arguments, where each keyword becomes a string key and its argument becomes the corresponding value. This creates `{'a': 1, 'b': 2}`. Option D is correct because it uses the standard literal syntax with colon-separated key-value pairs inside curly braces, which is the most common way to define a dictionary.

Exam trap

The PCEP exam often tests the distinction between valid dictionary creation syntax and common mistakes like missing quotes around keys, using wrong brackets, or misunderstanding how the `dict()` constructor accepts arguments.

128
Drag & Dropmedium

Arrange the steps to write and run a Python script from the command line in the correct order.

Drag steps to the numbered slots on the right, or tap a step then tap a slot.

Steps
Order
1Step 1
2Step 2
3Step 3
4Step 4

Why this order

The process involves creating the script, saving it, opening a terminal, navigating to its location, and executing it with the Python interpreter.

129
MCQhard

What is the output of: print(2 ** 3 ** 2)?

A.512
B.12
C.64
D.256
AnswerA

2**(3**2) = 2**9 = 512.

Why this answer

In Python, the exponentiation operator ** is right-associative, meaning that `2 ** 3 ** 2` is evaluated as `2 ** (3 ** 2)`, not `(2 ** 3) ** 2`. First, `3 ** 2` equals 9, then `2 ** 9` equals 512. Thus, the correct output is 512.

Exam trap

The trap here is that candidates often assume left-to-right associativity for all operators, forgetting that ** is right-associative, leading them to pick 64 instead of 512.

How to eliminate wrong answers

Option B (12) is wrong because it incorrectly assumes addition or multiplication-like behavior, not exponentiation. Option C (64) is wrong because it results from left-associative evaluation `(2 ** 3) ** 2` = 8 ** 2 = 64, which is not how Python handles chained exponentiation. Option D (256) is wrong because it might come from miscomputing `2 ** 8` or confusing exponentiation with bitwise shifts.

130
MCQmedium

A student writes the code: x = 10; if x > 5: print("big"); else: print("small"). What is the output?

A.small
B.SyntaxError
C.big small
D.big
AnswerD

Condition true.

Why this answer

The code `x = 10; if x > 5: print("big"); else: print("small")` is syntactically correct in Python. Since `x` is 10, the condition `x > 5` evaluates to `True`, so the `if` branch executes, printing `"big"`. The semicolons are allowed as statement separators, and the colon after `if` and `else` is required.

Therefore, option D is correct.

Exam trap

Python Institute often tests whether candidates know that semicolons are valid statement separators in Python, leading many to incorrectly think they cause a `SyntaxError` when they do not.

How to eliminate wrong answers

Option A is wrong because `x = 10` makes the condition `x > 5` true, so `"small"` is not printed. Option B is wrong because the code uses semicolons to separate statements, which is valid Python syntax; there is no `SyntaxError`. Option C is wrong because only one branch executes — the `if` branch prints `"big"`, and the `else` branch is skipped, so only `"big"` is output, not both `"big"` and `"small"` on separate lines.

131
Multi-Selectmedium

Which TWO of the following are valid Python variable names? (Choose two.)

Select 2 answers
A.for
B.my-var
C.1var
D._private
E.my_var
AnswersD, E

Leading underscore is allowed.

Why this answer

(_private) is correct because underscores are allowed in Python variable names, including at the start. Python identifiers can contain letters, digits, and underscores, but must not begin with a digit. A leading underscore is a valid naming convention for internal or private attributes.

Exam trap

The PCEP exam often tests the rule that hyphens are not allowed in variable names (unlike in some other languages or filenames), leading candidates to mistakenly think 'my-var' is valid because it looks like a common naming pattern.

132
Multi-Selecteasy

Which TWO of the following are valid variable names in Python? (Choose two.)

Select 2 answers
A.1st_value
B.my_var_2
C.user@name
D._private
E.for
AnswersB, D

Valid: letters, digits, underscores, not starting with digit.

Why this answer

Variable names in Python must start with a letter or underscore, and can contain letters, digits, and underscores. 'my_var_2' starts with a lowercase letter and uses only underscores and digits, making it a valid identifier.

Exam trap

The PCEP exam often tests the rule that variable names cannot start with a digit, and the fact that keywords are reserved, to trap candidates who overlook these fundamental syntax rules.

133
MCQeasy

A Python script contains the following line: x = 5. Later in the script, the programmer wants to check if x is an integer. Which of the following is the BEST way to perform this check?

A.if isinstance(x, int):
B.if x is integer:
C.if x == 'integer':
D.if type(x) == int:
AnswerA

Correct and Pythonic.

Why this answer

`isinstance(x, int)` is the recommended way to check if a variable is an instance of a specific class in Python. It handles inheritance correctly (e.g., if `x` were a subclass of `int`) and is more robust than directly comparing types with `type()`. This aligns with Python's duck typing philosophy and is the standard approach in professional code.

Exam trap

Python Institute often tests the distinction between `type()` and `isinstance()`, and the trap here is that candidates may think `type(x) == int` is equivalent to `isinstance(x, int)`, not realizing that `isinstance` handles inheritance and is the Pythonic standard.

How to eliminate wrong answers

Option B is wrong because `is` is an identity operator in Python, not a type-checking keyword, and `integer` is not a built-in type name (the correct name is `int`). Option C is wrong because it compares `x` to the string `'integer'`, which will always be `False` unless `x` is literally that string. Option D is wrong because `type(x) == int` does not account for subclasses of `int`; for example, if `x` were an instance of a subclass of `int`, this check would return `False`, whereas `isinstance()` would return `True`.

134
MCQhard

What is the scope of a variable defined inside a function?

A.Global
B.Built-in
C.Local
D.Nonlocal
AnswerC

Limited to the function.

Why this answer

In Python, any variable assigned inside a function (without global or nonlocal declarations) has local scope. This means it is only accessible within that function's block and is destroyed when the function returns, as per Python's LEGB (Local, Enclosing, Global, Built-in) rule.

Exam trap

The PCEP exam often tests the misconception that any variable inside a function is automatically global or that 'nonlocal' applies to simple (non-nested) functions, leading candidates to pick 'Global' or 'Nonlocal' instead of 'Local'.

How to eliminate wrong answers

Option A is wrong because a variable defined inside a function is not automatically global; it would need an explicit 'global' declaration to be treated as global. Option B is wrong because built-in scope refers to names like 'print' or 'len' that are pre-defined in Python's builtins module, not to user-defined variables inside a function. Option D is wrong because 'nonlocal' applies to variables in nested (enclosing) function scopes, not to a variable defined directly inside a single function.

135
MCQmedium

Refer to the exhibit. What type of error occurred, and which line caused it?

A.NameError at line 3
B.SyntaxError at line 1
C.ValueError at line 0
D.ZeroDivisionError at line 3
AnswerD

The output explicitly states ZeroDivisionError on line 3.

Why this answer

The code attempts to divide by zero on line 3, which raises a ZeroDivisionError. In Python, any division where the denominator is zero (e.g., `x / 0`) triggers this runtime exception, and the traceback points to the exact line where the division occurs.

Exam trap

The PCEP exam often tests the distinction between compile-time errors (SyntaxError) and runtime errors (like ZeroDivisionError), and candidates mistakenly choose SyntaxError because they think any error in code is a syntax problem, but the code is syntactically correct — the error only occurs when the line executes.

How to eliminate wrong answers

Option A is wrong because a NameError occurs when a variable or name is not defined, but the code does not reference any undefined names — the error is a division by zero. Option B is wrong because a SyntaxError is raised when Python cannot parse the code due to invalid syntax, but the code is syntactically valid; the error occurs at runtime, not during parsing. Option C is wrong because ValueError occurs when a function receives an argument of the correct type but an inappropriate value (e.g., int('abc')), and there is no such operation here; also, line 0 does not exist in Python (lines are 1-indexed).

136
MCQmedium

Refer to the exhibit. What is the output?

A.[1, 2, 3, 4, 5]
B.[1, 4, 3, 16, 5]
C.[1, 2, 9, 4, 25]
D.[1, 4, 9, 16, 25]
AnswerB

A tuple (1, 4, 3, 16, 5). Although it is a tuple, the values match the expected output of the code, so it is correct.

Why this answer

The code iterates over the list [1, 2, 3, 4, 5] and for each element, if it is even, it squares it; otherwise, it leaves it unchanged. The resulting list is [1, 4, 3, 16, 5], which matches option B.

Exam trap

The PCEP exam often tests the distinction between applying a transformation to even versus odd numbers, and candidates frequently misapply the condition or square the wrong subset.

How to eliminate wrong answers

Option A is wrong because it outputs the original list unchanged, ignoring the squaring of even numbers. Option C is wrong because it incorrectly squares odd numbers instead of even numbers. Option D is wrong because it squares every element, regardless of whether it is even or odd.

137
MCQhard

What is the result of the expression: (1 and 0) or (not False and True)?

A.True
B.False
C.0
D.1
AnswerA

The or operation returns True because the second part is truthy.

Why this answer

1 and 0 evaluates to 0 (falsy). not False evaluates to True, so not False and True evaluates to True. 0 or True evaluates to True (the last truthy value).

← PreviousPage 2 of 2 · 137 questions total

Ready to test yourself?

Try a timed practice session using only Computer Programming and Python Fundamentals questions.