Courseiva

CCNA Computer Programming and Python Fundamentals Questions

47 of 122 questions · Page 2/2 · Computer Programming and Python Fundamentals · Answers revealed

76
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

float is a built-in numeric type representing double-precision floating-point values, created via literals such as 3.14 or the float() constructor. It is distinct from int and complex, and is one of the three correct selections.

Why this answer

Option A (float) is correct because float is a built-in Python numeric type used to represent floating-point (decimal) numbers such as 3.14. Option B (list) is correct because list is a built-in Python sequence type that holds an ordered, mutable collection of items, e.g., [1, 2, 3]. Option D (dict) is correct because dict is a built-in Python mapping type that stores key-value pairs, e.g., {"a": 1}.

Option C (char) is not a Python data type; Python has no distinct char type and represents single characters as strings of length one. Option E (record) is not a built-in Python data type; record-like structures are typically emulated with dicts, tuples, or classes such as namedtuple or dataclass.

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.

77
MCQeasy

A Python script contains the following code: x = 10 y = 3 result = x // y What is the value of result after execution?

A.3.3333333333333335
B.1
C.4
D.3
AnswerD

The // operator performs floor division, dividing x by y and rounding down to the nearest integer. 10 divided by 3 is 3.333..., and floor division yields 3. Since both operands are integers, the result is an int. This is the correct value for result.

Why this answer

The // operator performs floor division, which divides the left operand by the right and rounds down to the nearest integer. With x=10 and y=3, 10 // 3 equals 3. The other options correspond to true division, rounding up, or modulo, none of which match the behavior of //.

Exam trap

The trap here is confusing floor division // with true division / or modulo %, especially when the result is a repeating decimal.

78
MCQeasy

A programmer needs to store the number of items in a shopping cart. The value will be a whole number and may be used in arithmetic operations. Which Python data type is most appropriate for this variable?

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

An int represents whole numbers without a fractional part, which fits the count of items in a cart. It supports arithmetic operations like addition or multiplication. Since the quantity is always a whole number, int avoids unnecessary decimal precision and is the idiomatic choice for counts.

Why this answer

The number of items in a cart is a whole number used in arithmetic, so int is the correct type. Floats are for decimal values and can introduce rounding, strings are text and would break calculations, and booleans only represent truth values. Using int keeps the data accurate and operations predictable.

Exam trap

The trap here is assuming any numeric type works, but float may cause rounding and str will concatenate instead of add.

79
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

`my_var` is valid because Python identifiers may contain letters, digits and underscores, provided they do not begin with a digit. The underscore sits between letters, satisfying the stem's requirement for a legal variable name. It is also not a reserved keyword, so the interpreter accepts it without error.

Why this answer

Option B, my_var, is a valid Python identifier because it starts with a letter and contains only letters and underscores, which are permitted characters. Option D, _count, is also valid because a leading underscore is allowed in Python variable names and the rest of the name consists of legal characters. Option A, my-var, is invalid because hyphens are not allowed in identifiers and would be parsed as subtraction.

Option C, 2nd_place, is invalid because identifiers cannot begin with a digit. Option E, class, is invalid because it is a reserved Python keyword and cannot be used as a variable name.

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.

80
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

Assignment binds y to the same list object as x, not a copy. Calling append(4) mutates that shared object in place, so both names observe the change and printing x outputs [1, 2, 3, 4].

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`.

81
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

A dictionary maps JSON objects directly: keys become strings and values become nested dictionaries, lists or scalars. This mirrors the exhibit's key-value pairs, satisfying the requirement to represent the configuration faithfully while allowing lookup by key rather than by positional index.

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.

82
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

Assigning `x = 5` inside `func` creates a new local variable, so the printed value within the function is 5. The module-level `x` remains 10, since Python resolves names by local-then-global scope and the assignment never rebinds the global. Hence the output is 5, then 10.

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.

83
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

Returning a, b packs the two values into a single tuple, which the caller can unpack directly. Python has no multi-value return type, so the tuple is the mechanism that satisfies the requirement to return multiple values from one function.

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.

84
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

Python's + operator does not coerce types, so adding int 3 to str '4' raises TypeError. The operands must share a compatible type for concatenation or addition, and no implicit conversion occurs between int and str.

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.

85
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

The empty parameter list satisfies the no-arguments constraint, and the bare `return 42` supplies the required value. Python permits a single-line suite after the colon, so this definition is syntactically valid and returns the integer 42 when called as `f()`.

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.

86
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

The division operator in Python 3 always performs true division, returning a float regardless of whether operands are integers. So 5 / 2 yields 2.5, typed as float, not int. Floor division (//) would return an integer instead.

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.

87
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

The built-in `input()` function reads a line from standard input, pauses execution until the user presses Enter, and returns the entered text as a string. This directly satisfies the Python 3 requirement, unlike `raw_input()`, which was renamed to `input()` in Python 3 and no longer exists.

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`.

