Courseiva

CCNA Data Types, Variables, Basic I/O and Operators Questions

31 of 181 questions · Page 3/3 · Data Types, Variables, Basic I/O and Operators · Answers revealed

151
MCQeasy

What is the result of 17 % 5 in Python?

A.2
B.4
C.3
D.1
AnswerA

The modulo operator returns the remainder after integer division, so 17 % 5 evaluates to 2 because 5 divides into 17 three times (15) with 2 left over. This satisfies the stem's requirement for the exact result of the expression, matching Python's behaviour for positive integers.

Why this answer

In Python, the % operator performs modulo division, returning the remainder after integer division. 17 divided by 5 equals 3 with a remainder of 2 (since 5 * 3 = 15, and 17 - 15 = 2), so 17 % 5 evaluates to 2.

Exam trap

Python Institute often tests the distinction between the modulo operator (%) and floor division (//), trapping candidates who confuse the remainder with the quotient.

How to eliminate wrong answers

Option B (4) is wrong because it incorrectly assumes the result is the quotient minus 1, or confuses modulo with floor division (17 // 5 = 3). Option C (3) is wrong because it represents the integer quotient (17 // 5), not the remainder. Option D (1) is wrong because it might come from mistakenly subtracting 5 twice (17 - 5 - 5 = 7, then 7 - 5 = 2, not 1) or from a miscalculation of the remainder.

152
MCQmedium

A developer wants to output a variable price with two decimal places using formatting. Which line of code will produce 'Price: $12.50' for price = 12.5?

A.print('Price: $' + price)
B.print(f'Price: ${price:.2f}')
C.print('Price: $' + str(round(price, 2)))
D.print('Price: $%s' % price)
AnswerB

The f-string's `:.2f` format specifier rounds the float to exactly two decimal places, satisfying the stem's two-decimal requirement. Substituting price = 12.5 yields `12.50`, and the literal `$` inside the string produces the required `Price: $12.50` output precisely.

Why this answer

It uses an f-string with the format specifier `:.2f`, which formats the float `12.5` as a string with exactly two decimal places, producing '12.50'. The f-string then interpolates this into the full string 'Price: $12.50'.

Exam trap

Python Institute often tests the difference between `round()` (which returns a float and may not add trailing zeros) and format specifiers (which control string representation), leading candidates to mistakenly choose Option C thinking it produces two decimal places.

How to eliminate wrong answers

Option A is wrong because it attempts to concatenate a string with a float using the `+` operator, which raises a `TypeError` (cannot concatenate str and float). Option C is wrong because `round(price, 2)` returns the float `12.5` (not a string), and converting it with `str()` yields '12.5' without forcing two decimal places, so the output would be 'Price: $12.5'. Option D is wrong because the `%s` placeholder converts the float to a string using `str()`, which again produces '12.5' without two decimal places, and the `%` formatting does not apply numeric precision to `%s`.

153
MCQeasy

What does 'print(2 ** 3)' output?

A.9
B.23
C.8
D.6
AnswerC

The `**` operator performs exponentiation, raising the left operand to the power of the right. Here 2 raised to the power 3 equals 8, so `print` outputs 8. It is distinct from `^`, which is bitwise XOR in Python.

Why this answer

The ** operator in Python performs exponentiation, raising the left operand (2) to the power of the right operand (3), which equals 8. The print() function then outputs this integer result to the console.

Exam trap

The trap here is that candidates often confuse the ** operator with multiplication (*) or addition (+), leading them to pick 6 or 23, or they reverse the base and exponent, picking 9 instead of 8.

How to eliminate wrong answers

Option A is wrong because 9 would be the result of 3 ** 2 (3 squared), not 2 ** 3; this confuses the base and exponent. Option B is wrong because 23 is the result of string concatenation '2' + '3', not the exponentiation operator; this confuses the ** operator with string operations. Option D is wrong because 6 is the result of 2 * 3 (multiplication), not 2 ** 3 (exponentiation); this confuses the ** operator with the * multiplication operator.

154
MCQhard

Consider the following code: `x = 5` then `y = 2` then `result = x // y * y + x % y`. What is the value of `result`?

A.`7`
B.`6`
C.`5`
D.`2`
AnswerC

Operator precedence: `//`, `*`, and `%` have the same precedence and are evaluated left-to-right. First `x // y` gives `2` (since `5 // 2 = 2`). Then `2 * y` gives `4`. Then `x % y` gives `1` (since `5 % 2 = 1`). Finally, `4 + 1` equals `5`. This is a standard identity: `(x // y) * y + (x % y)` reconstructs `x` for positive integers.

Why this answer

The expression combines floor division, multiplication, and modulo. Due to left-to-right evaluation of operators with equal precedence, `x // y` is computed first, then multiplied by `y`, then `x % y` is computed and added. For `x = 5` and `y = 2`, this yields `(5 // 2) * 2 + (5 % 2) = 2 * 2 + 1 = 5`.

This demonstrates the relationship between floor division and modulo.

Exam trap

The trap here is misapplying operator precedence, such as evaluating `*` before `//` or `%`, or misunderstanding the modulo operation.

155
MCQmedium

A developer wants to assign the value 3.14 to a variable and later change it to the integer 3. Which of the following is true?

A.This is allowed only if the variable was declared as a float.
B.This causes a TypeError because you cannot change types.
C.This is allowed because Python is dynamically typed.
D.This is allowed only if you use the int() function during assignment.
AnswerC

Python variables are unbound names, so rebinding `pi` from the float 3.14 to the integer 3 is legal; the interpreter checks types at runtime, not at declaration. This satisfies the stem's requirement that the same name later hold a different type, which dynamic typing permits.

Why this answer

Python is dynamically typed, meaning variables can be reassigned to values of any type at runtime. The developer can first assign the float 3.14 to a variable and later reassign the integer 3 to the same variable without any type declaration or conversion function required.

Exam trap

The trap here is that candidates often confuse Python's dynamic typing with static typing rules from languages like Java or C, leading them to believe that type changes require explicit conversion or are disallowed.

How to eliminate wrong answers

Option A is wrong because Python does not require variable declaration with a type; you can assign any value to any variable regardless of its previous type. Option B is wrong because Python does not raise a TypeError when changing the type of a variable; dynamic typing allows reassignment to a different type without error. Option D is wrong because the int() function is not required for reassignment; you can directly assign the integer 3 without any conversion.

156
MCQhard

A script runs: x = 5 y = x y += 3 print(x, y) What is printed?

A.5 8
B.5 5
C.8 5
D.8 8
AnswerA

After y = x, both names refer to the same integer object with value 5. The statement y += 3 computes 5 + 3 and rebinds y to a new integer object with value 8, but it does not modify the original object, which integers cannot do. The name x still references 5, so the script prints 5 8.

Why this answer

Names in Python are references to objects, and integers are immutable. Assigning y = x makes both names point to the same 5 object, but y += 3 creates a new integer and rebinds only y. Since x is never reassigned, it continues to reference 5, and the output is 5 8.

Exam trap

The trap here is believing that assigning one variable to another creates a permanent link, so changing one automatically changes the other.

157
MCQhard

A Python programmer writes the following code: x = 5 y = 2 result = x / y print(type(result)) What is printed?

A.<class 'int'>
B.<class 'decimal'>
C.<class 'float'>
D.<class 'double'>
AnswerC

In Python 3, the division operator / always returns a floating-point number, even when both operands are integers and the division is exact. Here, 5 / 2 yields 2.5, which is a float. The type() function returns <class 'float'>.

Why this answer

In Python 3, the division operator / performs true division and always returns a float, even if the result is a whole number. Therefore, 5 / 2 evaluates to 2.5, and type(result) is <class 'float'>. The floor division operator // would return an integer if both operands are integers.

Exam trap

The trap here is assuming that division of two integers yields an integer, as in Python 2 or some other languages, when Python 3 always returns a float for /.

158
Multi-Selectmedium

Which of the following expressions evaluate to True? (Choose three.)

Select 3 answers
A.3 ** 2 == 9
B.4.0 == 4
C.10 % 3 == 0
D."Py" in "Python"
E.bool(0)
AnswersA, B, D

Raising 3 to the power of 2 via the exponentiation operator yields 9, so the equality comparison returns True. This satisfies the stem's requirement for expressions evaluating to True, since Python's ** operator binds tighter than ==, making the comparison 9 == 9.

Why this answer

Option A is correct because the exponentiation operator ** raises 3 to the power of 2, yielding 9, and 9 == 9 evaluates to True. Option B is correct because in Python, comparing a float and an int with == performs numeric value comparison: 4.0 and 4 represent the same numeric value, so 4.0 == 4 is True. Option D is correct because the in operator performs a substring membership test on strings, and the substring "Py" occurs at the start of "Python", so the expression is True.

Option C is not correct because 10 % 3 returns the remainder 1 (not 0), so 1 == 0 is False. Option E is not correct because bool(0) evaluates to False, not True, since zero is a falsy value in Python.

Exam trap

The PCEP exam often tests the distinction between the modulo operator returning the remainder (not the quotient) and the falsy nature of zero, leading candidates to mistakenly think `10 % 3 == 0` or `bool(0)` evaluate to `True`.

159
MCQeasy

What is the type of the result of the expression 5 + 3.0?

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

Adding an int and a float triggers Python's implicit numeric promotion: the int operand is converted to float before addition, so the result always takes the wider type. Here 5 becomes 5.0, and 5.0 + 3.0 yields 8.0, a float, satisfying the expression's mixed-type operand constraint.

Why this answer

In Python, when an integer (int) and a float are combined using the addition operator, the result is implicitly converted to a float to preserve precision. Since 3.0 is a float, 5 + 3.0 yields 8.0, which is of type float.

Exam trap

The PCEP exam often tests the misconception that adding an integer and a float returns an integer, or that Python truncates the result, when in fact Python always promotes to the more precise type (float).

How to eliminate wrong answers

Option A is wrong because str is the string type, and adding an int and a float does not produce a string unless explicit conversion is performed. Option C is wrong because int would only result if both operands were integers; the presence of 3.0 forces implicit conversion to float. Option D is wrong because complex numbers require a real and imaginary part (e.g., 5+3j), and this expression involves no imaginary component.

160
MCQmedium

Given the code: ```python name = input('Enter your name: ') print('Hello, ' + name) ``` If the user enters 'Alice', what is the output?

A.Hello,Alice
B.Hello, 'Alice'
C.Hello, Alice
D.Hello, Alice
AnswerC

The `input()` function returns the entered text as a string, so `name` holds `'Alice'`. String concatenation with `+` joins `'Hello, '` and `'Alice'` into a single string, which `print()` outputs exactly as `Hello, Alice`, satisfying the stem's request for the program's output.

Why this answer

The `print('Hello, ' + name)` statement concatenates the string literal `'Hello, '` (which includes a trailing space) with the user input `'Alice'`, producing the output `Hello, Alice`. The `input()` function returns the exact string entered by the user without any extra quotes or formatting.

Exam trap

Python Institute often tests whether candidates notice the trailing space in the string literal `'Hello, '` versus a missing space, and whether they understand that `input()` does not add quotes around the entered value.

How to eliminate wrong answers

Option A is wrong because it omits the space between 'Hello,' and 'Alice', which is present in the code as part of the string literal `'Hello, '`. Option B is wrong because it incorrectly adds single quotes around the name, which are not part of the output; the `input()` function does not add quotes to the user's input. Option D is wrong because it is identical to option C, but the question expects a single correct answer; the duplication is a distractor, and the correct output is exactly `Hello, Alice` with a space.

161
MCQmedium

A developer needs to swap the values of two variables a and b without using a temporary variable. Which single line of code correctly performs the swap?

A.a = b; b = a
B.a, b = b, a
C.a = a ^ b; b = a ^ b; a = a ^ b
D.a = a + b; b = a - b; a = a - b
AnswerB

Tuple packing and unpacking evaluates the right-hand side first, building the tuple (b, a), then assigns its elements to a and b. This swaps the values in one statement, satisfying the no-temporary-variable constraint in the stem.

Why this answer

Python supports tuple unpacking, which allows swapping the values of two variables in a single line without a temporary variable. The expression `a, b = b, a` evaluates the right-hand side tuple `(b, a)` first, then assigns the values to `a` and `b` respectively, effectively swapping them. Option A fails because after `a = b`, the original value of `a` is lost, so `b = a` assigns the same value to both.

Option C (XOR swap) works but requires three statements, not a single line. Option D (arithmetic swap) also works but requires three statements and may cause overflow in other languages, though Python handles big integers; still, it is not a single line.

Exam trap

Candidates may think that XOR or arithmetic swaps are acceptable, but they require multiple lines. The question explicitly asks for a 'single line of code', so only tuple unpacking qualifies.

How to eliminate wrong answers

Option A is wrong because `a = b; b = a` first overwrites `a` with `b`'s value, then assigns the now-overwritten `a` (which equals original `b`) to `b`, resulting in both variables holding the original `b` value, not a swap. Option C is wrong because it uses XOR bitwise operations across three lines, not a single line as required by the question. Option D is wrong because it uses arithmetic operations across three lines, not a single line as required by the question.

162
MCQeasy

What is the data type of z after executing z = 10 / 2?

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

The division operator always returns a float in Python 3, even when both operands are integers and divide evenly. So 10 / 2 yields 5.0, a float, not an int. This satisfies the question's requirement to identify the resulting data type.

Why this answer

Float because in Python, the / operator always performs true division and returns a float, regardless of the operands. This is a fundamental concept tested in the PCEP exam to distinguish between / and //.

Exam trap

Python Institute often tests the distinction between / (true division, returns float) and // (floor division, returns int) to catch candidates who assume integer division returns an integer.

How to eliminate wrong answers

Option A is wrong because bool is a subtype of int in Python, but the result of 10 / 3 is not a boolean value (True or False). Option B is wrong because int would be the result of floor division (10 // 3) or integer division in some languages, but Python's / operator always returns a float. Option D is wrong because str is a string type, and the division operator does not produce a string; it produces a numeric float.

163
Multi-Selectmedium

Which FOUR of the following are correct uses of the print() function?

Select 4 answers
A.print 'Hello'
B.print('Hello', 'World', sep='-')
C.print('Hello', 'World')
D.print('Hello')
E.print('Hello', 5)
AnswersB, C, D, E

Passing `sep='-'` overrides print()'s default single-space separator, so the two arguments are joined with a hyphen and the output is `Hello-World`. This satisfies the stem's requirement for a correct use of print(), since `sep` is a valid keyword argument controlling the separator inserted between multiple positional arguments.

Why this answer

Option B is correct because print() accepts the keyword argument sep to define the separator between multiple arguments, so print('Hello', 'World', sep='-') outputs Hello-World. Option C is correct because print() can take multiple positional arguments and by default separates them with a single space, producing Hello World. Option D is correct because print('Hello') is the standard way to call print() with a single string argument, outputting Hello followed by a newline.

Option E is correct because print() accepts arguments of different types, so print('Hello', 5) outputs Hello 5, converting the integer to its string representation. Option A is not correct because print 'Hello' is Python 2 statement syntax, not a valid call to the print() function in Python 3.

Exam trap

Python Institute often tests the distinction between Python 2's print statement (no parentheses) and Python 3's print function (requires parentheses), leading candidates to mistakenly select option A as valid.

164
Drag & Dropmedium

Order the steps to write a for loop that iterates over a range of numbers.

Drag or tap steps into the slots.

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

Why this order

The correct order is to write 'for', then the loop variable, then 'in', then the range() function with appropriate arguments, then a colon, and finally an indented block containing the statements to repeat. This structure defines a for loop that iterates over a sequence generated by range().

165
MCQmedium

A developer is inspecting a variable and writes: value = 7.0 // 2. What is the value and type of the result assigned to 'value'?

A.3.5, of type float
B.3, of type int
C.4.0, of type float
D.3.0, of type float
AnswerD

The floor division operator // divides and rounds down to the nearest integer value, but when either operand is a float the result is a float. 7.0 // 2 computes 3.5 and floors it to 3.0, keeping the float type. This is correct because // preserves float type when any operand is a float.

Why this answer

Floor division // computes the quotient and rounds down to the nearest whole number, and the result is a float whenever either operand is a float. With 7.0 // 2, the quotient 3.5 floors to 3.0 and remains a float. The int result appears only when both operands are ints, and plain division would leave 3.5.

Exam trap

The trap here is assuming // always returns an int, when in fact it returns a float if either operand is a float.

166
Multi-Selectmedium

A Python script performs the following operations: s = "Hello" n = 5 result1 = s * 2 result2 = s + str(n) Which TWO statements about the values of result1 and result2 are true? (Choose two.)

Select 2 answers
A.result1 is "HelloHello"
B.result1 is 10
C.result2 is "Hello5"
D.result2 causes a TypeError
E.result1 is "Hello Hello"
AnswersA, C

The multiplication operator on a string and an integer repeats the string. Here s * 2 concatenates two copies of "Hello", producing "HelloHello". This is a standard string operation in Python that does not modify the original string but returns a new one. The value assigned to result1 is therefore exactly "HelloHello".

Why this answer

String repetition with * produces a new string containing the original repeated the given number of times, so "Hello" * 2 yields "HelloHello". Concatenation with + requires both operands to be strings, so the integer must be converted using str before joining, producing "Hello5". Direct concatenation without conversion would raise a TypeError.

Exam trap

The trap here is assuming that string multiplication inserts separators or performs numeric multiplication, and forgetting that concatenation requires explicit type conversion.

167
MCQmedium

A data scientist needs to read a list of floats from a file, one per line, and compute the sum. The current code: total = 0.0 with open("data.txt") as f: for line in f: total = total + line print(total) When run, a TypeError occurs: unsupported operand type(s) for +: 'float' and 'str'. The scientist knows that line is a string. Which fix will correctly sum the numbers?

A.Change to: total = total + eval(line)
B.Change to: total = total + line.strip()
C.Change to: total = total + float(line.strip())
D.Change to: total = total + int(line)
AnswerC

`line` is a string, so adding it to a float raises TypeError. Wrapping it in `float()` converts the stripped text into a numeric value, enabling correct arithmetic. `strip()` removes the trailing newline that `float()` would otherwise reject.

Why this answer

`float(line.strip())` converts the string read from the file (after removing any surrounding whitespace, including the newline character) into a float, which can then be added to the float variable `total`. The original error occurs because Python does not allow implicit addition of a string to a float.

Exam trap

Python Institute often tests the candidate's understanding that file input is always a string and must be explicitly converted to a numeric type before arithmetic, and that `strip()` alone does not change the data type.

How to eliminate wrong answers

Option A is wrong because `eval(line)` is dangerous and unnecessary; it evaluates the string as a Python expression, which could execute arbitrary code and is not a safe or recommended way to convert a string to a float. Option B is wrong because `line.strip()` returns a string, not a float, so the same TypeError would occur when trying to add a string to a float. Option D is wrong because `int(line)` would fail if the line contains a decimal point (e.g., '3.14') and would also raise a ValueError; moreover, the data is floats, not integers.

168
MCQmedium

A quiz program stores a user's score as score = 7 and the number of questions as total = 2. The developer writes percentage = score / total * 100. What value is displayed?

A.350
B.350.0
C.3.5
D.TypeError
AnswerB

In Python 3, the / operator always performs true division, so 7 / 2 evaluates to 3.5 even though both operands are integers. Multiplying by 100 gives 350.0. The result is a float, which is why the decimal appears. This is the expected behavior for a percentage calculation.

Why this answer

Python 3 uses true division for the / operator, so dividing two integers yields a float. With score = 7 and total = 2, 7 / 2 is 3.5, and 3.5 * 100 is 350.0. The expression evaluates left to right, so the multiplication by 100 cannot be skipped.

The displayed value includes a decimal because the result type is float.

Exam trap

The trap here is expecting integer division from the / operator, as in Python 2 or many other languages, when Python 3 always returns a float.

169
MCQhard

After executing: a = 5; b = 2; c = a // b; d = a % b; e = a ** b. What is the value of (c + d) * 2 - e?

A.-20
B.-19
C.-11
D.-15
AnswerB

Integer division gives c = 2, modulo gives d = 1, and exponentiation gives e = 25. So (2 + 1) * 2 - 25 = 6 - 25 = -19, matching the computed value exactly.

Why this answer

After executing the code, a=5, b=2, c=5//2=2 (floor division), d=5%2=1 (remainder), e=5**2=25 (exponentiation). Then (c+d)*2-e = (2+1)*2-25 = 3*2-25 = 6-25 = -19. Option B is correct because it matches this calculation.

Exam trap

Python Institute often tests the distinction between floor division (//) and true division (/), and the correct order of operations (PEMDAS), where candidates may incorrectly compute c as 2.5 or misapply the exponentiation operator.

How to eliminate wrong answers

Option A is wrong because -20 would result if you mistakenly used regular division (c=2.5) and then rounded incorrectly, or if you swapped the order of operations (e.g., c+d*2-e). Option C is wrong because -11 would result if you incorrectly computed c as 5//2=2, d as 5%2=1, but then miscalculated e as 5**2=10 (confusing exponentiation with multiplication). Option D is wrong because -15 would result if you used integer division incorrectly (e.g., c=2, d=1, but then computed (c+d)*2 as 2+1*2=4, then 4-25=-21, or if you mistakenly used c=2, d=1, e=25 but then did (2+1)*2-25=6-25=-19, so -15 suggests a different arithmetic error like using c=5//2=2, d=5%2=1, e=5**2=25, but then computing (2+1)*2-25 as 2+1*2-25=2+2-25=-21, or mis-evaluating exponentiation as 5*2=10 leading to 6-10=-4, none of which match -15.

170
MCQeasy

A developer writes a program to calculate the average of three numbers: a=10; b=20; c=30; avg = a + b + c / 3; print(avg). What is the output?

A.20.0
B.10.0
C.40.0
D.60.0
AnswerC

Operator precedence evaluates division before addition, so c / 3 yields 10.0, then a + b + 10.0 gives 40.0. The float result arises because true division always returns a float in Python 3, satisfying the stem's expression exactly as written without parentheses.

Why this answer

The expression `a + b + c / 3` follows Python's operator precedence: division (`/`) has higher precedence than addition (`+`), so `c / 3` is evaluated first (30 / 3 = 10.0), then the additions are performed left to right: 10 + 20 + 10.0 = 40.0. The result is a float because division always returns a float in Python 3.

Exam trap

Python Institute often tests operator precedence by placing a division operation at the end of an expression without parentheses, tricking candidates into assuming left-to-right evaluation or that the entire sum is divided.

How to eliminate wrong answers

Option A is wrong because 20.0 would be the result if the expression were `(a + b + c) / 3` (average calculation), but the parentheses are missing. Option B is wrong because 10.0 would be the result if only `c / 3` were printed, ignoring `a` and `b`. Option D is wrong because 60.0 would be the result if the expression were `a + b + c` without division, or if the division were applied incorrectly to the entire sum without parentheses.

171
MCQhard

A Python program loads this JSON and accesses the first rule's action. Which expression gives the string "permit"?

A.data["rules"][0]["action"]
B.data["rules"][0]["action"][:5]
C.data["rules"][0]["action"][0]
D.data["rules"][1]["action"]
AnswerA

Subscripting `data["rules"]` returns the list, then `[0]` selects its first element — a dictionary — and `["action"]` retrieves that key's value, the string `"permit"`. This directly satisfies the stem's requirement to access the first rule's action field without iteration.

Why this answer

It uses the correct indexing to access the first element of the 'rules' list (index 0) and then retrieves the value associated with the key 'action' from that dictionary. This yields the string 'permit' as stored in the JSON data.

Exam trap

Python Institute often tests the distinction between accessing the first element of a list (index 0) versus the second element (index 1), and between retrieving a dictionary value by key versus slicing or indexing a string.

How to eliminate wrong answers

Option B is wrong because it attempts to slice the string 'permit' with [:5], which would return 'permit' only if the string length is exactly 5, but the correct approach is direct key access, not slicing. Option C is wrong because it uses index [0] on the string 'permit', which returns the first character 'p', not the whole string. Option D is wrong because it accesses the second rule (index 1) instead of the first rule (index 0), so it would retrieve the action of the second rule, which might not be 'permit'.

172
Matchingmedium

Match each Python data structure to its characteristic.

Drag a concept onto its matching description — or click a concept then click the description.

Concepts
Matches

Ordered, immutable sequence of items

Unordered collection of unique items

Mapping of key-value pairs

Ordered, mutable sequence of items

Immutable sequence of characters

Why these pairings

Python data structures have distinct properties: lists and tuples are ordered sequences (lists mutable, tuples immutable); sets are unordered and contain unique elements; dictionaries map keys to values. Common confusions include mixing mutability/order between lists and tuples, and assuming sets maintain order.

173
MCQmedium

What is the data type of the expression (3.14 > 2) and ('a' < 'b')?

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

Both comparisons yield Boolean values, and the `and` operator returns a `bool` when combining them. This satisfies the stem's requirement for the expression's data type: `3.14 > 2` evaluates to `True`, `'a' < 'b'` evaluates to `True`, and `True and True` produces the Boolean result `True`.

Why this answer

The expression (3.14 > 2) evaluates to True because 3.14 is greater than 2, and ('a' < 'b') evaluates to True because in Python string comparison uses lexicographic order based on Unicode code points ('a' has code point 97, 'b' has 98). The 'and' operator combines these two Boolean values, resulting in True, which is of type bool. Therefore, the entire expression's data type is bool.

Exam trap

Python Institute often tests the misconception that the 'and' operator returns a Boolean only when both operands are Boolean, but in Python it can return any operand type; however, in this specific case both operands are comparisons that yield bool, so the result is bool, and candidates may incorrectly think the result is int because True/False are subclasses of int.

How to eliminate wrong answers

Option B (float) is wrong because the expression does not produce a floating-point number; it produces a Boolean result from comparison and logical operators. Option C (str) is wrong because the expression involves comparisons and a logical operator, not string concatenation or manipulation, so the result is not a string. Option D (int) is wrong because while Booleans in Python are a subclass of int (True equals 1, False equals 0), the expression's type is explicitly bool, not int, and the question asks for the data type of the expression, which is bool.

174
MCQmedium

A junior developer writes: print('Hello' + 5). This code raises an error. What is the best way to fix it?

A.print('Hello' * 5)
B.print('Hello' + str(5))
C.print('Hello', 5)
D.print('Hello' + '5')
AnswerB

Explicitly converting the integer with str() resolves the TypeError, because Python's + operator requires both operands to be the same sequence type for concatenation. It satisfies the stem's constraint of fixing the error while preserving the original concatenation intent, yielding 'Hello5' rather than altering the output format.

Why this answer

Python's `+` operator for strings requires both operands to be strings. The code `print('Hello' + 5)` raises a `TypeError` because it attempts to concatenate a string with an integer. Using `str(5)` converts the integer to the string `'5'`, allowing the concatenation to succeed and print `Hello5`.

Exam trap

Python Institute often tests the distinction between concatenation (`+`) and multiple arguments in `print()`, where candidates may think `print('Hello', 5)` produces `Hello5` instead of `Hello 5` due to the default `sep=' '` parameter.

How to eliminate wrong answers

Option A is wrong because `'Hello' * 5` does not concatenate; it repeats the string 5 times, producing `HelloHelloHelloHelloHello`, which changes the intended output. Option C is wrong because `print('Hello', 5)` passes two separate arguments to `print()`, which prints them with a space separator (e.g., `Hello 5`), not as a single concatenated string. Option D is wrong because `'Hello' + '5'` works syntactically but does not fix the original error; it simply uses a string literal `'5'` instead of converting the integer `5`, which would still fail if the variable were truly an integer (e.g., from user input).

175
MCQeasy

Refer to the exhibit. What is the output?

A.3.0 1.0
B.3 3
C.3.333 1
D.3 1
AnswerD

The exhibit's code produces two values on one line separated by a space, matching the stem's expected output. The first value derives from the initial computation and the second from the subsequent operation, giving the precise sequence 3 1 as shown.

Why this answer

The code in the exhibit is `print(10//3, 10%3)`. The `//` operator performs floor division, which for positive numbers truncates the decimal part, so `10//3` yields 3. The `%` operator returns the remainder of the division, `10%3` yields 1.

Thus the output is '3 1'.

Exam trap

Python Institute often tests the difference between `/` (true division) and `//` (floor division) and `%` (modulo), and the trap here is that candidates confuse the modulo operator `%` with floor division `//`, expecting the integer quotient instead of the remainder.

How to eliminate wrong answers

Option A is wrong because `3.0 1.0` would result from `print(10/3, 10%3)` only if both results were explicitly cast to float, but `10%3` returns an integer `1`, not `1.0`. Option B is wrong because `3 3` would imply both operators returned integers, but `10/3` returns a float, not an integer. Option C is wrong because `3.333 1` would be the output of `print(10/3, 10%3)` only if the first value were truncated to three decimal places, but Python's default float representation does not round to three decimal places; it prints the full precision.

176
MCQmedium

What is the output of the code in the exhibit?

A.3
B.4
C.3.0
D.3.3333333333333335
AnswerA

The loop iterates over the list `[1, 2, 3]`, and the accumulator variable is reassigned on each pass rather than appended to, so only the final element survives. Printing after the loop therefore yields the last value, 3, satisfying the stem's requirement to trace the code's actual output.

Why this answer

The code performs integer division using the // operator, which in Python returns the floor of the division result for positive numbers. Since 10 // 3 equals 3 (the integer part of 10/3), the output is 3. Option A is correct because integer division discards the fractional part.

Exam trap

Python Institute often tests the distinction between / (true division returning a float) and // (floor division returning an int), tricking candidates who confuse the two operators or forget that integer division discards the remainder.

How to eliminate wrong answers

Option B is wrong because it assumes the result is 4, which would only occur if the code used ceiling division or an incorrect operation. Option C is wrong because it outputs 3.0, which would result from true division (/) rather than integer division (//). Option D is wrong because it outputs the full floating-point result of 10/3 (3.3333333333333335), which is produced by the / operator, not the // operator.

177
MCQmedium

What is the output when the following code is executed? try: print(1/0) except ZeroDivisionError: print("Cannot divide by zero")

A.Cannot divide by zero
B.The program crashes with an unhandled exception
C.Result: 0
D.Unsupported operand
AnswerA

Dividing 1 by 0 raises a ZeroDivisionError, which the except clause catches by matching that exact exception type. The handler then executes its print statement, emitting the string "Cannot divide by zero" instead of terminating with a traceback. This satisfies the stem's requirement to show the caught-exception output.

Why this answer

The code inside the try block attempts to divide by zero, which raises a ZeroDivisionError. The except block catches this exception and executes its print statement, outputting 'Cannot divide by zero'.

Exam trap

Python Institute often tests the distinction between an unhandled exception (crash) and a caught exception (graceful handling). In this case, the exception is caught, so the program does not crash.

How to eliminate wrong answers

Option B is wrong because the program does not crash with an unhandled exception; the ZeroDivisionError is caught by the try-except block, so execution continues gracefully. Option C is wrong because division by zero does not yield 0; Python raises an exception instead of returning a numeric result. Option D is wrong because 'Unsupported operand' is not a Python error message; the actual error is ZeroDivisionError, which occurs when the divisor is zero, not due to operand type mismatch.

178
MCQmedium

A Python script contains the following code: x = 0.1 + 0.2 y = 0.3 print(x == y) What is printed?

A.0.3
B.True
C.False
D.An error occurs because floats cannot be compared with ==.
AnswerC

Due to binary floating-point representation, 0.1 and 0.2 cannot be stored exactly, and their sum is slightly more than 0.3. The literal 0.3 is also stored as a slightly different approximation. Therefore, the equality comparison returns False, and the program prints False.

Why this answer

Floating-point numbers in Python follow the IEEE 754 standard, so decimal values like 0.1, 0.2, and 0.3 are stored as approximations. Adding 0.1 and 0.2 yields a result that is not exactly equal to the stored approximation of 0.3. Consequently, the equality check returns False.

Exam trap

The trap here is assuming that decimal arithmetic behaves exactly as it does in mathematics, overlooking the binary floating-point representation that causes tiny rounding errors.

179
MCQmedium

A programmer needs to swap the values of two variables a and b without using a temporary variable. Which approach works in Python?

A.a = b; b = a
B.a, b = b, a
C.a = a ^ b; b = a ^ b; a = a ^ b
D.a = b + a; b = a - b; a = a - b
AnswerB

Python evaluates the right-hand tuple (b, a) fully before assigning to the left-hand targets, so both original values are captured prior to rebinding. This tuple-unpacking swap needs no temporary variable and works for any assignable targets.

Why this answer

Python supports tuple unpacking, which allows the values of a and b to be swapped in a single atomic operation: a, b = b, a. This works by creating a tuple (b, a) on the right-hand side, then unpacking it into the variables on the left, effectively swapping the values without a temporary variable.

Exam trap

Python Institute often tests the misconception that simple sequential assignment (a = b; b = a) works for swapping, leading candidates to overlook Python's tuple unpacking mechanism.

How to eliminate wrong answers

Option A is wrong because a = b; b = a first overwrites a with b's value, then assigns the new a (which is now b) to b, so both variables end up with the original b value, failing to swap. Option C is wrong because while a = a ^ b; b = a ^ b; a = a ^ b works in languages like C with mutable integers, Python's integers are immutable and the XOR operation on integers does not modify variables in place; the code would actually work in Python due to rebinding, but it is not a recommended or readable approach and can fail with large integers due to Python's arbitrary precision. Option D is wrong because a = b + a; b = a - b; a = a - b works only if the sum does not overflow, but Python integers are arbitrary precision so overflow is not an issue; however, this approach is fragile with floating-point numbers and is not the idiomatic Python way.

180
MCQeasy

Which of the following is NOT a valid variable name in Python?

A._myvar
B.myVar2
C.2nd_var
D.my_var
AnswerC

Python identifiers cannot begin with a digit, so 2nd_var raises a SyntaxError at parse time. Valid names must start with a letter or underscore, then contain letters, digits or underscores, making this the only invalid option.

Why this answer

Python variable names cannot start with a digit. The name '2nd_var' begins with '2', which violates Python's identifier naming rules. Valid variable names must start with a letter (a-z, A-Z) or an underscore (_), and can be followed by letters, digits, or underscores.

Exam trap

The PCEP exam often tests the rule that variable names cannot start with a digit, knowing that candidates may mistakenly think digits are allowed anywhere or that underscores are not valid starting characters.

How to eliminate wrong answers

Option A is wrong because '_myvar' is a valid variable name; it starts with an underscore, which is allowed, and contains only letters and underscores. Option B is wrong because 'myVar2' is valid; it starts with a letter and contains letters and digits, which is permitted. Option D is wrong because 'my_var' is valid; it starts with a letter and uses an underscore, both of which are allowed in Python identifiers.

181
MCQmedium

What is the output of the following code? print('Hello', 'World', sep='-', end='!\n')

A.Hello-World\n
B.Hello-World!\n
C.Hello World!\n
D.Hello World!\n
AnswerB

The `sep='-'` argument replaces the default space between the two string arguments, joining them as `Hello-World`, while `end='!\n'` substitutes the default newline terminator with an exclamation mark followed by a newline. Both keyword arguments therefore take effect, producing exactly `Hello-World!` plus a line break.

Why this answer

The `print()` function with `sep='-'` replaces the default space separator with a hyphen between the two arguments 'Hello' and 'World', producing 'Hello-World'. The `end='!\n'` parameter overrides the default newline-only end with an exclamation mark followed by a newline, so the output ends with '!' before the newline. Therefore, the correct output is 'Hello-World!\n'.

Exam trap

The trap here is that candidates often overlook the `end` parameter override and assume the default newline-only ending, or they confuse `sep` with `end`, leading them to pick an option with a space separator or missing the exclamation mark.

How to eliminate wrong answers

Option A is wrong because it omits the exclamation mark specified by `end='!\n'`, showing only the default newline. Option C is wrong because it uses a space separator instead of the hyphen specified by `sep='-'`. Option D is wrong for the same reason as C (space instead of hyphen) and also omits the exclamation mark.

← PreviousPage 3 of 3 · 181 questions total

Ready to test yourself?

Try a timed practice session using only Data Types, Variables, Basic I/O and Operators questions.