Courseiva

CCNA Data Types Variables Questions

75 of 181 questions · Page 1/3 · Data Types Variables topic · Answers revealed

1
Multi-Selecthard

A Python programmer is analyzing the results of several expressions. Which TWO of the following expressions evaluate to a float value? (Choose two.)

Select 2 answers
A.4 + 2
B.4.0 // 2
C.4 / 2
D.4 * 2
E.4 // 2
AnswersB, C

The floor division operator // returns a float if either operand is a float. Here, 4.0 is a float, so 4.0 // 2 yields 2.0, which is a float. Even though the operation is floor division, the presence of a float operand forces the result to be a float. Thus, this expression evaluates to a float value.

Why this answer

In Python, the / operator always returns a float, so 4 / 2 yields 2.0. Additionally, floor division // returns a float if either operand is a float, so 4.0 // 2 yields 2.0. The other expressions involve only integers and use operators that return integers when both operands are integers.

Thus, the expressions that evaluate to a float are 4 / 2 and 4.0 // 2.

Exam trap

The trap here is assuming that floor division always returns an integer, but when one operand is a float, the result is a float.

2
MCQhard

What is the output of the following code? print(type(3.0) == float)

A.<class 'bool'>
B.False
C.Error
D.True
AnswerD

The literal 3.0 is a floating-point number, so type(3.0) returns the float class object. Comparing that class object with float using == tests identity of the same built-in type, yielding True. This satisfies the stem's requirement to evaluate the expression's actual output.

Why this answer

The expression `type(3.0) == float` compares the result of `type(3.0)` (which is `<class 'float'>`) directly to the `float` class. In Python, `type()` returns the class object, and comparing it with `==` to the built-in class `float` yields `True` because they are the same object. Therefore, `print(True)` outputs `True`.

Exam trap

Python Institute often tests the distinction between `type()` returning a class object versus a string representation, and candidates mistakenly think `type(3.0)` returns the string `'float'`, leading them to choose `False` or `Error`.

How to eliminate wrong answers

Option A is wrong because `print()` outputs the value of the expression, not its type; the expression evaluates to `True`, which is a boolean, but the output is the string representation `True`, not `<class 'bool'>`. Option B is wrong because the comparison `type(3.0) == float` is `True`, not `False`; a common mistake is thinking `type()` returns a string like `'float'`, but it returns the actual class object. Option C is wrong because the code is syntactically valid and runs without any error; `type(3.0)` is a valid call, and comparing it with `==` to `float` is allowed.

3
MCQhard

A function sometimes returns None. Which expression correctly checks if the return value is not None?

A.if not val is None:
B.if val != None:
C.if val is not None:
D.if val:
AnswerC

The identity operator is not None compares the object reference against the None singleton, which is the correct idiom for checking a missing return value. Equality operators can be overridden by custom __eq__ methods, so 'is not' is safer.

Why this answer

The `is not` operator is the proper way to check identity inequality in Python. Since `None` is a singleton, comparing with `is not` ensures you are checking whether the value is literally the `None` object, which is the recommended and most readable approach for `None` checks.

Exam trap

Python Institute often tests the distinction between identity (`is`) and equality (`==`) operators, and the trap here is that candidates mistakenly use `!= None` (value comparison) instead of `is not None` (identity comparison), or confuse truthiness checks with `None` checks.

How to eliminate wrong answers

Option A is wrong because `if not val is None:` is syntactically valid but confusing and non-idiomatic; it actually means `if not (val is None):` due to operator precedence, which is equivalent to `if val is not None:` but is discouraged for readability. Option B is wrong because `if val != None:` uses value equality (`!=`) instead of identity (`is not`); while it often works due to Python's implementation, it can fail if the object's `__eq__` method is overridden to return `True` when compared to `None`. Option D is wrong because `if val:` checks truthiness, not whether the value is `None`; many falsy values (e.g., `0`, `False`, empty list) would cause the condition to be `False` even though they are not `None`.

4
MCQeasy

A developer writes the following code: result = (5 + 3) * 2 ** 3 // 4. What is the value of result?

A.8
B.16
C.13
D.64
AnswerB

Parentheses force 5 + 3 to evaluate first, giving 8. Exponentiation binds tighter than floor division, so 2 ** 3 yields 8, and 8 * 8 gives 64. Floor division by 4 then returns 16, satisfying Python's precedence order of parentheses, exponent, multiplication, then floor division.

Why this answer

Python follows the operator precedence rules: exponentiation (**) is evaluated before multiplication and division, and multiplication/division are evaluated before addition/subtraction. The expression evaluates as: 2 ** 3 = 8, then (5 + 3) = 8, then 8 * 8 = 64, then 64 // 4 = 16. The integer division (//) yields an integer result of 16.

Exam trap

Python Institute often tests the combination of exponentiation and floor division with parentheses, where candidates forget that ** binds tighter than * and //, leading them to compute (5+3)*2 = 16, then 16**3 = 4096, then 4096//4 = 1024, or they ignore the // and just compute 8*8=64.

How to eliminate wrong answers

Option A is wrong because it assumes the expression is evaluated left-to-right without precedence, e.g., (5+3)=8, then 8*2=16, then 16**3=4096, then 4096//4=1024, which is not 8; or it might incorrectly compute 2**3=8, then 8//4=2, then 8*2=16, but then subtract something incorrectly. Option C is wrong because it likely results from misapplying precedence, e.g., computing (5+3)=8, then 2**3=8, then 8*8=64, then 64/4=16.0 (float) but then rounding or truncating incorrectly to 13, or mixing // with / in a wrong order. Option D is wrong because it ignores the floor division (//) entirely, computing 8 * 8 = 64 and stopping, or it incorrectly treats // as exponentiation again.

5
MCQmedium

A developer needs to store the result of dividing two numbers, a/b, but only if b is not zero. They write: result = a / b if b != 0 else 'undefined'. What is the data type of result when b is zero?

A.float
B.NoneType
C.bool
D.str
AnswerD

When b equals zero, the conditional expression selects the literal 'undefined', a string, so result holds str. The division branch is never evaluated, avoiding ZeroDivisionError; the ternary returns whichever operand's type applies, and here that operand is textual.

Why this answer

When `b` is zero, the expression `a / b if b != 0 else 'undefined'` evaluates to the string literal `'undefined'`. Therefore, the variable `result` is assigned a value of type `str` (string). The conditional expression explicitly returns a string in the else branch, making option D correct.

Exam trap

Python Institute often tests the ternary conditional expression to see if candidates mistakenly think the else branch returns a special 'undefined' value (like in JavaScript) instead of recognizing it as a plain Python string literal.

How to eliminate wrong answers

Option A is wrong because a float is returned only when the division occurs (b != 0); when b is zero, no division happens, so no float is produced. Option B is wrong because NoneType would require the expression to evaluate to `None`, but the else clause explicitly returns the string `'undefined'`, not the Python `None` object. Option C is wrong because a bool would require the expression to evaluate to `True` or `False`, but the else clause returns a string, not a boolean.

6
Matchingmedium

Match each Python control flow statement to its purpose.

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

Concepts
Matches

Exits the current loop immediately

Skips the rest of the current iteration and goes to the next

Does nothing; used as a placeholder

Short for else-if; checks another condition

Executes a block when no previous condition is true

Why these pairings

The correct matches: break exits the loop, continue skips to next iteration, pass does nothing, else runs after normal loop completion. Common confusions include swapping break and continue, or confusing else with pass.

7
Multi-Selecthard

Which THREE of the following statements about Python operators are true?

Select 3 answers
A.The not operator is a logical operator that negates a condition.
B.The // operator performs floor division.
C.The ** operator is the bitwise XOR operator.
D.The / operator always returns an integer if both operands are integers.
E.The % operator returns the remainder of division.
AnswersA, B, E

The `not` operator is a logical (Boolean) operator that inverts the truth value of its operand, returning `True` for a falsy operand and `False` for a truthy one. This directly satisfies the stem's requirement for a true statement about Python operators, as `not` is one of the three logical operators alongside `and` and `or`.

Why this answer

Option A is correct because 'not' is Python's logical negation operator, returning True for a falsy operand and False for a truthy one, so it negates a condition. Option B is correct because '//' performs floor division, dividing operands and rounding the result down to the nearest integer (e.g., 7 // 2 == 3, and -7 // 2 == -4). Option E is correct because '%' is the modulo operator, returning the remainder of integer or float division (e.g., 7 % 3 == 1).

Option C is wrong because '**' is the exponentiation (power) operator, while bitwise XOR is '^'. Option D is wrong because '/' performs true division in Python 3 and always returns a float, even when both operands are integers (e.g., 4 / 2 == 2.0).

Exam trap

Python Institute often tests the Python 3-specific change that the `/` operator always returns a float, trapping candidates who remember the Python 2 behavior where `/` performed integer division on integers.

8
MCQeasy

A beginner writes: x = '10'; y = 20; print(x + y). What happens?

A.Raises TypeError
B.Prints 30
C.Prints 10 + 20
D.Prints 1020
AnswerA

Python does not implicitly convert between str and int, so adding the string '10' to the integer 20 raises TypeError. This satisfies the question by identifying the runtime error produced when concatenation and addition are mixed across incompatible types.

Why this answer

Python's type system does not allow implicit concatenation of a string and an integer. The variable `x` is a string (`'10'`), and `y` is an integer (`20`). The `+` operator with these types triggers a `TypeError: unsupported operand type(s) for +: 'int' and 'str'` (or vice versa), as Python refuses to guess the programmer's intent.

Exam trap

The trap here is that candidates often expect Python to behave like JavaScript or PHP, which implicitly coerce types, but Python strictly requires explicit type conversion for mixed-type operations.

How to eliminate wrong answers

Option B is wrong because it assumes Python will implicitly convert the string to an integer and perform numeric addition, which Python does not do for mixed types. Option C is wrong because it treats the `+` operator as a literal string concatenation in the output, but Python evaluates expressions, not printing the source code. Option D is wrong because it assumes Python will implicitly convert the integer to a string and concatenate them as `'10' + '20'` → `'1020'`, but Python raises a TypeError instead of performing implicit type coercion.

9
MCQmedium

A developer writes: num = input('Enter a number: '); result = num * 2; print(result). If the user enters 5, what is the output?

A.Error: cannot multiply string by int
B.10
C.'5' * 2
D.55
AnswerD

`input()` returns a string, so `num` holds `'5'`, not the integer 5. Multiplying a string by 2 repeats it, giving `'55'`, which `print()` outputs without quotes. The stem's constraint is that no `int()` conversion is applied before the multiplication.

Why this answer

The `input()` function always returns a string. When the user enters '5', `num` is the string '5', not the integer 5. The `*` operator on a string performs repetition, so `'5' * 2` produces '55', which is printed as 55.

Exam trap

Python Institute often tests the misconception that `input()` returns a numeric type when the user types digits, leading candidates to expect arithmetic multiplication instead of string repetition.

How to eliminate wrong answers

Option A is wrong because Python does not raise an error when multiplying a string by an integer; it performs string repetition. Option B is wrong because it assumes `input()` returns an integer, but it returns a string, so numeric multiplication does not occur. Option C is wrong because it shows the raw expression `'5' * 2` as output, but `print()` outputs the resulting string '55', not the expression.

10
MCQeasy

Which data type is the result of: value = 10 // 3?

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

Floor division with `//` discards the fractional part and returns an integer when both operands are integers, so `10 // 3` yields `3`, not `3.333...`. This satisfies the stem's requirement for the exact data type of the result, which is `int`.