88
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

Python uses indentation to delimit blocks, and every statement within the same block must share identical leading whitespace. Mixing tabs and spaces or varying indent width within one block raises an IndentationError, so consistency is mandatory rather than stylistic.

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.

89
MCQmedium

A developer writes the following code to sum a list of scores: scores = [12, 7, 25, 18] total = 0 for s in scores: total += s print(total) What is printed?

A.[12, 7, 25, 18]
B.62
C.12
D.0
AnswerB

The loop iterates over each element of scores and adds it to total using the augmented assignment +=. The running sum becomes 12, then 19, then 44, then 62. After the loop finishes, print displays the accumulated total, which is 62. This correctly sums all four values in the list.

Why this answer

The for loop visits every item in the scores list, and the augmented assignment total += s adds each score to the running sum. Starting from zero, the additions produce 12, 19, 44, and finally 62, which is the value printed after the loop completes.

Exam trap

The trap here is misreading total += s as an assignment that replaces total each pass, when it actually accumulates the running sum.

90
MCQhard

A programmer writes the following code to classify a temperature reading: temp = 25 if temp > 30: print('Hot') elif temp > 20: print('Warm') else: print('Cool') What is printed when this code runs?

A.Cool
B.Nothing is printed because the code has a syntax error.
C.Warm
D.Hot
AnswerC

The first condition temp > 30 evaluates to False because 25 is not greater than 30. The elif condition temp > 20 evaluates to True because 25 is greater than 20. Therefore, the block under elif executes, printing 'Warm'. The else block is skipped. This is the correct output.

Why this answer

The if-elif-else structure evaluates conditions top-down. Since temp is 25, the first condition (temp > 30) is false, the second (temp > 20) is true, so the 'Warm' branch executes. The else is bypassed.

The other outputs would occur only if the temperature fell into different ranges or if the code were invalid.

Exam trap

The trap here is misreading the boundary conditions or assuming the first condition is true without checking the actual value of temp.

91
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 count from the end, so -3 maps to index 2 (value 3) and -1 maps to index 4 (value 5). Slicing excludes the stop index, returning elements at positions 2 and 3, giving [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:].

92
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 binds tighter than addition, so a + b + c / 3 computes a + b + (c/3), not (a+b+c)/3. Wrapping the sum in parentheses restores the intended grouping, satisfying the stem's requirement for a correct average calculation across all three numbers.

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.

93
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

Python determines a variable's type at assignment time from the object bound to it, with no type declaration required. The interpreter infers the type from the assigned value, which is the mechanism underlying dynamic typing rather than static annotation.

Why this answer

Option D is correct because Python is dynamically typed: when you write an assignment such as x = 42, the interpreter determines the type of the object (int) from the value on the right-hand side at runtime, without any explicit type declaration. Option E is correct because a name in Python is just a reference to an object, so the same variable can be rebound to an object of a different type later, e.g., x = 42 followed by x = 'hello' changes x from int to str at runtime. Option A is wrong because Python requires no type declarations; types are attached to objects, not to variable names.

Option B is wrong because Python performs type checking at runtime, not at compile time (the CPython compiler only produces bytecode and does not enforce types). Option C is wrong because a variable's type is not fixed after assignment; rebinding the name to a new object of another type is perfectly legal.

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.

94
MCQeasy