Why this answer

The // operator in Python performs floor division, which divides the left operand by the right operand and returns the largest integer less than or equal to the result. Since both 10 and 3 are integers, the result is an integer (3), not a float. Therefore, the data type of value is int.

Exam trap

Python Institute often tests the distinction between / (true division returning float) and // (floor division returning int), trapping candidates who assume all division in Python returns a float.

How to eliminate wrong answers

Option A is wrong because floor division (//) with integer operands always returns an int, not a float; a float result would require the / operator (true division). Option B is wrong because the result is a numeric value, not a string; str would only be produced by explicit conversion or string concatenation. Option D is wrong because the result is a numeric integer, not a Boolean; bool would only be returned by comparison operators (e.g., ==, >) or logical operations.

11
MCQhard

A script uses the input() function to get a user's age: age = input('Enter age: '). Later it computes age > 18. This raises a TypeError. What is the root cause?

A.The input() function cannot read numbers.
B.The variable age is automatically converted to int.
C.The variable age is a string, not an integer.
D.The comparison operator > is not valid for strings.
AnswerC

input() always returns a string in Python 3, so age holds text like "18". Comparing a str with an int using > raises TypeError, since Python won't implicitly coerce types. Converting with int(age) before the comparison resolves it.

Why this answer

The `input()` function in Python always returns a string, regardless of what the user types. When the user enters their age, the variable `age` holds a string like '25', not an integer. Comparing a string to an integer with the `>` operator raises a `TypeError` because Python does not automatically convert strings to numbers for comparison.

Exam trap

Python Institute often tests the misconception that `input()` returns a numeric type when the user types a number, or that Python automatically converts strings to integers for comparison, leading candidates to overlook the need for explicit type conversion.

How to eliminate wrong answers

Option A is wrong because the `input()` function can read numbers, but it reads them as strings — it does not convert them to numeric types. Option B is wrong because the variable `age` is not automatically converted to `int`; Python requires explicit conversion using `int()` or `float()`. Option D is wrong because the `>` operator is valid for strings (it performs lexicographic comparison), but the error arises from comparing a string to an integer, not from the operator being invalid for strings.

12
Multi-Selecteasy

Which TWO of the following are valid Python data types?

Select 2 answers
A.real
B.str
C.array
D.int
E.char
AnswersB, D

str is a built-in Python data type representing text sequences, such as 'hello'. It satisfies the question's requirement to identify a valid data type, since str is one of Python's core immutable types alongside int, float and bool.

Why this answer

Option B (str) is correct because str is a built-in Python data type used to represent immutable sequences of Unicode characters, such as 'hello'. Option D (int) is correct because int is a built-in Python data type for arbitrary-precision integers, e.g., 42. Option A (real) is not a Python built-in type; Python uses float for floating-point numbers.

Option C (array) is not a built-in Python data type, though the array module provides an array class. Option E (char) is not a Python data type; Python represents single characters as strings of length 1.

Exam trap

Python Institute often tests the distinction between Python's built-in types and types from other languages or modules, so candidates mistakenly choose 'real' (from mathematics) or 'char' (from C/Java) because they assume Python uses the same terminology.

13
MCQeasy

A developer writes the following code: x = 5; y = 2; print(x // y). What is the output?

A.1
B.2
C.2.0
D.2.5
AnswerB

The // operator performs floor division, dividing 5 by 2 and rounding the result down to the nearest integer. Since both operands are integers, Python returns an int, and 2.5 floors to 2, matching the printed output.

Why this answer

The floor division operator (//) in Python returns the largest integer less than or equal to the result of the division. Since 5 divided by 2 equals 2.5, the floor is 2, and the result is an integer (int) because both operands are integers. Therefore, the output is 2.

Exam trap

Python Institute often tests the distinction between floor division (//) and true division (/), trapping candidates who confuse the two operators or forget that integer operands produce an integer result with //.

How to eliminate wrong answers

Option A is wrong because 1 would be the result of integer division only if the quotient were truncated toward zero (as in C/C++ with negative numbers) or if the calculation were 5 // 3; here 5 // 2 yields 2, not 1. Option C is wrong because floor division with two integers returns an integer, not a float; 2.0 would only appear if at least one operand were a float (e.g., 5.0 // 2). Option D is wrong because 2.5 is the result of true division (/) not floor division (//); the // operator always discards the fractional part.

14
Multi-Selecthard

Which THREE of the following statements about Python operators are correct?

Select 3 answers
A.The ** operator performs exponentiation.
B.The // operator performs floor division and returns an int if both operands are ints.
C.The / operator always returns a float.
D.The + operator can be used to concatenate strings and integers.
E.The % operator returns the quotient.
AnswersA, B, C

Python's arithmetic operator set includes ** for exponentiation, so 2 ** 3 evaluates to 8. This satisfies the stem's requirement for a correct operator statement, distinguishing it from operators such as ^, which performs bitwise XOR rather than raising to a power.

Why this answer

Option A is correct because in Python the ** operator is the exponentiation operator, so 2 ** 3 evaluates to 8. Option B is correct because // performs floor division, discarding the fractional part, and returns an int when both operands are ints (e.g., 7 // 2 gives 3). Option C is correct because the / operator performs true division and always returns a float, even for evenly divisible integers (e.g., 4 / 2 gives 2.0).

Option D is not correct because + cannot concatenate a string and an integer directly; doing so raises a TypeError unless the integer is converted with str(). Option E is not correct because % is the modulo operator and returns the remainder of a division, not the quotient.

Exam trap

Python Institute often tests the distinction between the / operator (always returns float) and the // operator (returns int when both operands are ints), and the misconception that % returns the quotient instead of the remainder.

15
MCQmedium

A developer writes: total = 2 ** 3 + 4. What is the value of total?

A.16
B.12
C.14
D.10
AnswerB

Exponentiation binds tighter than addition, so 2 ** 3 evaluates first to 8, then 8 + 4 yields 12. The stem's expression therefore assigns 12 to total, not 14 as left-to-right evaluation would wrongly suggest.

Why this answer

In Python, the exponentiation operator (**) has higher precedence than addition (+). Therefore, 2 ** 3 is evaluated first, yielding 8. Then 8 + 4 equals 12.

Option B is correct.

Exam trap

Python Institute often tests operator precedence by combining exponentiation with addition, trapping candidates who mistakenly evaluate left-to-right or confuse ** with multiplication.

How to eliminate wrong answers

Option A is wrong because it incorrectly assumes that addition is performed before exponentiation, computing 2 ** (3 + 4) = 2 ** 7 = 128, or perhaps misinterprets the expression as (2 ** 3) * 2 = 16. Option C is wrong because it likely results from a miscalculation such as 2 ** 3 = 6 (instead of 8) plus 4 = 10, or from misapplying operator precedence. Option D is wrong because it represents the result of 2 * 3 + 4 = 10, confusing the exponentiation operator with multiplication.

16
Multi-Selectmedium

Which THREE of the following expressions evaluate to the integer 1? (Select three.)

Select 3 answers
A.int(1.0)
B.2 // 2
C.True == 1
D.1 * 1.0
E.4 % 3
AnswersA, B, E

int() truncates a float toward zero, discarding the fractional part. Applying it to 1.0 yields the integer 1, satisfying the stem's requirement for an int result rather than a float. This is the explicit type-conversion route to the value 1.

Why this answer

Option A, int(1.0), is correct because Python's int() constructor truncates the float 1.0 toward zero, yielding the integer 1. Option B, 2 // 2, is correct because floor division of 2 by 2 produces the integer quotient 1. Option E, 4 % 3, is correct because the modulo operator returns the remainder of 4 divided by 3, which is the integer 1.

Option C, True == 1, evaluates to the Boolean True rather than the integer 1, even though True is numerically equal to 1 in Python. Option D, 1 * 1.0, evaluates to the float 1.0, not the integer 1, because multiplying an int by a float promotes the result to float.

Exam trap

The PCEP exam often tests the distinction between Boolean `True` and the integer `1`, and the fact that arithmetic with a float operand always yields a float, not an integer.

17
MCQmedium

A Python programmer wants to determine whether the variable n is an even number greater than zero. Which expression correctly evaluates to True only when n is a positive even integer?

A.n % 2 == 0 and n > 0
B.n % 2 == 1 or n > 0
C.n / 2 == 0 and n > 0
D.n // 2 == 0 and n > 0
AnswerA

The modulo operation n % 2 yields the remainder when n is divided by 2. For even integers the remainder is 0, so n % 2 == 0 is True. The comparison n > 0 ensures the number is positive. Combining them with and requires both conditions to hold, which exactly matches the requirement of a positive even integer.

Why this answer

Even numbers leave a remainder of zero when divided by two, which the modulo operator % detects. The comparison n > 0 filters out zero and negative values. Joining these with the logical and operator yields True only for positive even integers.

Division and floor division do not test divisibility by two, and using or would accept odd values.

Exam trap

The trap here is confusing the division operator with the modulo operator, or using or instead of and, which would admit odd or non-positive numbers.

18
MCQhard

Given x = 5, which of the following assignments will cause a runtime error?

A.x **= 2
B.x -= 3
C.x //= 0
D.x += 2
AnswerC

Floor division by zero raises ZeroDivisionError at runtime, since Python cannot compute an integer quotient when the divisor is zero. The augmented assignment evaluates x // 0 immediately, satisfying the stem's condition of causing a runtime error rather than a syntax or name error.

Why this answer

Division by zero is undefined in Python, and the floor division assignment operator `//=` with a divisor of 0 raises a `ZeroDivisionError` at runtime. The other operators (`**=`, `-=`, `+=`) perform valid arithmetic on the integer 5 and do not cause errors.

Exam trap

The trap here is that candidates may mistakenly think any operator can handle zero as a divisor or confuse floor division with modulo, but The PCEP exam specifically tests that `//` with a zero divisor raises a runtime error, not a syntax error or silent failure.

How to eliminate wrong answers

Option A is wrong because `x **= 2` raises 5 to the power of 2, resulting in 25, which is a valid integer operation. Option B is wrong because `x -= 3` subtracts 3 from 5, yielding 2, a perfectly legal assignment. Option D is wrong because `x += 2` adds 2 to 5, producing 7, with no error.

Only division by zero triggers a runtime exception.

19
MCQeasy

Refer to the exhibit. What is the cause of the error?

A.Using + on incompatible types (str and int)
B.Division by zero
C.Missing import statement
D.Variable not defined
AnswerA

The plus operator cannot concatenate a string with an integer; Python raises TypeError because the operands' types are incompatible. The exhibit's error stems from mixing str and int with +, which requires explicit conversion of the integer via str() before concatenation can succeed.

Why this answer

The error occurs because the `+` operator is being used between a string and an integer, which are incompatible types in Python. Python does not implicitly convert the integer to a string for concatenation; it raises a `TypeError: unsupported operand type(s) for +: 'str' and 'int'`.

Exam trap

Python Institute often tests the misconception that Python will automatically convert types (like JavaScript does), leading candidates to think the code will run without error, when in fact Python raises a TypeError for mixed-type `+` operations.

How to eliminate wrong answers

Option B is wrong because division by zero would raise a `ZeroDivisionError`, not a type-related error. Option C is wrong because no import statement is required for basic arithmetic or string operations in Python; the error is purely about type mismatch. Option D is wrong because the variable is defined (the error message would be `NameError` if it were not), and the actual error is a `TypeError` from using `+` on incompatible types.

20
MCQmedium

A program prints a greeting: name = input("Enter name: "); print("Hello, " + name + "!"). If user enters "Alice", what is output?

A.Hello, Alice!
B.Hello,Alice !
C.Hello,Alice!
D.Hello, Alice !
AnswerA

The `input()` function returns the entered text as a string, so `name` holds `"Alice"`. String concatenation with `+` joins `"Hello, "`, `"Alice"`, and `"!"` in sequence, producing exactly `Hello, Alice!` with no added spaces beyond those already inside the literals.

Why this answer

The `print` function concatenates the string literals and the variable `name` using the `+` operator exactly as specified. When the user enters "Alice", the expression `"Hello, " + name + "!"` becomes `"Hello, Alice!"` — the space after the comma is part of the first string literal, and the exclamation mark is part of the last string literal, producing the output exactly as shown in option A.

Exam trap

Python Institute often tests whether candidates notice the exact placement of spaces and punctuation in string literals, exploiting the common assumption that Python automatically adds spaces around concatenated values.

How to eliminate wrong answers

Option B is wrong because it shows a space after the exclamation mark (`Alice !`), but the code has no space before the exclamation mark in the string literal `"!"`. Option C is wrong because it omits the space after the comma (`Hello,Alice!`), but the first string literal `"Hello, "` includes a trailing space. Option D is wrong because it adds an extra space before the exclamation mark (`Alice !`), which is not present in the concatenation; the code joins `name` directly to `"!"` with no intervening space.

21
MCQeasy

What is the output of the following code? ```python print('Hello', 'World', sep='-') ```

A.HelloWorld
B.Hello - World
C.Hello World
D.Hello-World
AnswerD

Passing `sep='-'` overrides the default single-space separator that `print()` inserts between multiple arguments, so the two strings are joined by a hyphen instead. The output is therefore `Hello-World`, satisfying the stem's requirement to show the exact printed result.

Why this answer

The `print()` function's `sep` parameter specifies the separator between multiple arguments. By default, `sep` is a space, but here it is explicitly set to `'-'`, so the output joins 'Hello' and 'World' with a hyphen, producing 'Hello-World'. Option D is correct because the hyphen is placed directly between the two strings without any extra spaces.

Exam trap

The trap here is that candidates often assume the default space separator is used or misread the hyphen as a space, leading them to choose 'Hello World' instead of recognizing the explicit `sep='-'` override.

How to eliminate wrong answers

Option A is wrong because it omits the separator entirely, as if `sep=''` were used, but the default or specified separator is not empty. Option B is wrong because it adds spaces around the hyphen, which would only happen if the separator included spaces or if extra arguments were printed; the `sep` parameter does not add spaces unless they are part of the separator string. Option C is wrong because it uses a space as the separator, which is the default behavior, but the code explicitly overrides it with `sep='-`.

22
MCQhard

A developer needs to store a large collection of unique user IDs (integers) and quickly check if a new ID already exists. Which data type is most appropriate for this task?

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

A set stores unique elements and provides average O(1) membership testing, so checking whether an ID already exists is fast. Lists allow duplicates and require linear scans, making a set the appropriate structure for large collections of unique integers.

Why this answer

A set is the most appropriate data type because it stores unordered collections of unique elements and provides O(1) average-time complexity for membership testing using the `in` operator. This makes it ideal for quickly checking if a new user ID already exists without needing to manage keys or maintain order.

Exam trap

Python Institute often tests the misconception that a dict is required for any kind of lookup, when in fact a set is the correct choice for membership testing without associated data.

How to eliminate wrong answers

Option A is wrong because a dict stores key-value pairs, which adds unnecessary overhead when only the IDs themselves need to be stored and checked. Option B is wrong because a list requires O(n) linear search to check membership, which is inefficient for large collections. Option D is wrong because a tuple is immutable and does not support efficient membership testing; it also cannot be modified to add new IDs after creation.

23
MCQmedium

Evaluate the expression: not (True or False) and (False or True). What is the result?

A.SyntaxError
B.True
C.False
D.None
AnswerC

Evaluating the parentheses first: `(True or False)` yields True, and `(False or True)` yields True. Applying `not` to the first gives False, since `not True` is False. The final `and` combines False with True, producing False, satisfying the Boolean precedence rules tested here.

Why this answer

The expression is evaluated step by step: first, `True or False` evaluates to `True`; then `False or True` evaluates to `True`; the `not` operator negates the first `True` to `False`; finally, `False and True` evaluates to `False`. Therefore, the correct answer is C.

Exam trap

The trap here is that candidates often forget the precedence of `not` over `and` and `or`, or misapply short-circuit evaluation, leading them to incorrectly compute the result as `True`.

How to eliminate wrong answers

Option A is wrong because the expression uses valid Python operators and boolean values, so no SyntaxError occurs. Option B is wrong because the result is not True; the `not` operator negates the first `True` to `False`, and the `and` operator then yields `False`. Option D is wrong because the expression does not involve any function or operation that returns `None`; it produces a boolean value.

24
MCQhard

A developer wrote: x = 10; y = 5; x += y * 2. What are the values of x and y after execution?

A.x=15, y=5
B.x=30, y=5
C.x=20, y=5
D.x=20, y=10
AnswerC

Compound assignment evaluates the right-hand side first: y * 2 gives 10, then x += 10 adds it to the existing 10, yielding 20. Because the multiplication binds tighter than the augmented addition, y is never reassigned and retains its original value of 5, satisfying the stem's requirement.

Why this answer

The expression `x += y * 2` is evaluated as `x = x + (y * 2)`. Given `x = 10` and `y = 5`, `y * 2` equals 10, then `x + 10` equals 20, so `x` becomes 20. The value of `y` remains unchanged at 5 because the assignment operator `+=` only modifies `x`.

Exam trap

The PCEP exam often tests the misconception that `x += y * 2` means `(x + y) * 2`, leading candidates to pick 30, or that `y` is also modified, causing confusion with the assignment operator's scope.

How to eliminate wrong answers

Option A is wrong because it incorrectly assumes `x += y * 2` is evaluated as `(x + y) * 2`, which would give 30, but then mistakenly halves it to 15; the correct evaluation order gives 20. Option B is wrong because it assumes the multiplication applies to the entire right-hand side as `(x + y) * 2`, yielding 30, but Python's operator precedence dictates `*` binds tighter than `+=`, so only `y * 2` is multiplied. Option D is wrong because it incorrectly changes `y` to 10, but the `+=` operator only updates `x` and does not modify `y`.

25
Multi-Selecteasy

Which TWO of the following are valid Python variable names?

Select 2 answers
A._count
B.my_var
C.var-name
D.2nd_var
E.var name
AnswersA, B

Leading underscores are permitted as the first character of an identifier, so `_count` is a valid Python variable name. It satisfies the stem's requirement by starting with a letter or underscore rather than a digit, and containing only alphanumeric characters and underscores, with no reserved keyword conflict.

Why this answer

Option A, `_count`, is a valid Python variable name because it begins with an underscore, which is an allowed identifier character, and contains only letters and underscores. Option B, `my_var`, is also valid since it starts with a letter and uses only letters and underscores, conforming to Python's identifier rules (letters, digits, and underscores, not starting with a digit). Option C, `var-name`, is invalid because hyphens are not permitted in Python identifiers; the hyphen would be parsed as a subtraction operator.

Option D, `2nd_var`, is invalid because an identifier cannot begin with a digit. Option E, `var name`, is invalid because spaces are not allowed in identifiers.

Exam trap

Python Institute often tests the rule that hyphens and spaces are invalid in variable names, as candidates may confuse Python with other languages (like Lisp or CSS) where hyphens are allowed, or mistakenly think spaces can be used for readability.

26
MCQeasy

A Python script contains the following assignment: `value = 5` followed by `result = value * '2'`. What is the value of `result` after these statements execute?

A.A `TypeError` is raised.
B.`'22222'`
C.`'10'`
D.`10`
AnswerB

In Python, when the `*` operator has an integer and a string as operands, it performs repetition: the string is repeated that many times. With `value = 5` and the string `'2'`, the expression `value * '2'` produces the string `'22222'`, a five-character string. This is valid because string repetition is supported when one operand is an integer.

Why this answer

The multiplication operator `*` behaves differently depending on operand types. When one operand is an integer and the other is a string, Python repeats the string that many times. With `value = 5` and string `'2'`, the result is `'22222'`.

This is a common source of confusion for beginners who expect numeric multiplication or implicit type conversion. Recognizing the operand types is essential to predicting the outcome correctly.

Exam trap

The trap here is assuming that `*` always performs numeric multiplication, leading to an expectation of implicit conversion or a numeric result instead of string repetition.

27
MCQmedium

A Python script reads this JSON and needs to check if port 8080 is allowed. Which expression correctly checks? Assume data is already parsed into a dictionary.

A.data["ports"].contains(8080)
B.data.get("ports") == 8080
C.8080 in data["ports"]
D."ports" in data
AnswerC

Testing `8080 in data["ports"]` uses the `in` operator against the list, performing a membership check that returns `True` when the integer 8080 appears among the parsed values. This satisfies the stem's requirement to verify whether port 8080 is permitted, without iterating manually or comparing types incorrectly.

Why this answer

The `in` operator checks for membership in a list. Since `data["ports"]` is a list (e.g., `[80, 443, 8080]`), `8080 in data["ports"]` returns `True` if 8080 is present. This directly tests whether port 8080 is allowed.

Exam trap

Python Institute often tests the distinction between checking for a key in a dictionary (`key in dict`) versus checking for a value in a list (`value in list`), and candidates mistakenly use `contains()` (from Java or other languages) or confuse dictionary key existence with list membership.

How to eliminate wrong answers

Option A is wrong because `contains()` is not a built-in method for Python lists; the correct method is `list.count()` or the `in` operator. Option B is wrong because `data.get("ports")` returns the entire list, not a single integer, so comparing it with `== 8080` will always be `False`. Option D is wrong because `"ports" in data` checks if the key `"ports"` exists in the dictionary, not whether port 8080 is in the list of allowed ports.

28
MCQhard

A developer needs to check if a variable x is between 10 and 20 (inclusive). Which expression is correct?

A.x > 10 and x < 20
B.x < 10 and x < 20
C.10 <= x <= 20
D.x >= 10 or x <= 20
AnswerC

Python supports chained comparison operators, so 10 <= x <= 20 evaluates as (10 <= x) and (x <= 20). Both bounds are inclusive because <= is used, satisfying the stem's requirement to include 10 and 20 themselves. This is the idiomatic single expression for range checking.

Why this answer

Python supports chained comparison operators, allowing `10 <= x <= 20` to evaluate whether `x` is between 10 and 20 inclusive. This expression is equivalent to `(10 <= x) and (x <= 20)`, which checks both boundaries simultaneously.

Exam trap

The trap here is that candidates often confuse inclusive vs. exclusive boundaries and select Option A with strict inequalities, or they misunderstand that `or` (Option D) creates a condition that is always true, failing to recognize the need for `and` logic.

How to eliminate wrong answers

Option A is wrong because it uses strict inequality operators (`>` and `<`), which exclude the boundary values 10 and 20, so it checks for values strictly between 10 and 20, not inclusive. Option B is wrong because `x < 10 and x < 20` is equivalent to `x < 10`, which only checks if x is less than 10, completely missing the upper bound and the inclusive requirement. Option D is wrong because the `or` operator means the condition is true if x is either greater than or equal to 10 OR less than or equal to 20, which is always true for any real number, making it a tautology.

29
Multi-Selectmedium

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

Select 3 answers
A.str
B.int
C.float
D.list
E.dict
AnswersA, B, C

Strings cannot be altered after creation; any operation such as concatenation or upper() returns a new str object rather than modifying the original. This immutability is what allows strings to be used as dictionary keys and satisfies the question's requirement for immutable types.

Why this answer

In Python, str (A) is immutable because string objects cannot be modified in place—operations like concatenation or replace() return a new string rather than altering the original. int (B) is immutable since integer objects have a fixed value once created, and arithmetic operations produce new int objects instead of changing existing ones. float (C) is likewise immutable, as floating-point values cannot be changed after creation and any arithmetic yields a new float object. By contrast, list (D) is mutable because elements can be added, removed, or reassigned in place, and dict (E) is mutable because key-value pairs can be inserted, updated, or deleted after the dictionary is created.

Exam trap

Python Institute often tests the misconception that all numeric types are mutable or that strings can be changed in place, leading candidates to incorrectly select list or dict as immutable.

30
MCQhard

A network engineer uses bitwise operators to set flags for packet filtering. The variable 'flags' currently holds the integer 10 (binary 1010). To enable the second bit (value 2) and disable the fourth bit (value 8), which expression should be used?

A.flags = flags | 2
B.flags = flags ^ 10
C.flags = flags & ~8
D.flags = (flags | 2) & ~8
AnswerD

Correctly sets bit 1 and clears bit 3

Why this answer

It combines two operations in a single expression: first, it sets the second bit (value 2) using the bitwise OR (|) operator, which turns on that bit without affecting others; second, it clears the fourth bit (value 8) using the bitwise AND with the complement of 8 (& ~8), which forces that bit to 0. This achieves the required flag state: binary 1010 becomes 0010 (decimal 2).

Exam trap

Python Institute often tests the misconception that a single operator (like OR or AND alone) can both set and clear bits, leading candidates to pick Option A or C, when in reality you must combine both operations to independently control different bits.

How to eliminate wrong answers

Option A is wrong because it only sets the second bit (flags = flags | 2) but does not disable the fourth bit, leaving the result as 1010 (10) unchanged since bit 2 is already set. Option B is wrong because XOR with 10 (binary 1010) toggles bits: it would flip the second bit (0→1) and the fourth bit (1→0), resulting in 0000 (0), which disables the fourth bit but also incorrectly toggles other bits, not matching the requirement to only enable bit 2 and disable bit 4. Option C is wrong because it only clears the fourth bit (flags = flags & ~8) but does not enable the second bit, leaving the result as 0010 (2) if the second bit was already set, but if it were not set, it would remain 0; in this case, flags is 10 (1010), so bit 2 is already 1, but the expression does not guarantee enabling it if it were 0.

31
MCQmedium

Which operator is used to check if two values are equal in Python?

A.=
B.eq
C.!=
D.==
AnswerD

The `==` operator performs a value equality comparison, returning `True` when both operands hold equivalent values and `False` otherwise. This directly satisfies the stem's requirement to check whether two values are equal, unlike `=` which assigns, or `is` which tests object identity rather than value equivalence.

Why this answer

The == operator is Python's equality comparison operator, used to check if two values are equal. It returns True if the values are equal and False otherwise, making it the standard way to test equality in conditions and expressions.

Exam trap

Python Institute often tests the confusion between the assignment operator = and the equality operator ==, as beginners mistakenly use = in conditions like if x = 5 instead of if x == 5, which causes a syntax error or unintended assignment.

How to eliminate wrong answers

Option A is wrong because = is the assignment operator in Python, used to assign a value to a variable, not to compare values. Option B is wrong because eq is not a built-in operator in Python; while some objects may have an __eq__() method for custom equality, eq alone is not a valid operator. Option C is wrong because != is the inequality operator, which checks if two values are not equal, the opposite of what the question asks.

32
MCQeasy

Which operator performs integer (floor) division in Python?

A.//
B.%
C./
D.**
AnswerA

The `//` operator performs floor division, dividing two numbers and rounding the result down to the nearest integer. For positive operands it discards the fractional part, satisfying the stem's requirement for integer division; unlike `/`, which always returns a float, `//` yields an integer when both operands are integers.

Why this answer

The // operator performs integer (floor) division in Python, which divides two numbers and returns the largest integer less than or equal to the result. For example, 7 // 2 returns 3, not 3.5, because it discards the fractional part and rounds down toward negative infinity for negative numbers.

Exam trap

Python Institute often tests the distinction between / (true division) and // (floor division), trapping candidates who assume / performs integer division as in some other languages like C or Java.

How to eliminate wrong answers

Option B (%) is wrong because it is the modulo operator, which returns the remainder of a division, not the quotient. Option C (/) is wrong because it performs true (floating-point) division, always returning a float result (e.g., 7 / 2 = 3.5). Option D (**) is wrong because it is the exponentiation operator, used for raising a number to a power (e.g., 2 ** 3 = 8).

33
MCQeasy

Based on the exhibit, which expression returns 2.5 in Python?

A.int(5 / 2)
B.5 % 2
C.5 // 2
D.5 / 2
AnswerD

Python 3's division operator always performs true division on integers, so 5 / 2 yields the float 2.5 rather than the floored integer 2. Floor division (//) would return 2, and integer operands do not otherwise produce a float result.

Why this answer

The division operator `/` in Python always returns a float, even when dividing two integers. Since 5 divided by 2 equals 2.5, the expression `5 / 2` returns the float `2.5`.

Exam trap

Python Institute often tests the distinction between `/` (true division returning float) and `//` (floor division returning integer), trapping candidates who confuse the two or expect integer division from `/` as in Python 2.

How to eliminate wrong answers

Option A is wrong because `int(5 / 2)` first computes `5 / 2` to get `2.5`, then `int()` truncates the decimal part, returning the integer `2`, not `2.5`. Option B is wrong because the modulo operator `%` returns the remainder of the division, which is `1` (since 5 divided by 2 gives quotient 2 and remainder 1), not `2.5`. Option C is wrong because the floor division operator `//` performs integer division and returns the integer quotient `2` (truncating toward negative infinity for positive numbers), not `2.5`.

34
MCQeasy

A program asks for the user's age and then prints a message: age = input("How old are you? "); print("You are " + age + " years old."). A user enters "twenty five" and the program prints "You are twenty five years old." which is not the intended numeric age. The requirement is to ensure only numeric ages are accepted and to convert the input to an integer. Which modification is the best?

A.Use try-except to catch ValueError and print an error message, then exit.
B.Check if age.isdigit() before converting, and if not, ask again.
C.Assume the user will always enter a number; no changes needed.
D.Use a try-except in a loop to repeatedly ask until valid integer is entered: while True: try: age = int(input("How old are you? ")) break except ValueError: print("Invalid.")
AnswerD

Wrapping int() in try-except inside a while loop rejects non-numeric input with ValueError handling and re-prompts until a valid integer is supplied, satisfying the requirement to accept only numeric ages and convert them to int.

Why this answer

It uses a `while True` loop with a `try-except` block to repeatedly prompt the user until a valid integer is entered. The `int()` conversion raises a `ValueError` for non-numeric strings like "twenty five", and the `except` clause catches that error and prints "Invalid." without breaking the loop, ensuring only numeric ages are accepted and converted to an integer.

Exam trap

The trap here is that candidates often choose Option B (isdigit) thinking it is sufficient, but they overlook that `isdigit()` does not handle spaces or negative numbers and does not loop to re-prompt, while the correct solution must combine error handling with a loop to meet the requirement of repeatedly asking until valid input is provided.

How to eliminate wrong answers

Option A is wrong because it uses `try-except` to catch `ValueError` and then exits the program, which does not meet the requirement to keep asking until a valid numeric age is entered; it only handles the error once and terminates. Option B is wrong because `age.isdigit()` returns `False` for strings with spaces (like "twenty five"), but it does not handle the case where the user enters a valid numeric string with leading zeros (e.g., "025") which would pass `isdigit()` but `int()` would convert correctly; more importantly, it does not loop to re-prompt after a failed check, so the program would stop or proceed with invalid data. Option C is wrong because it assumes the user will always enter a number, which is unsafe and does not handle the given input "twenty five" — the program would print the string as-is without conversion, failing the requirement to accept only numeric ages and convert to integer.

35
MCQhard

A program checks divisibility. Which condition correctly determines if a number n is divisible by 7?

A.n / 7 == 0
B.n // 7 == 0
C.n % 7 == 0
D.n % 7 != 0
AnswerC

The modulo operator returns the remainder of integer division, so n % 7 yields zero exactly when seven divides n without a remainder. This directly satisfies the stem's divisibility requirement, correctly identifying multiples of 7 including zero, unlike division or comparison operators that would not test remainder.

Why this answer

The modulo operator (%) returns the remainder of the division of n by 7. If the remainder is 0, then n is exactly divisible by 7. This is the standard way to test divisibility in Python.

Exam trap

The PCEP exam often tests the distinction between division operators (/, //, %) and expects candidates to know that only the modulo operator (%) correctly checks divisibility, not the quotient operators.

How to eliminate wrong answers

Option A is wrong because the division operator (/) returns a float, and comparing a float to 0 will almost never be True for integer divisibility (e.g., 7/7 == 1.0, not 0). Option B is wrong because floor division (//) returns the integer quotient, which is 0 only when n is less than 7 (e.g., 5//7 == 0), not when n is divisible by 7. Option D is wrong because n % 7 != 0 is the condition for non-divisibility, the exact opposite of what is required.

36
MCQhard

A developer runs the following code: x = 0.1; y = 0.2; print(x + y == 0.3). What is the output and why?

A.False, because the + operator is not defined for floats
B.True, because Python rounds to 0.3
C.True, because Python uses decimal arithmetic
D.False, due to floating-point precision
AnswerD

Binary floating-point cannot represent 0.1, 0.2 or 0.3 exactly, so their stored approximations sum to 0.30000000000000004 rather than 0.3. The equality test therefore returns False, satisfying the stem's requirement to explain the output of comparing x + y against 0.3.

Why this answer

Floating-point numbers in Python (and most programming languages) are stored in binary (IEEE 754 double-precision), and values like 0.1 and 0.2 cannot be represented exactly. The sum 0.1 + 0.2 yields a result slightly greater than 0.3 (approximately 0.30000000000000004), so the equality comparison returns False.

Exam trap

Python Institute often tests the misconception that Python performs exact decimal arithmetic, leading candidates to expect True, when in fact the binary floating-point representation causes a small rounding error that makes the comparison False.

How to eliminate wrong answers

Option A is wrong because the + operator is fully defined for floats in Python and performs arithmetic addition. Option B is wrong because Python does not round the result of 0.1 + 0.2 to exactly 0.3; the internal binary representation causes a tiny error. Option C is wrong because Python uses binary floating-point arithmetic (IEEE 754), not decimal arithmetic; decimal arithmetic would require the decimal module.

37
MCQeasy

A cashier script stores a product's unit price as a string read from a barcode label: price = '4.50'. The developer must compute the total for 3 units and print a numeric result. Which code produces the value 13.5?

A.total = float(price) * 3
B.total = price * 3
C.total = str(price) * 3
D.total = int(price) * 3
AnswerA

float(price) parses the string '4.50' into the floating-point number 4.5, and multiplying by the integer 3 yields 13.5. This is the only option that both converts the text to a numeric type and performs arithmetic, so the printed value is the expected decimal total rather than a repeated string.

Why this answer

The price arrives as text, so it must be converted with float() before multiplication. float('4.50') becomes 4.5, and 4.5 * 3 evaluates to 13.5. Using int() fails on the decimal point, while string repetition produces concatenated text. The correct approach converts first, then computes.

Exam trap

The trap here is assuming that any arithmetic on a numeric-looking string performs math, when Python instead repeats the string or raises an error depending on the operator.

38
MCQmedium

A developer accidentally wrote: print('Hello' + 5). What happens?

A.It prints 'Hello' and ignores the 5
B.It prints a warning but still runs
C.It raises a TypeError
D.It prints 'Hello5'
AnswerC

Concatenating a string with an integer using `+` raises a TypeError, because Python's `+` operator requires both operands to be the same sequence type. The string `'Hello'` cannot be implicitly converted to an integer, nor the `5` to a string, so the interpreter halts execution rather than coercing types.

Why this answer

In Python, the `+` operator is overloaded for string concatenation only when both operands are strings. Attempting to concatenate a string (`'Hello'`) with an integer (`5`) violates Python's strong dynamic typing rules, which do not perform implicit type coercion for this operation. This raises a `TypeError` with a message like 'can only concatenate str (not "int") to str'.

Exam trap

The trap here is that candidates from languages like JavaScript or PHP, which perform implicit type coercion (e.g., `'Hello' + 5` yields `'Hello5'`), assume Python behaves similarly, but Python's strict typing requires explicit conversion.

How to eliminate wrong answers

Option A is wrong because Python does not silently ignore the integer; it raises an exception instead of discarding the operand. Option B is wrong because Python does not issue a warning for type mismatches in concatenation; it immediately raises a `TypeError` and halts execution. Option D is wrong because Python does not automatically convert the integer to a string for concatenation; that would require an explicit `str()` call or an f-string.

39
MCQmedium

A developer runs this code: a = 10 b = 3 a += b * 2 a //= b print(a) What is printed?

A.5.333333333333333
B.3
C.6
D.5
AnswerD

The expression b * 2 is 6, so a += 6 makes a equal 16. Then a //= b performs floor division by 3, and 16 // 3 is 5 because 5 * 3 is 15 with 1 left over. The result is an int, so print outputs 5. This follows augmented assignment and operator precedence correctly.

Why this answer

Augmented assignment evaluates the right-hand side first, so b * 2 is 6 and a becomes 16. The floor division assignment a //= b then divides 16 by 3 and rounds down to 5. Because both operands are ints, the result stays an int and print displays 5 without a decimal point.

Exam trap

The trap here is reading a //= b as true division and expecting a fractional result, when //= always floors the quotient.

40
MCQhard

A script uses the // operator with negative numbers. For example, -7 // 2 returns -4. The developer expected -3. Which statement best explains this behavior?

A.The // operator uses banker's rounding.
B.The // operator truncates toward zero for negative numbers.
C.The // operator performs integer division with rounding to the nearest even integer.
D.The // operator performs floor division, which rounds down to the next lower integer.
AnswerD

Floor division returns the largest integer less than or equal to the true quotient. For -7 // 2, the exact quotient is -3.5, and flooring gives -4, not truncation toward zero, which would yield -3.

Why this answer

In Python, the // operator performs floor division, which always rounds down to the next lower integer (toward negative infinity). For -7 // 2, the exact result is -3.5, and floor division rounds down to -4, not -3. This behavior is defined by the Python language specification and differs from truncation toward zero.

Exam trap

Python Institute often tests the distinction between floor division (rounding down) and truncation toward zero, exploiting the common misconception that integer division always discards the fractional part, which is true in languages like C or Java but not in Python.

How to eliminate wrong answers

Option A is wrong because banker's rounding (round half to even) is not used by the // operator; it applies to the round() function in some contexts. Option B is wrong because truncation toward zero would give -3 for -7 // 2, but Python's // operator does not truncate toward zero; it floors toward negative infinity. Option C is wrong because integer division with rounding to the nearest even integer is not a standard Python behavior for //; the operator always floors, not rounds.

41
Multi-Selecthard

Which THREE of the following expressions evaluate to True?

Select 3 answers
A.3 == 3
B.1 < 0
C.'a' < 'b'
D.4 > 5
E.2 != 1
AnswersA, C, E

Comparing two identical integer literals with the equality operator returns True, since `==` tests value equality rather than object identity. This satisfies the stem's requirement for an expression evaluating to True, and it is one of the three correct selections.

Why this answer

Option A (3 == 3) is correct because the equality operator compares the two integer literals 3 and 3, which are identical, so the expression evaluates to True. Option C ('a' < 'b') is correct because Python compares strings lexicographically by Unicode code point, and the code point of 'a' (97) is less than that of 'b' (98), yielding True. Option E (2 != 1) is correct because the inequality operator returns True when the operands differ, and 2 is not equal to 1.

Option B (1 < 0) is not correct because 1 is greater than 0, so the less-than comparison evaluates to False. Option D (4 > 5) is not correct because 4 is less than 5, so the greater-than comparison evaluates to False.

Exam trap

Python Institute often tests the distinction between value comparison and assignment, but here the trap is that candidates may misread the operators (e.g., thinking '<' means 'less than or equal') or forget that string comparison uses Unicode order, not length or alphabetical position in a different locale.

42
MCQhard

Refer to the exhibit. The code used is: name = input('Enter name: '); print('Hello', name). What will be printed if the user enters 'Alice'?

A.Hello Bob
B.Error
C.Hello Alice
D.Hello name
AnswerC

The comma in `print('Hello', name)` inserts a single space between its arguments, so the output is `Hello Alice`. This satisfies the stem's exact input, `Alice`, and the requirement to show precisely what the program prints, including that separating space.

Why this answer

The `input()` function captures the user's typed input as a string, and the `print()` function outputs the string 'Hello ' followed by the value of the `name` variable. When the user enters 'Alice', `name` becomes 'Alice', so the output is 'Hello Alice'.

Exam trap

Python Institute often tests whether candidates understand that `input()` returns the actual typed value, not a predefined string, and that `print()` with a comma separator adds a space automatically, which can confuse those expecting concatenation with `+`.

How to eliminate wrong answers

Option A is wrong because the code does not assign 'Bob' to the variable; it uses `input()` to read whatever the user types, so 'Hello Bob' would only appear if the user entered 'Bob'. Option B is wrong because the code is syntactically valid — `input()` returns a string, and `print()` can concatenate a string literal with a variable using a comma, which adds a space automatically. Option D is wrong because `name` is a variable, not the literal string 'name'; the `print()` function outputs the value of the variable, not its name.

43
Multi-Selecthard

Which THREE of the following are valid Python variable names?

Select 3 answers
A.myVar2
B.my-var
C._myVar
D.value
E.2ndValue
AnswersA, C, D

`myVar2` satisfies Python's identifier rules: it begins with a letter, contains only letters and digits, and avoids reserved keywords. Python permits digits after the first character, so the trailing `2` is valid. It also respects case sensitivity and the prohibition on starting with a numeral, making it a legal variable name.

Why this answer

Option A, myVar2, is a valid Python identifier because it starts with a letter and contains only letters and digits, with no reserved characters. Option C, _myVar, is valid because a leading underscore is permitted in Python identifiers and is commonly used to signal internal or private names. Option D, value, is valid because it is a plain sequence of letters that does not collide with any Python keyword.

Option B, my-var, is invalid because the hyphen is not allowed in identifiers and would be parsed as subtraction. Option E, 2ndValue, is invalid because Python identifiers cannot begin with a digit.

Exam trap

Python Institute often tests the rule that hyphens are invalid in identifiers, tempting candidates who are used to hyphenated names from other contexts, and also tests that leading digits are forbidden, catching those who think numbers can appear anywhere.

44
MCQhard

Refer to the exhibit. What is the printed value?

A.27
B.5
C.21
D.35
AnswerD

Tracing the exhibit's arithmetic yields 35, so this printed value matches the interpreter's evaluated output. The expression's operator precedence and variable assignments resolve exactly to this integer, satisfying the stem's requirement for the actual console result rather than a rounded or misordered alternative.

Why this answer

The expression in the exhibit is (2+3)*(5+2). Parentheses have the highest precedence, so we first evaluate the two addition operations: 2+3=5 and 5+2=7. Then we multiply the results: 5*7=35.

Therefore, the printed value is 35, corresponding to option D.

Exam trap

Candidates may ignore the parentheses and apply default operator precedence (multiplication before addition), leading to an incorrect result such as 2+3*5+2=19 (not an option) or possibly misinterpreting the expression. The correct approach is to respect the parentheses.

How to eliminate wrong answers

Option A (27) is wrong because it likely results from incorrectly applying left-to-right evaluation without respecting precedence, e.g., `(5+4)*3` = 27, ignoring exponentiation and multiplication precedence. Option B (5) is wrong because it would only occur if all operations after the first addition were ignored or if the expression was truncated. Option C (21) is wrong because it might come from evaluating `5 + 4 * 3` = 17 and then adding `2 * 3` = 6, but omitting the exponentiation step.

Option D (35) is the correct result based on proper Python operator precedence.

45
Multi-Selecthard

A developer is reviewing operators in Python. Which TWO of the following statements about comparison and logical operators are correct? (Choose two.)

Select 2 answers
A.The expression 'a' == 'A' evaluates to True because comparisons ignore case.
B.The expression 3 < 5 < 8 is evaluated as (3 < 5) and (5 < 8).
C.The or operator always evaluates both of its operands before returning a result.
D.The and operator returns the first operand if it is falsy, otherwise the second operand.
E.The expression not 0 evaluates to False because 0 is a number.
AnswersB, D

Python supports chained comparisons, so 3 < 5 < 8 is treated as a conjunction of two comparisons rather than evaluating 3 < 5 to a boolean and then comparing that boolean with 8. The middle operand 5 is evaluated only once. Both parts are true, so the whole expression is true, and this chaining feature makes range checks more concise and readable.

Why this answer

Python evaluates chained comparisons as a series of and-ed comparisons, evaluating the middle operand once, and its logical operators return operands rather than forcing booleans while short-circuiting. Recognizing these two behaviors explains idioms like range checks and default-value fallbacks. The other statements misstate case sensitivity of strings, short-circuit evaluation of or, and the truthiness of zero.

Exam trap

The trap here is assuming logical operators always produce True or False and that comparison chains behave like sequential boolean comparisons.

46
Multi-Selectmedium

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

Select 3 answers
A.array
B.bool
C.char
D.float
E.int
AnswersB, D, E

As a built-in Boolean type, `bool` is one of Python's core scalar types, alongside `int`, `float`, `complex` and `str`. It satisfies the stem's requirement for built-in data types because it is implemented directly in the interpreter, requiring no import, and instances return `True` or `False`.

Why this answer

Option B (bool) is a Python built-in type used for the two truth values True and False, and it is a subclass of int. Option D (float) is a built-in numeric type representing double-precision floating-point numbers such as 3.14. Option E (int) is a built-in numeric type for arbitrary-precision integers, so it is correct as well.

Option A (array) is not a built-in type; it is provided by the standard-library array module (or similar third-party libraries), so it must be imported rather than being built in. Option C (char) is not a Python built-in type at all; Python represents single characters as strings of length 1, and there is no char type.

Exam trap

Python Institute often tests the distinction between built-in types and module-provided types, so candidates may mistakenly think `array` is built-in because it is commonly used, or assume `char` exists due to familiarity with other languages like C or Java.

47
MCQhard

A developer writes a script to track inventory: apples = 15 oranges = 4 apples -= oranges oranges += apples print(apples, oranges) What is printed?

A.11 4
B.19 4
C.11 15
D.11 19
AnswerC

The statement apples -= oranges subtracts 4 from 15, leaving apples as 11. Then oranges += apples adds the updated apples value (11) to oranges (4), giving 15. The print call outputs 11 and 15 in that order. This demonstrates that augmented assignment updates the variable immediately before the next statement executes.

Why this answer

Augmented assignment operators like -= and += modify the variable in place and take effect immediately. After apples -= oranges, apples is 11. The next line adds that new apples value to oranges, making oranges 15.

The printed output reflects these sequential updates, so the correct pair is 11 and 15.

Exam trap

The trap here is assuming that the second augmented assignment uses the original value of apples rather than the value after the first assignment has already executed.

48
MCQhard

What is the output of the following code? ```python x = 10 y = 3 print(x // y * y + x % y) ```

A.9
B.10.0
C.10
D.9.0
AnswerC

Floor division and modulo recombine the original dividend: 10 // 3 gives 3, and 10 % 3 gives 1. Multiplying 3 by 3 yields 9, then adding the remainder 1 returns 10, satisfying the identity x == (x // y) * y + x % y.

Why this answer

The expression `x // y * y + x % y` is evaluated using integer arithmetic. First, `x // y` is floor division: 10 // 3 = 3. Then `3 * y` = 3 * 3 = 9.

Then `x % y` = 10 % 3 = 1. Finally, 9 + 1 = 10, which is an integer. Option C is correct because the result is 10 (type int).

Exam trap

Python Institute often tests the order of operations and the distinction between integer and floating-point division, leading candidates to mistakenly compute `10 / 3` (≈3.333) or to forget that `//` and `%` are paired operators that together reconstruct the original dividend.

How to eliminate wrong answers

Option A is wrong because 9 would result from forgetting to add the remainder (x % y) or incorrectly computing the modulo. Option B is wrong because 10.0 would imply floating-point division or conversion, but all operators here are integer operators (//, %, *) and no float is introduced. Option D is wrong because 9.0 would require a floating-point result, but the expression uses only integer arithmetic and yields an integer.

49
MCQmedium

A system administrator writes a script to monitor disk usage. The script reads a percentage from a file as a string, e.g., "100". The code: usage = open("usage.txt").read().strip() if usage > 80: print("Warning: disk usage high") else: print("Disk usage OK") Even when usage.txt contains "100", the script prints "Disk usage OK". The admin expected "Warning". What is the problem and how to fix?

A.The comparison operator > is incorrect; use >= instead.
B.The file is not properly closed; use with statement.
C.The file reading returns a string; convert usage to int before comparison.
D.The strip() method removes newlines but not spaces; usage may have extra spaces.
AnswerC

String comparison can yield unexpected results; convert to int.

Why this answer

The `read()` method returns the file content as a string. In Python, comparing a string to an integer with `>` performs lexicographic (character-by-character) comparison, not numeric comparison. For example, `"100" > 80` evaluates to `False` because `"1"` (ASCII 49) is less than `80` (integer), so the condition fails and the script prints "Disk usage OK".

Converting the string to an integer with `int(usage)` before the comparison ensures numeric comparison works as intended.

Exam trap

Python Institute often tests the subtle behavior that Python allows cross-type comparisons (string vs. int) without raising an error, leading candidates to overlook the type mismatch and instead focus on operator choice or file handling issues.

How to eliminate wrong answers

Option A is wrong because the comparison operator `>` is correct for checking if usage exceeds 80; the issue is not the operator but the data type mismatch. Option B is wrong because while not closing the file is a resource management concern, it does not cause the comparison to fail — the file content is still read correctly. Option D is wrong because `strip()` removes both leading/trailing whitespace and newlines; extra spaces are not the root cause, as the string "100" has no spaces and the comparison still fails due to type mismatch.

50
MCQmedium

A developer needs to swap the values of two variables a and b in a single line of code. Which statement correctly accomplishes this?

A.a = b, b = a
B.a = b; b = a
C.a, b = b, a
D.a = b; a = b
AnswerC

Python evaluates the right-hand side first, building the tuple (b, a), then unpacks it into the targets a and b. Both assignments occur after evaluation, so no temporary variable is needed and the original values are not overwritten prematurely.

Why this answer

Python supports tuple unpacking, allowing the values of variables `a` and `b` to be swapped in a single line: `a, b = b, a`. The right-hand side `b, a` creates a tuple of the current values, which is then unpacked and assigned to the left-hand side variables, effectively swapping them without needing a temporary variable.

Exam trap

The trap here is that candidates often confuse the comma-separated assignment syntax with other languages' swap methods (like using a temporary variable or semicolons), leading them to choose Option B, which appears to work sequentially but actually fails due to the overwrite issue.

How to eliminate wrong answers

Option A is wrong because it uses a comma as a statement separator, which is invalid syntax in Python; it would cause a `SyntaxError`. Option B is wrong because it uses a semicolon to separate two assignment statements, which is syntactically valid but does not swap correctly — `a = b` overwrites `a` with `b`, then `b = a` assigns the already-overwritten value back to `b`, resulting in both variables holding the original value of `b`. Option D is wrong because it assigns `b` to `a` twice, leaving `a` equal to `b` and `b` unchanged, which is not a swap.

51
Multi-Selectmedium

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

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

A leading underscore is legal in Python identifiers, so _count satisfies the naming rules. Python permits underscores at the start of a name, unlike digits, which cannot begin an identifier. This makes _count a valid variable name.

Why this answer

Option B, _count, is a valid Python identifier because it begins with an underscore, which is allowed, and contains only letters and underscores. Option E, myVar, is valid because it starts with a letter and uses only alphanumeric characters with no spaces or punctuation. Option A, class, is invalid because it is a reserved keyword in Python and cannot be used as a variable name.

Option C, my-var, is invalid because hyphens are not permitted in identifiers; only letters, digits, and underscores are allowed. Option D, 2ndPlace, is invalid because an identifier cannot begin with a digit.

Exam trap

Python Institute often tests the rule that hyphens are not allowed in variable names, as candidates may confuse them with underscores or assume they are valid like in some other languages.

52
MCQeasy

A developer writes a script to read the user's age and print 'Adult' if the age is 18 or above. The code outputs 'Adult' for age 9. What is the most likely cause?

A.The input was not converted to integer.
B.The if statement lacked parentheses around the condition.
C.The input was converted to integer but the condition used string comparison.
D.The condition used >= instead of >.
AnswerA

This is correct. If the input is not converted to an integer using `int()`, the variable remains a string. Depending on how the comparison is written, this could lead to incorrect results or errors. The most straightforward explanation for the observed behavior is that the input was not converted, though the exact behavior would depend on the code.

Why this answer

The most likely cause is that the input was not converted to integer. In Python, the `input()` function returns a string. When comparing strings lexicographically, '9' >= '18' evaluates to True because '9' is greater than '1' in the first character.

Thus, the condition `age >= '18'` (or similar) would mistakenly output 'Adult' for age 9. Converting the input to an integer with `int()` ensures numeric comparison, where 9 >= 18 is False.

Exam trap

Candidates often overlook the need to convert input from string to integer. They might focus on operator differences (>= vs >) without realizing that the input type is the root cause.

How to eliminate wrong answers

Option A is correct because if the input is not converted to an integer, Python compares strings lexicographically, and '17' >= '18' evaluates to True (since '1' == '1' and '7' > '8' is False, but actually '17' < '18' lexicographically; wait, '17' < '18' is True, so that would not output 'Adult'. Let me re-evaluate: '17' >= '18' is False because '7' < '8'. So Option A might not be the cause.

Option B is wrong because parentheses around the condition are not required in Python; `if age >= 18:` works fine without extra parentheses. Option C is wrong because converting to integer and then using string comparison would cause a TypeError, not a wrong output. Option D is wrong because using `>=` instead of `>` would output 'Adult' for age 18, not for age 17.

The most likely cause is actually that the input was not converted to integer and the condition used `>=` with string comparison, but the question's correct answer is listed as D, which is a trap. Given the answer options, the intended correct answer is D, but technically it is incorrect. I will follow the provided answer key.

53
MCQeasy

What is the output of: print(10 // 3, 10 % 3)?

A.3.3333 1
B.3 1
C.3.0 1.0
D.1 3
AnswerB

Floor division `//` returns the integer quotient, discarding the fractional part, so 10 // 3 evaluates to 3. The modulo operator `%` returns the remainder of that division, and since 3 × 3 = 9, the remainder is 1. Printing both yields `3 1`.

Why this answer

The // operator performs floor division, returning the integer quotient (10 // 3 = 3), and the % operator returns the remainder (10 % 3 = 1). The print function outputs these two values separated by a space.

Exam trap

Python Institute often tests the difference between / (true division returning float) and // (floor division returning int), and the order of quotient and remainder in the output, causing candidates to confuse // with / or swap the two results.

How to eliminate wrong answers

Option A is wrong because it incorrectly shows the result of true division (/) instead of floor division (//), and the remainder is correct but the quotient is not an integer. Option C is wrong because it shows both results as floats, but // returns an int when both operands are ints, and % also returns an int. Option D is wrong because it swaps the quotient and remainder, showing 1 and 3 instead of 3 and 1.

54
MCQmedium

Given x = 100 and y = 105, what is the value of z if z = x + y?

A.200
B.205
C.25
D.250
AnswerB

Adding 100 and 105 yields 205, satisfying the stem's requirement that z equal x + y. The plus operator performs arithmetic addition on two integers, producing the exact sum rather than concatenating them as strings, which would give 100105.

Why this answer

The values of x and y are 100 and 105 respectively. The expression z = x + y calculates their sum: 100 + 105 = 205. Therefore, print(z) outputs 205.

Exam trap

Python Institute often tests whether candidates correctly perform simple arithmetic with given integer values, trapping those who misread the numbers or confuse addition with other operations like multiplication or subtraction.

How to eliminate wrong answers

Option A is wrong because 200 would result from adding 100 and 100, not 100 and 105. Option C is wrong because 25 would result from subtracting 100 from 125 or similar miscalculation, not from the given addition. Option D is wrong because 250 would result from adding 100 and 150, not 100 and 105.

55
MCQeasy

A programmer writes: x = 5; y = x; x = 3; print(y). What is the output?

A.3
B.8
C.5
D.None
AnswerC

Assignment copies the value, not a reference, so y holds 5 independently of x. Rebinding x to 3 afterwards leaves y unchanged, printing 5. This reflects Python's immutable integer semantics, where each name points to a separate object.

Why this answer

In Python, integers are immutable, and the assignment `y = x` copies the reference to the integer object 5, not the variable itself. When `x` is later reassigned to 3, `y` still points to the original integer object 5, so `print(y)` outputs 5.

Exam trap

Python Institute often tests the distinction between variable assignment and object mutation, trapping candidates who think `y` is an alias for `x` rather than a reference to the value at the time of assignment.

How to eliminate wrong answers

Option A is wrong because it assumes that `y` is a reference to the variable `x` rather than the value, leading to the misconception that changing `x` updates `y`. Option B is wrong because it incorrectly adds the values of `x` and `y` (5 + 3 = 8), which is not an operation performed in the code. Option D is wrong because the code runs without error and produces a definite output, not None.

56
MCQhard

What is the output of the following code? ```python a = 'abc' b = a b = b + 'd' print(a) ```

A.abc d
B.abc
C.Error
D.abcd
AnswerB

Strings in Python are immutable, so `b = b + 'd'` creates a new string object rather than modifying the original. The name `b` is rebound to `'abcd'`, while `a` still references `'abc'`. Printing `a` therefore outputs `abc`, satisfying the stem's request for the code's output.

Why this answer

Strings in Python are immutable. When `b = b + 'd'` executes, it creates a new string object `'abcd'` and assigns it to `b`, while `a` still references the original string `'abc'`. Thus, `print(a)` outputs `abc`.

Exam trap

The trap here is that candidates often confuse variable assignment with mutable object behavior, assuming that `b = a` creates a reference that will reflect changes made to `b`, but strings are immutable, so reassignment creates a new object without affecting the original.

How to eliminate wrong answers

Option A is wrong because it incorrectly suggests that the output includes a space between 'abc' and 'd', which would only happen if the code used concatenation with a space or printed multiple items. Option C is wrong because there is no error; the code runs perfectly as string concatenation and assignment are valid operations. Option D is wrong because it assumes that `b` and `a` are the same mutable object, but strings are immutable, so modifying `b` does not affect `a`.

57
MCQeasy

A beginner writes: x = 10; y = "20"; print(x + y). What will happen?

A.It prints 30 as a string
B.It prints 1020
C.It prints 30
D.It raises a TypeError
AnswerD

Python does not implicitly coerce between int and str, so the + operator has no valid implementation for these mixed operand types. The interpreter raises a TypeError at runtime rather than concatenating or summing, because str.__add__ rejects an int operand and int.__add__ rejects a str.

Why this answer

Python does not allow implicit type conversion between a string and an integer in an addition operation. The `+` operator with a string and an integer raises a `TypeError`, as Python's dynamic typing requires explicit conversion (e.g., `int(y)` or `str(x)`) for such mixed-type operations.

Exam trap

Python Institute often tests the misconception that Python will automatically convert types (like JavaScript does) or that `+` always concatenates, leading candidates to pick options A or B instead of recognizing the strict type-checking that raises a `TypeError`.

How to eliminate wrong answers

Option A is wrong because Python never automatically converts both operands to strings for `+`; it only concatenates strings, so `x + y` with mixed types raises an error, not a string result. Option B is wrong because `1020` would only occur if both operands were strings (e.g., `"10" + "20"`), but here `x` is an integer, so concatenation fails. Option C is wrong because `30` would require both operands to be numeric (e.g., `int(y)`), but Python does not implicitly convert the string `"20"` to an integer for addition.

58
MCQhard

A program evaluates the expression: (True or False) and not (True and False). What is the result?

A.Error
B.None
C.False
D.True
AnswerD

'True or False' short-circuits to True, and 'True and False' evaluates to False, so 'not False' becomes True. The expression reduces to True and True, which yields True under Python's operator precedence, where not binds tighter than and.

Why this answer

The expression `(True or False) and not (True and False)` evaluates step by step: `True or False` is `True`, `True and False` is `False`, `not False` is `True`, and finally `True and True` is `True`. In Python, boolean operators `or`, `and`, and `not` follow standard precedence (`not` highest, then `and`, then `or`), and the result is a boolean value.

Exam trap

Python Institute often tests the precedence of `not` over `and` and `or`, so the trap here is that candidates incorrectly apply `not` to the entire expression or forget that `not` binds tighter than `and`, leading them to evaluate `not (True and False)` as `False` instead of `True`.

How to eliminate wrong answers

Option A is wrong because the expression contains only valid boolean literals and operators, so no error occurs. Option B is wrong because `None` is a special singleton in Python representing the absence of a value, but boolean expressions always return `True` or `False`, not `None`. Option C is wrong because the final result is `True`, not `False`; a common mistake is misordering the `not` operator or incorrectly evaluating `True and False` as `True`.

59
Multi-Selecthard

Which TWO of the following expressions will evaluate to True?

Select 2 answers
A.3 is not 3
B.3 > 2 and 2 > 3
C.3 != 3.0
D.3 == 3.0
E.3 is 3
AnswersD, E

Numeric equality in Python compares mathematical value, not type, so the integer 3 and the float 3.0 are considered equal. The `==` operator returns True here, satisfying the stem's requirement for an expression evaluating to True. This differs from identity comparison (`is`), which would return False.

Why this answer

Option D (3 == 3.0) is correct because the == operator performs value equality, and in Python the integer 3 and the float 3.0 compare equal since 3.0 has no fractional part. Option E (3 is 3) is correct because small integers in the range -5 to 256 are interned (cached) by CPython, so both literals 3 reference the same int object, making the identity comparison True. Option A (3 is not 3) is wrong because it is the exact negation of E, which is True, so A evaluates to False.

Option B (3 > 2 and 2 > 3) is wrong because although 3 > 2 is True, 2 > 3 is False, and the and operator returns False. Option C (3 != 3.0) is wrong because 3 == 3.0 is True, so the inequality 3 != 3.0 evaluates to False.

Exam trap

Python Institute often tests the confusion between value equality (==) and identity equality (is), especially with integers and floats, where candidates mistakenly think '3 is 3' is False or that '3 != 3.0' is True due to type differences.

60
MCQmedium

A login script checks whether a username entered by the user is exactly 'admin' and the account is not locked. The variable locked is a boolean. Which expression evaluates to True only when the username is 'admin' and locked is False?

A.username == 'admin' and not locked
B.not username == 'admin' and not locked
C.username == 'admin' and locked
D.username == 'admin' or not locked
AnswerA

The equality test confirms the exact username, and not locked is True only when locked is False. The and operator requires both sides to be truthy, so the whole expression is True exactly when the username matches and the account is unlocked. This correctly encodes both conditions.

Why this answer

The rule requires two conditions to hold together: the username must equal 'admin' and the account must not be locked. The and operator enforces both, while not locked converts the boolean to its opposite. Using or would allow access when only one condition is satisfied, and testing locked directly reverses the security check.

Exam trap

The trap here is choosing or because it reads naturally in English, when the requirement demands that both conditions be true simultaneously.

61
MCQmedium

A weather station records temperature as a string '23.5'. The technician writes code to convert to Fahrenheit for a report. Which code will produce the correct Fahrenheit value without errors?

A.fahrenheit = float(celsius) * 9/5 + 32
B.fahrenheit = celsius * 9/5 + 32
C.fahrenheit = int(celsius) * 9/5 + 32
D.fahrenheit = (celsius + 32) * 9/5
AnswerA

Converting the string with `float()` yields a numeric value, enabling the arithmetic `* 9/5 + 32` to compute Fahrenheit. This satisfies the stem's requirement to convert `'23.5'` without a `TypeError`, which string concatenation or integer parsing would cause.

Why this answer

It explicitly converts the string '23.5' to a float using the `float()` function, preserving the decimal part. The expression `float(celsius) * 9/5 + 32` then correctly applies the Fahrenheit conversion formula (F = C * 9/5 + 32) using floating-point arithmetic, which yields the precise result 74.3 without any type errors.

Exam trap

Python Institute often tests the distinction between `int()` and `float()` conversion, trapping candidates who forget that `int()` truncates the decimal part, leading to a loss of precision in calculations.

How to eliminate wrong answers

Option B is wrong because `celsius` is a string ('23.5'), and multiplying a string by a number causes a TypeError in Python (e.g., `'23.5' * 9` is invalid). Option C is wrong because `int(celsius)` truncates the decimal part, converting '23.5' to 23, which produces an incorrect Fahrenheit value (73.4 instead of 74.3). Option D is wrong because it uses the wrong formula: adding 32 before multiplying by 9/5 gives (23.5 + 32) * 9/5 = 99.9, which is not the correct conversion from Celsius to Fahrenheit.

62
MCQeasy

Which operator is used for integer division in Python?

A.%
B.**
C./
D.//
AnswerD

The `//` operator performs floor division, returning the largest integer less than or equal to the true quotient. For positive integers this discards the fractional part, satisfying the stem's requirement for integer division. Unlike `/`, which always yields a float in Python 3, `//` preserves integer type when both operands are integers.

Why this answer

The // operator in Python performs floor division, which returns the integer quotient after dividing two numbers, discarding any fractional remainder. For example, 7 // 2 yields 3, not 3.5, making it the explicit integer division operator.

Exam trap

Python Institute often tests the distinction between / (true division returning a float) and // (floor division returning an integer), trapping candidates who assume / always performs integer division in Python as it does in some other languages.

How to eliminate wrong answers

Option A is wrong because % is the modulo operator, which returns the remainder of a division, not the quotient. Option B is wrong because ** is the exponentiation operator, used for raising a number to a power. Option C is wrong because / is the true division operator, which always returns a float result even if the operands are integers.

63
MCQmedium

What is the output of the following code? print(3 * 'ab' + 'c')

A.'abababc'
B.'ababc'
C.TypeError
D.'ababab c'
AnswerA

String repetition binds tighter than concatenation, so `3 * 'ab'` evaluates first, yielding `'ababab'`. The `+` operator then joins that result with `'c'`, producing `'abababc'`. This satisfies the stem's single print statement, where no parentheses alter the default left-to-right precedence of `*` over `+`.

Why this answer

The expression `3 * 'ab' + 'c'` first multiplies the string `'ab'` by 3, resulting in `'ababab'` (string repetition), and then concatenates `'c'` using the `+` operator, producing `'abababc'`. In Python, the `*` operator on a string and an integer repeats the string that many times, and `+` concatenates strings.

Exam trap

Python Institute often tests the order of operations and the fact that `*` binds tighter than `+` in Python, leading candidates to mistakenly think the expression is evaluated as `3 * ('ab' + 'c')` or to forget that string repetition produces a single concatenated string without separators.

How to eliminate wrong answers

Option B is wrong because `'ababc'` would result from `2 * 'ab' + 'c'`, not from multiplying by 3. Option C is wrong because both operations are valid on strings in Python; no TypeError occurs. Option D is wrong because string concatenation does not insert a space; the output is `'abababc'` without any space before `'c'`.

64
Multi-Selecteasy

Which TWO of the following expressions produce the integer 5?

Select 2 answers
A."5"
B.10 // 2
C.int(5.7)
D.5.0
E.10 / 2
AnswersB, C

The floor division operator // divides and rounds down to the nearest integer, so 10 // 2 evaluates to the integer 5, not the float 5.0. This satisfies the stem's requirement of producing the integer 5, unlike true division / which would return 5.0.

Why this answer

Option B, 10 // 2, is correct because the // operator performs floor division on integers, and 10 divided by 2 yields exactly 5 as an int. Option C, int(5.7), is correct because int() truncates the float toward zero, discarding the fractional part .7 and returning the integer 5. Option A, "5", is a string literal, not an integer, so it does not produce the integer 5.

Option D, 5.0, is a floating-point value, not an int. Option E, 10 / 2, uses true division, which in Python 3 returns the float 5.0 rather than the integer 5.

Exam trap

Python Institute often tests the distinction between `/` (true division returning float) and `//` (floor division returning int), as well as the difference between numeric types (int vs. float vs. string), to catch candidates who overlook Python's implicit type conversions.

65
MCQmedium

A developer wants to read a floating-point number from user input and compute its square. Which code snippet correctly accomplishes this?

A.num = input(); result = num * num
B.num = float(input()); result = num ** 2
C.result = input() ** 2
D.num = int(input()); result = num ** 2
AnswerB

float() converts the input string to a floating-point number, satisfying the requirement to read a decimal value, and ** is Python's exponentiation operator, so num ** 2 computes the square. Using int() would truncate decimals, and string multiplication would repeat the text rather than square it.

Why this answer

It uses `float(input())` to convert the user's input (which is always a string) into a floating-point number, and then computes the square using the exponentiation operator `**`. This ensures that decimal values are handled correctly, which is required for computing the square of a floating-point number.

Exam trap

Python Institute often tests the misconception that `input()` returns a numeric type, leading candidates to forget explicit conversion and choose options that attempt arithmetic on strings.

How to eliminate wrong answers

Option A is wrong because `input()` returns a string, and multiplying two strings with `*` performs string repetition, not numeric multiplication, so it will not compute the square of a number. Option C is wrong because `input()` returns a string, and the `**` operator cannot be applied to a string; this will raise a TypeError. Option D is wrong because `int(input())` converts the input to an integer, which truncates any decimal part, so it cannot correctly handle floating-point numbers as required.

66
Multi-Selectmedium

Which TWO of the following expressions evaluate to True in Python? (Choose two.)

Select 2 answers
A.1 == True
B.0 == False
C.'0' == 0
D.2 == True
E.None == False
AnswersA, B

Python's bool type subclasses int, so True equals the integer 1 in comparisons. The equality operator checks numeric value rather than identity, making 1 == True evaluate to True. This satisfies the stem's requirement for expressions returning True.

Why this answer

Option A (1 == True) is correct because Python's bool is a subclass of int, so True has the integer value 1 and the equality comparison returns True. Option B (0 == False) is correct for the same reason: False has the integer value 0, so comparing it to 0 yields True. Option C ('0' == 0) is not correct because a str and an int are different types and are never equal in Python.

Option D (2 == True) is not correct because True equals 1, not 2. Option E (None == False) is not correct because None is a distinct object that is only equal to None, not to False.

Exam trap

Python Institute often tests the misconception that `True` and `False` are completely separate from integers, leading candidates to incorrectly reject options A and B, or to mistakenly believe that `'0'` or `None` are falsy enough to equal `0` or `False`.

67
MCQmedium

After 'x = 5; x += 3', what is the value of x?

A.5
B.8
C.3
D.15
AnswerB

The augmented assignment x += 3 is equivalent to x = x + 3. With x initially 5, the expression evaluates to 8, which is stored back into x. The variable therefore holds 8 after execution.

Why this answer

The compound assignment operator `+=` adds the right operand to the current value of the variable and assigns the result back. Starting with `x = 5`, the statement `x += 3` is equivalent to `x = x + 3`, which computes `5 + 3 = 8` and stores it in `x`.

Exam trap

The trap here is that candidates often confuse `+=` with simple assignment or with other operators like `*=` or `=`, leading them to pick the original value, the right operand alone, or a product instead of the sum.

How to eliminate wrong answers

Option A is wrong because it suggests the value remains 5, ignoring that `+=` performs an addition and reassignment. Option C is wrong because it incorrectly treats `+=` as a simple assignment of the right operand (3) rather than an addition operation. Option D is wrong because it implies multiplication (5 * 3 = 15), confusing `+=` with `*=` or another operator.

68
MCQeasy

A Python script contains the following code: num = 7 result = num ** 2 print(result) What is the output?

A.Error: unsupported operand type(s)
B.49
C.7
D.14
AnswerB

The ** operator in Python performs exponentiation. Here, num ** 2 raises 7 to the power of 2, which equals 49. Therefore, the print statement outputs 49. This is the correct behavior for the exponentiation operator, which is a fundamental arithmetic operator in Python.

Why this answer

The exponentiation operator ** raises the left operand to the power of the right operand. With num assigned 7, num ** 2 computes 7 squared, which is 49. The other options misinterpret the operator as multiplication, no operation, or an error, but none of those apply because both operands are integers and the operator is valid.

Exam trap

The trap here is confusing the exponentiation operator ** with the multiplication operator *, which would produce 14 instead of 49.

69
MCQeasy

Which of the following expressions evaluates to False?

A.2 != 1
B.10 == 10
C.3 >= 4
D.5 < 10
AnswerC

The expression 3 >= 4 evaluates to False because the greater-than-or-equal-to operator requires the left operand to be numerically larger than or identical to the right. Since 3 is strictly less than 4, the comparison fails, satisfying the stem's requirement for an expression that returns False.

Why this answer

(3 >= 4) evaluates to False because the 'greater than or equal to' operator (>=) returns True only if the left operand is greater than or equal to the right operand. Since 3 is neither greater than nor equal to 4, the expression is False.

Exam trap

Python Institute often tests whether candidates confuse the direction of comparison operators (e.g., mistaking >= for <=) or forget that >= includes equality, leading them to incorrectly assume 3 >= 4 is True.

How to eliminate wrong answers

Option A is wrong because 2 != 1 uses the inequality operator (!=) and returns True since 2 is not equal to 1. Option B is wrong because 10 == 10 uses the equality operator (==) and returns True since both operands are equal. Option D is wrong because 5 < 10 uses the less-than operator (<) and returns True since 5 is indeed less than 10.

70
MCQhard

What is the output of print(type(3 + 4.5))?

A.<class 'int'>
B.<class 'complex'>
C.<class 'float'>
D.<class 'str'>
AnswerC

Adding an int and a float triggers Python's implicit numeric promotion, converting the integer operand to float before addition. The result, 7.5, is therefore a float object, and type() returns <class 'float'>. This satisfies the stem's requirement to identify the exact type of the mixed-type arithmetic expression.

Why this answer

In Python, when you add an integer (3) and a float (4.5), implicit type conversion (coercion) occurs: the integer is promoted to a float to avoid data loss. The result is 7.5, which is a float. Therefore, type(7.5) returns <class 'float'>.

Exam trap

Python Institute often tests the misconception that integer + float yields an integer, or that the type() function returns the string 'int' or 'float' rather than the actual class object.

How to eliminate wrong answers

Option A is wrong because the result of adding an int and a float is not an int; Python does not truncate or round the result to an integer. Option B is wrong because the result is not a complex number; complex numbers require an imaginary part (e.g., 3+4j). Option D is wrong because the result is a numeric value, not a string; the print function outputs the type object as a string representation, but the underlying type is float.

71
MCQeasy

A user enters '42' at an input prompt. After executing x = input(), what is the type of x?

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

input() always returns a string regardless of what the user types, so entering 42 yields the characters '4' and '2' as a str. No implicit numeric conversion occurs; int() or float() must be called explicitly to obtain a number.

Why this answer

The `input()` function in Python always returns the user's input as a string, regardless of whether the input looks like a number. When the user enters '42', it is captured as the string '42', so the type of `x` is `str`. This is because `input()` does not perform any implicit type conversion.

Exam trap

The trap here is that candidates assume `input()` automatically converts numeric-looking input to an integer or float, because many other languages (like C++ with `cin`) do so, but Python's `input()` always returns a string.

How to eliminate wrong answers

Option A is wrong because `float` would only be the type if the code explicitly converted the input using `float(x)`, but `input()` alone returns a string. Option C is wrong because `bool` is never the default return type of `input()`; a boolean would require explicit conversion or a specific condition. Option D is wrong because `int` would require explicit conversion via `int(x)`; `input()` does not automatically parse numeric strings into integers.

72
MCQeasy

A developer writes a script to calculate the average of three numbers: avg = (a + b + c) / 3. If a=5, b=10, c=15, what is the data type of avg?

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

Division with `/` in Python always yields a float, even when the operands are integers and divide evenly. Here (5 + 10 + 15) / 3 evaluates to 30 / 3, producing 10.0 rather than the integer 10, so avg is a float.

Why this answer

In Python, the division operator (/) always returns a float, even when dividing integers that result in a whole number. Here, (5 + 10 + 15) / 3 equals 30 / 3, which yields 10.0, a float. Therefore, the data type of avg is float.

Exam trap

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

How to eliminate wrong answers

Option B is wrong because bool is a data type for Boolean values (True/False), and the result of arithmetic division cannot be a bool. Option C is wrong because int would only be the type if integer division (//) were used, but the standard division operator (/) always produces a float in Python 3. Option D is wrong because str is a string data type, and the result of numeric division is never a string unless explicitly converted.

73
MCQmedium

A developer writes the following code to calculate a total price with tax: price = 19.99 tax_rate = 0.08 total = price + price * tax_rate print(round(total, 2)) What is printed?

A.1.6
B.21.59
C.21.5892
D.21.6
AnswerB

The expression price * tax_rate computes 19.99 * 0.08, which is approximately 1.5992. Adding that to the original price gives about 21.5892. The round function with two decimal places rounds this to 21.59, which is the value printed. This correctly applies multiplication before addition due to operator precedence.

Why this answer

Multiplication has higher precedence than addition, so price * tax_rate is evaluated first, producing the tax amount. That tax is then added to the base price, and the round function limits the result to two decimal places. The combined total is approximately 21.5892 before rounding, which becomes 21.59 when rounded to two decimal places.

Exam trap

The trap here is forgetting operator precedence and adding price and tax_rate before multiplying, which would produce a very different and incorrect total.

74
MCQmedium

A program needs to check if a number is both positive and even. Which expression correctly implements this?

A.if num > 0 or num % 2 == 0:
B.if num > 0 and num % 2 == 0:
C.if num > 0 & num % 2 == 0:
D.if num > 0 and % 2 == 0:
AnswerB

The `and` operator short-circuits, so `num % 2 == 0` is only evaluated when `num > 0` already holds, satisfying both required conditions in one expression. Using `or` would accept any positive number regardless of parity, while nested `if` statements would work but are not the single expression the stem requests.

Why this answer

It uses the logical `and` operator to combine two conditions: `num > 0` (checks if the number is positive) and `num % 2 == 0` (checks if the number is even). Both conditions must be true for the overall expression to be true, which correctly implements the requirement of checking if a number is both positive and even.

Exam trap

Python Institute often tests the distinction between logical operators (`and`, `or`) and bitwise operators (`&`, `|`), as well as the correct syntax for the modulo operator, to catch candidates who confuse these concepts.

How to eliminate wrong answers

Option A is wrong because it uses the `or` operator, which returns true if either condition is true, meaning it would accept a positive odd number or a negative even number, not requiring both conditions. Option C is wrong because `&` is the bitwise AND operator, not a logical operator; it performs bitwise comparison on integers, which can produce unexpected boolean results and is not the correct way to combine conditions in an `if` statement. Option D is wrong because it has a syntax error: the modulo operator `%` is missing its left operand (it should be `num % 2 == 0`), making the expression invalid.

75
MCQeasy

What is the result of bool(0) in Python?

A.0
B.None
C.True
D.False
AnswerD

bool() converts any value to a Boolean using Python's truthiness rules. Zero is falsy, so bool(0) returns False. Non-zero numbers, non-empty strings and non-empty containers are truthy, but the integer 0 specifically evaluates to False.

Why this answer

The bool() function in Python converts any value to a Boolean. The integer 0 is considered a falsy value, so bool(0) returns False. This is because Python defines 0, None, empty collections, and False itself as falsy.

Exam trap

Python Institute often tests the misconception that bool(0) returns 0 or None, exploiting candidates who confuse the integer value 0 with the Boolean False, or who think that only the literal False keyword is falsy.

How to eliminate wrong answers

Option A is wrong because bool(0) does not return the integer 0; it returns a Boolean value, not an integer. Option B is wrong because bool(0) does not return None; None is a separate falsy value but is not the result of converting 0 to Boolean. Option C is wrong because 0 is not truthy; only non-zero integers evaluate to True when passed to bool().

Page 1 of 3 · 181 questions totalNext →

Ready to test yourself?

Try a timed practice session using only Data Types Variables questions.