A student types the following into a Python 3 interactive session: >>> greeting = 'Hello' >>> greeting = greeting + ' World' >>> print(greeting) What is displayed?

A.Hello
B.HelloWorld
C.Hello World
D.A TypeError is raised
AnswerC

The name greeting is first bound to the string 'Hello'. The assignment greeting = greeting + ' World' concatenates the two strings and rebinds the name to the new string 'Hello World'. print then displays that value. Strings are immutable, so a new string object is created rather than modifying the original.

Why this answer

The second statement evaluates the right-hand side first: greeting still refers to 'Hello', so 'Hello' + ' World' produces a new string containing the space, and the name greeting is rebound to that value. The subsequent print call therefore outputs the combined text. Because str objects are immutable, reassignment replaces the reference rather than altering the original object in place.

Exam trap

The trap here is assuming that reassigning a string variable modifies the original string object instead of creating a new one and rebinding the name.

95
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 sequences, so elements retain their insertion position and can be retrieved by index, satisfying the stem's requirement for a true statement. This contrasts with unordered collections such as sets and dictionaries, where iteration order is not guaranteed by the data type itself.

Why this answer

Option A is correct because Python lists are ordered sequences: elements are stored in a defined index order (starting at index 0), and iteration, indexing, and slicing return them in that insertion order. Option C is correct because lists are mutable: after creation you can change them in place with operations such as append(), insert(), remove(), pop(), sort(), or item assignment like lst[0] = 5. Option B is wrong because lists are dynamically sized; they grow and shrink automatically as elements are added or removed.

Option D is wrong because immutability describes tuples (and strings), not lists, which support in-place modification. Option E is wrong because Python lists are heterogeneous and may hold objects of different types, e.g., [1, 'two', 3.0].

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.

96
MCQeasy

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

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

Tuples are immutable: once created, their elements cannot be reassigned, added or removed, satisfying the stem's requirement for an immutable type. Unlike lists, which permit in-place mutation, a tuple's contents stay fixed for its lifetime, making it the correct choice among the options given.

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().

97
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

Using `config.get('debug')` returns the stored boolean, so `not` inverts it: when `debug` is `True` the condition fails and `timeout` is skipped, satisfying the stem's constraint. `setdefault` inserts `'timeout': 30` only when the key is absent, and Python 3.7+ dictionaries preserve insertion order, keeping key ordering stable.

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.

98
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() yields pairs of index and value while iterating, so the loop unpacks both without manual counter management. It satisfies the requirement to access the index directly, unlike range() combined with indexing or zip(), which needs a separate sequence.

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.

99
MCQmedium

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

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

Exponentiation binds tightest, giving 2 ** 3 = 8; then 4 * 8 = 32; floor division 32 // 5 = 6; finally 3 + 6 = 9. Precedence order is **, then * and //, then +.

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.

100
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-quoted strings are valid Python string literals, so `'''Hello, World!'''` creates the same str object as single or double quotes and passes it to `print()`. The embedded apostrophe-free content needs no escaping, and the statement satisfies the stem's requirement to output exactly `Hello, World!`.

Why this answer

Option A is correct because triple-quoted strings ('''...''') are valid Python string literals, and since the content 'Hello, World!' contains no conflicting triple quotes, print('''Hello, World!''') outputs the string successfully. Option C is correct because a double-quoted string literal "Hello, World!" is valid Python syntax, and print("Hello, World!") outputs the exact text. Option E is correct because a single-quoted string literal 'Hello, World!' is valid Python syntax, and print('Hello, World!') outputs the exact text.

Option B is incorrect because the inner double quotes around Hello! terminate the string early, causing a SyntaxError. Option D is incorrect because the apostrophe in It's prematurely closes the single-quoted string, also causing a SyntaxError.

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.

101
MCQmedium

What will be printed? ```python my_list = [] my_list.append('192.168.1.10') my_list.append('255.255.255.0') my_list.append('192.168.1.1') print(my_list) ```

A.['255.255.255.0']
B.['192.168.1.10']
C.['192.168.1.10', '255.255.255.0', '192.168.1.1']
D.['192.168.1.10', '192.168.1.1']
AnswerC

append adds each string to the end of the list in call order, so the list holds the three addresses sequentially. Printing the list displays them in that insertion order within square brackets, with each element quoted as a string.

Why this answer

The printed output is a list containing three string elements: '192.168.1.10', '255.255.255.0', and '192.168.1.1'. When printing a list in Python, it displays each element enclosed in square brackets and separated by commas. Option C correctly shows this output.

The other options have an incorrect number of elements.

Exam trap

The PCEP exam often tests whether candidates understand that `append()` adds elements sequentially to the end of a list, and that printing the list shows all elements in order, not just the last one or a subset.

How to eliminate wrong answers

Option A is wrong because it only shows the subnet mask '255.255.255.0', ignoring the two IP addresses that were also appended. Option B is wrong because it only shows the first IP address '192.168.1.10', omitting the subnet mask and the gateway. Option D is wrong because it lists only the two IP addresses but leaves out the subnet mask '255.255.255.0' that was appended second.

102
MCQeasy

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

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

The `upper()` string method returns a copy of the string with all cased characters converted to uppercase, leaving the original unchanged. Applied to `'Hello'`, it transforms each lowercase letter, producing `HELLO`. This satisfies the stem's requirement to determine the exact printed output of the expression.

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.

103
MCQeasy

Which of the following is a floating-point literal?

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

The decimal point makes 3.14 a floating-point literal, satisfying the stem's requirement for a real-number constant. Python's tokeniser classifies any numeric literal containing a decimal point or exponent as float, so 3.14 evaluates to type float rather than int. Integers such as 42 lack that fractional marker.

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.

104
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

The first assignment a = b overwrites a with 10, destroying the original 5. The second assignment b = a then copies 10 back into b, so both variables hold 10; no temporary variable preserved the original value.

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.

105
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.

106
MCQeasy

Which keyword is used to define a function in Python?

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

The `def` keyword introduces a function definition, binding the function name to a callable object at runtime. It satisfies the stem's requirement for the specific keyword that declares functions, unlike `lambda` (anonymous expressions) or `class` (type definitions). Every named function in Python begins with `def`, followed by the name and parameter list.

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`.

107
MCQmedium

A developer is writing a Python script that stores the number of active user sessions in a variable. They want the variable to hold the value 42 as an integer. Which of the following statements correctly assigns the integer 42 to a variable named session_count?

A.session_count = 42
B.session_count := 42
C.session_count = '42'
D.int session_count = 42
AnswerA

This assignment uses the equals sign to bind the integer literal 42 to the name session_count. In Python, variables are created on assignment; no type declaration is needed. The value is stored as an int because 42 has no decimal point or quotes, making this the correct way to store the integer.

Why this answer

The correct assignment uses the equals sign to bind the integer literal to the variable name. Python does not require type declarations, and the absence of quotes ensures the value is an int. The other options either create a string, use invalid syntax, or misuse an operator not intended for simple assignment.

Exam trap

The trap here is confusing string literals with numeric literals because they look similar when printed, and forgetting that Python does not use C-style type declarations.

108
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

Converting `'hello'` raises `ValueError`, so the handler sets x to 0. The `TypeError` clause never executes. The `finally` block always runs, adding 1, giving x = 1. This satisfies the stem's requirement to trace exception handling and finalisation order precisely.

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.

109
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

Dividing by zero raises ZeroDivisionError, caught by the except block, which prints 'error'. The finally block always executes regardless of exception handling, printing 'done'. This satisfies the stem's requirement to show both the handled exception output and the guaranteed finally output.

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'.

110
MCQhard

A programmer is debugging a Python script that uses a while loop to process a list of numbers. The code is: numbers = [1, 2, 3, 4, 5] i = 0 while i < len(numbers): if numbers[i] % 2 == 0: print(numbers[i]) i += 1 What is the output of this code?

A.2 4 6
B.An infinite loop occurs because i is not incremented.
C.1 3 5
D.2 4
AnswerD

The loop iterates over the list using index i from 0 to 4. The condition checks if the current number is even (numbers[i] % 2 == 0). For 1, it's odd (no print). For 2, it's even (print 2). For 3, odd. For 4, even (print 4). For 5, odd. So the output is 2 and 4 on separate lines. The loop increments i correctly, avoiding an infinite loop.

Why this answer

The while loop iterates through the list by index, checking each element for evenness using the modulo operator. When an even number is found, it is printed. The loop correctly increments the index, so it terminates after processing all elements.

The even numbers in the list are 2 and 4, so they are printed on separate lines.

Exam trap

The trap here is misreading the modulo condition and thinking it prints odd numbers, or overlooking the increment that prevents an infinite loop.

111
Drag & Dropmedium

Arrange the steps to slice a list in Python.

Drag or tap steps into the slots.

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.

112
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

input() always returns a string, so wrapping it in int() converts the typed characters into an integer before assignment. This satisfies the requirement to store age as a numeric type, enabling arithmetic rather than string concatenation or comparison failures.

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.

113
Multi-Selectmedium

A developer is reviewing Python's built-in numeric types while preparing a data-processing script. Which TWO statements about Python's numeric types are accurate? (Choose two.)

Select 2 answers
A.The int type can represent arbitrarily large whole numbers, limited only by available memory.
B.The float type stores values with exact decimal precision for all real numbers.
C.The bool type is a subclass of int, so True and False behave as 1 and 0 in arithmetic.
D.The complex type cannot be used with the addition operator.
E.Dividing two integers with the single slash operator always produces an integer result.
AnswersA, C

Python integers are arbitrary-precision objects, so values grow beyond the fixed widths found in many other languages. Computing large powers such as 2 ** 200 produces an exact integer rather than an overflow. This behavior makes int suitable for exact arithmetic in scripts that process large counts or identifiers, and it is a defining characteristic of the type.

Why this answer

Python's int objects use arbitrary precision, allowing whole numbers far larger than fixed-width machine integers, and bool is a subclass of int whose instances act as one and zero in arithmetic. Together these two facts describe genuine features of the numeric type hierarchy. The other statements mischaracterize floats as exact, deny arithmetic support for complex numbers, and confuse true division with floor division.

Exam trap

The trap here is assuming that all numeric types behave like fixed-width integers from other languages, which leads to wrongly accepting claims about float exactness or integer overflow.

114
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

The dict() constructor accepts keyword arguments, mapping each parameter name to its value as a string key. This satisfies the requirement for a valid dictionary-creation syntax, producing {'a': 1, 'b': 2} without needing literal braces or quoted keys.

Why this answer

Option B, my_dict = dict(a=1, b=2), is correct because the dict() constructor accepts keyword arguments, using the parameter names as string keys and the assigned values as their values, producing {'a': 1, 'b': 2}. Option D, my_dict = {'a':1, 'b':2}, is correct because it uses standard dictionary literal syntax with curly braces, colon-separated key-value pairs, and comma separators. Option A is invalid because bare identifiers a and b are treated as variables rather than string keys, so it raises a NameError unless those variables exist, and even then it would not create the intended string-keyed dictionary.

Option C is invalid because dict() expects a single iterable of key-value pairs (e.g., dict([('a',1),('b',2)])), not multiple separate list arguments. Option E is invalid because square brackets denote a list, and the colon syntax inside them is not valid Python.

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.

115
Drag & Dropmedium

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

Drag or tap steps into the slots.

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.

116
MCQhard

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

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

The exponentiation operator ** is right-associative, so 3 ** 2 evaluates first to 9, then 2 ** 9 yields 512. Left-to-right evaluation would give 64, but Python's grammar groups the rightmost operation first, producing 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.

117
MCQhard

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

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

Variables created inside a function exist only within that function's local namespace, which Python binds at call time and discards on return. This satisfies the stem's scope constraint: the name is unreachable from module level or any other function, so it cannot leak or collide with globals of the same name.

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.

118
MCQmedium

A developer is reviewing a script that processes user data. The script contains the following lines: name = "Alice" age = 30 print(name + " is " + age) When executed, the script raises a TypeError. Which of the following changes will make the script run without error and produce the output "Alice is 30"?

A.Change the print statement to: print(name + " is " + str(age))
B.Change the print statement to: print(name + " is " + age + " years")
C.Change the print statement to: print(name + " is " + int(age))
D.Change the print statement to: print(name + " is " + float(age))
AnswerA

The TypeError occurs because the + operator cannot concatenate a string and an integer. Wrapping age with str() converts the integer to its string representation, allowing concatenation. This is the standard way to combine text and numbers in Python when not using f-strings or the format() method. The output will be exactly "Alice is 30".

Why this answer

The TypeError arises from attempting to concatenate a string and an integer using the + operator. Python requires both operands to be strings for concatenation. Converting the integer to a string with str() allows the concatenation to succeed.

The other options either leave the type mismatch or convert to other numeric types, which still cannot be concatenated with a string.

Exam trap

The trap here is assuming that Python automatically converts numbers to strings during concatenation, but the + operator is strict about operand types.

119
MCQmedium

A developer is writing a Python script to compare two numbers. They write the following code: x = 10 y = 20 result = x > y or x < y and y > 15 print(result) What is printed?

A.True
B.The output is 10 > 20 or 10 < 20 and 20 > 15, which is not a boolean value.
C.False
D.An error occurs because you cannot mix 'or' and 'and' without parentheses.
AnswerA

The expression is evaluated according to operator precedence: comparison operators have higher precedence than logical operators, and 'and' has higher precedence than 'or'. First, x > y is False, x < y is True, and y > 15 is True. Then, x < y and y > 15 evaluates to True and True, which is True. Finally, False or True evaluates to True. So the output is True.

Why this answer

Logical operators in Python follow a specific precedence: 'and' is evaluated before 'or'. Also, comparison operators are evaluated before logical operators. Thus, the expression is grouped as (x > y) or ((x < y) and (y > 15)).

Substituting values: (False) or (True and True) = False or True = True. Therefore, the output is True.

Exam trap

The trap here is assuming that logical operators are evaluated left-to-right without considering that 'and' has higher precedence than 'or'.

120
MCQhard

A developer writes the following code: values = [10, 20, 30, 40, 50] result = values[1:4] What does the variable result contain after execution?

A.[20, 30, 40]
B.[20, 30, 40, 50]
C.[10, 20, 30]
D.[10, 20, 30, 40]
AnswerA

Slicing uses a start index that is included and a stop index that is excluded. Starting at index one includes twenty, and stopping at index four excludes the element at index four, which is fifty. The elements at indexes one, two, and three are twenty, thirty, and forty, so the resulting list contains exactly those three values.

Why this answer

List slicing takes a start index that is included and a stop index that is excluded. With values[1:4], the slice begins at the element twenty and continues through the elements at indexes two and three, which are thirty and forty. The element at index four is not included because the stop bound is exclusive, so the result list holds three elements.

Exam trap

The trap here is treating the second slice index as inclusive, which shifts the result by one element and changes both the start and stop boundaries.

121
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

Python evaluates `and` before `or`, so `(1 and 0)` yields 0 and `(not False and True)` yields True. The `or` then returns True because one operand is truthy, satisfying the expression's requirement for a Boolean result.

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).

122
Multi-Selectmedium

A developer is creating a Python script and needs to assign a value to a variable. Which TWO of the following assignment statements are syntactically valid in Python? (Choose two.)

Select 2 answers
A.my-var = 10
B.my var = 10
C.my_var2 = 10
D.2myvar = 10
E.my_var = 10
AnswersC, E

This is valid: 'my_var2' starts with a letter, contains an underscore and a digit after the first character. Digits are allowed after the first character. The assignment sets my_var2 to 10. This is syntactically correct and demonstrates a common naming pattern.

Why this answer

Valid Python identifiers must start with a letter or underscore, and may contain letters, digits, and underscores. 'my_var = 10' and 'my_var2 = 10' follow these rules. Names starting with a digit, containing a hyphen, or containing a space are invalid and cause SyntaxError.

Exam trap

The trap here is assuming that digits can appear anywhere or that hyphens and spaces are allowed, but only letters, digits, and underscores are permitted after the first character.

← PreviousPage 2 of 2 · 122 questions total

Ready to test yourself?

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