Courseiva

CCNA Data Types Variables Questions

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

76
MCQhard

Which expression evaluates to False?

A.3 > 4
B.3 <= 3
C.3 == 3
D.3 != 2
AnswerA

The expression 3 > 4 evaluates to False because the greater-than operator compares the two integer operands and finds the left value smaller than the right. This directly satisfies the stem's requirement for an expression yielding False, unlike the other options whose comparisons return True.

Why this answer

The expression `3 > 4` evaluates to `False` in Python, as 3 is not greater than 4. All other options evaluate to `True` due to the correct application of comparison operators: `<=`, `==`, and `!=`.

Exam trap

Python Institute often tests whether candidates confuse the assignment operator `=` with the equality operator `==`, or mistakenly think that `<=` requires strict inequality, leading them to incorrectly evaluate `3 <= 3` as `False`.

How to eliminate wrong answers

Option B is wrong because `3 <= 3` evaluates to `True` — the `<=` operator returns `True` when the left operand is less than or equal to the right operand, and here they are equal. Option C is wrong because `3 == 3` evaluates to `True` — the `==` operator checks for value equality, and both integers are identical. Option D is wrong because `3 != 2` evaluates to `True` — the `!=` operator returns `True` when the operands are not equal, and 3 is indeed not equal to 2.

77
MCQmedium

A company needs to calculate the average of three test scores entered by a user. The scores are integers. The programmer writes the following code: s1 = input("Enter score 1: ") s2 = input("Enter score 2: ") s3 = input("Enter score 3: ") avg = (s1 + s2 + s3) / 3 print("Average:", avg) When run, the output is incorrect. What is the most likely cause?

A.The division by 3 will cause a ZeroDivisionError because 3 is not a float.
B.The division operator / always returns an integer, but the sum is not an integer.
C.The variable names s1, s2, s3 are not allowed because they start with a letter.
D.The input() function returns strings, so concatenation occurs instead of addition.
AnswerD

input() returns a string, so using + on strings concatenates them.

Why this answer

The `input()` function in Python always returns a string, even when the user types numbers. The `+` operator on strings performs concatenation (e.g., '5' + '3' + '2' becomes '532'), not numeric addition. Dividing the concatenated string by 3 then causes a `TypeError` (or produces an incorrect result if the string is implicitly converted), so the average calculation fails.

Exam trap

Python Institute often tests the misconception that `input()` returns a numeric type, leading candidates to overlook the need for explicit type conversion before arithmetic operations.

How to eliminate wrong answers

Option A is wrong because dividing by an integer literal like 3 is perfectly valid; Python allows division by integers, and a `ZeroDivisionError` only occurs when dividing by zero, not by a non-zero integer. Option B is wrong because the `/` operator in Python 3 always returns a float, not an integer, and the issue is not about the return type of division. Option C is wrong because variable names starting with a letter (like s1, s2, s3) are perfectly allowed in Python; identifiers must start with a letter or underscore, so these names are valid.

78
MCQmedium

A programmer writes: result = 'Py' * 2 + 'thon'. What is the value of result?

A.'Py2thon'
B.'Python'
C.'Pyththon'
D.'PyPy'
AnswerB

Correct: 'Py'*2 = 'PyPy', plus 'thon' = 'Python'

Why this answer

In Python, the * operator on a string repeats it, and the + operator concatenates strings. 'Py' * 2 produces 'PyPy', then 'PyPy' + 'thon' results in 'Python'. This follows Python's operator precedence where * has higher precedence than +, so the multiplication is evaluated first.

Exam trap

The PCEP exam often tests the misconception that the * operator concatenates the string with the numeric value as a string (e.g., 'Py' * 2 becomes 'Py2'), or that it only repeats the last character, leading candidates to choose option A or C.

How to eliminate wrong answers

Option A is wrong because it incorrectly assumes that the * operator concatenates with a numeric representation, producing 'Py2thon', but Python's string repetition does not insert the number as a string. Option C is wrong because it suggests the repetition applies only to the last character, yielding 'Pyththon', but * repeats the entire string 'Py', not just the 'y'. Option D is wrong because it shows only the result of 'Py' * 2 as 'PyPy', ignoring the concatenation with 'thon'.

79
MCQmedium

Which of the following variable names is NOT valid in Python?

A.My_Var
B._myVar
C.2nd_place
D.myVar2
AnswerC

Python identifiers cannot begin with a digit, so `2nd_place` raises a `SyntaxError` at parse time, satisfying the stem's requirement for an invalid name. Letters, underscores and digits are permitted only after the first character, which must be a letter or underscore.

Why this answer

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

Exam trap

Python Institute often tests the rule that variable names cannot start with a digit, and the trap here is that candidates may focus on the underscore or mixed case and overlook the leading digit, mistakenly thinking '2nd_place' is acceptable because it contains letters and underscores.

How to eliminate wrong answers

Option A is wrong because 'My_Var' starts with a letter and contains only letters and underscores, which is perfectly valid in Python. Option B is wrong because '_myVar' starts with an underscore, which is allowed and commonly used for internal or private variables. Option D is wrong because 'myVar2' starts with a letter and contains letters and digits, which is valid as digits are allowed after the first character.

80
MCQmedium

A developer runs the command and sees the output. Which statement about the data type is correct?

A.3.14 is a decimal.Decimal type.
B.3.14 is a float, but Python also treats it as a double.
C.3.14 is a float in Python.
D.3.14 is a string.
AnswerC

The literal 3.14 contains a decimal point, which makes Python create a float object rather than an int. Its type is therefore float, and this holds regardless of whether the value is displayed, stored in a variable, or passed to a function.

Why this answer

In Python, numeric literals with a decimal point, such as 3.14, are always interpreted as the built-in float type. Python does not have a separate 'double' type; its float is implemented as a C double (64-bit IEEE 754), but the language itself refers to it as float. This is a fundamental rule of Python's data type system.

Exam trap

The PCEP exam often tests the misconception that Python has separate 'float' and 'double' types, similar to languages like C or Java, when in fact Python's float is always double-precision and there is no distinct double type.

How to eliminate wrong answers

Option A is wrong because decimal.Decimal is a separate type from the decimal module, not a built-in literal type; 3.14 is not automatically a Decimal. Option B is wrong because Python does not have a distinct 'double' type — it uses a single float type, which is implemented as a double-precision floating-point number under the hood, but the language name is simply 'float'. Option D is wrong because 3.14 is not enclosed in quotes, so it is a numeric literal, not a string.

81
Multi-Selecteasy

Which TWO of the following are Python membership operators?

Select 2 answers
A.not
B.not in
C.in
D.is
E.and
AnswersB, C

'not in' is a membership operator that evaluates whether a value is absent from a sequence, returning a Boolean. It is the negated counterpart of 'in', satisfying the question's requirement for membership operators rather than identity or comparison operators.

Why this answer

Option B, 'not in', is a Python membership operator that evaluates to True when a specified value is absent from a sequence such as a list, tuple, string, or dictionary, making it correct. Option C, 'in', is likewise a membership operator that tests whether a value exists within a sequence, returning a Boolean result, so it is also correct. The other options are not membership operators: A 'not' is a logical (Boolean) operator, D 'is' is an identity operator that compares object identity, and E 'and' is a logical operator that combines Boolean expressions.

Exam trap

Python Institute often tests the distinction between membership operators ('in', 'not in') and identity operators ('is', 'is not'), as candidates frequently confuse 'is' with 'in' or mistake 'not' as a standalone membership operator when it must be paired with 'in'.

82
MCQeasy

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

A.my-var
B.2nd_place
C._count
D.class
AnswerC

A leading underscore is a legal identifier character in Python, and _count contains no spaces, digits at the start, or reserved keywords. It therefore satisfies Python's naming rules, unlike names beginning with a digit or using punctuation.

Why this answer

(_count) is correct because in Python, variable names can start with an underscore, and underscores are allowed anywhere in the name. The name _count follows all Python identifier rules: it starts with a letter or underscore, contains only letters, digits, or underscores, and is not a reserved keyword.

Exam trap

Python Institute often tests the rule that hyphens are not allowed in variable names, leading candidates to mistakenly think my-var is valid because it resembles common naming in other languages or file systems.

How to eliminate wrong answers

Option A is wrong because my-var contains a hyphen (-), which is not allowed in Python identifiers; only underscores are permitted as separators. Option B is wrong because 2nd_place starts with a digit, which violates Python's rule that identifiers must begin with a letter or underscore. Option D is wrong because class is a reserved keyword in Python and cannot be used as a variable name.

83
MCQeasy

What is the correct way to read a floating-point number from user input and store it in a variable?

A.x = input(float())
B.x = input() as float
C.x = float(input())
D.x = input().float()
AnswerC

`float(input())` converts the entered string directly into a floating-point value, satisfying the requirement to read a number rather than text. `input()` always returns a string, so wrapping it in `float()` performs the necessary type conversion in one step, storing the numeric result in `x`.

Why this answer

`float(input())` first reads the user input as a string via `input()`, then converts that string to a floating-point number using the `float()` function. This is the standard and only valid way in Python to obtain a float from console input, as `input()` always returns a string.

Exam trap

The trap here is that candidates often confuse the order of operations, thinking they can apply a type conversion method directly on the input string (like `.float()`) or use non-existent syntax like `as float`, instead of wrapping the `input()` call with the `float()` function.

How to eliminate wrong answers

Option A is wrong because `input(float())` attempts to call `float()` with no argument (which returns 0.0) and then passes that float as the prompt argument to `input()`, not converting the user's input. Option B is wrong because `x = input() as float` is not valid Python syntax; the `as` keyword is used only in `with` statements and exception handling, not for type conversion. Option D is wrong because `x = input().float()` tries to call a method named `float()` on the string returned by `input()`, but strings have no such method, causing an AttributeError.

84
Drag & Dropmedium

Order the steps to define and call a function in Python.

Drag or tap steps into the slots.

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

Why this order

Function definition starts with def, then the body, parameters are optional, and calling the function executes it.

85
Multi-Selectmedium

Which TWO of the following expressions evaluate to True?

Select 2 answers
A.bool('')
B.bool([])
C.bool(1)
D.bool('False')
E.bool(0)
AnswersC, D

`bool(1)` returns True because Python's truth-value testing converts any non-zero integer to True, and only zero is falsy among integers. This satisfies the stem's requirement for an expression evaluating to True, since the integer literal 1 is non-zero.

Why this answer

Option C, bool(1), evaluates to True because any non-zero integer is truthy in Python, and 1 is the canonical non-zero value. Option D, bool('False'), also evaluates to True because any non-empty string is truthy regardless of its content — the string 'False' has five characters, so it is truthy. The unmarked options do not belong: bool('') is False because an empty string is falsy, bool([]) is False because an empty list is falsy, and bool(0) is False because zero is the integer falsy value.

Exam trap

The trap here is that candidates often mistakenly think the string `'False'` is falsy because it looks like the Boolean `False`, but Python evaluates truthiness based on the object's type and content, not its string representation.

86
MCQhard

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

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

Python's exponentiation operator `**` is right-associative, so `2 ** 3 ** 2` groups as `2 ** (3 ** 2)`, not `(2 ** 3) ** 2`. Evaluating the innermost exponent first gives `3 ** 2 = 9`, then `2 ** 9 = 512`. Left-associative evaluation would wrongly yield 64.

Why this answer

The expression `2 ** 3 ** 2` uses the exponentiation operator `**`, which in Python is right-associative. This means it is evaluated as `2 ** (3 ** 2)`, not `(2 ** 3) ** 2`. First, `3 ** 2` equals 9, then `2 ** 9` equals 512.

Therefore, option A is correct.

Exam trap

The trap here is that many candidates assume exponentiation is left-associative like most other arithmetic operators, leading them to compute `(2 ** 3) ** 2 = 64` instead of the correct right-associative `2 ** (3 ** 2) = 512`.

How to eliminate wrong answers

Option B (256) is wrong because it would result from `(2 ** 3) ** 2` (i.e., 8 ** 2 = 64) and then incorrectly doubling, not from the correct right-associative evaluation. Option C (64) is wrong because it represents the result of `(2 ** 3) ** 2` (8 squared), which is the left-associative misinterpretation of the expression. Option D (128) is wrong because it would come from `2 ** 7` (a miscalculation of the exponent), not from the correct `2 ** 9`.

87
MCQmedium

A program calculates BMI. User inputs weight and height as strings. Which line correctly converts to float?

A.weight = float(input)
B.weight = input().float()
C.weight = float(input())
D.weight = input(float())
AnswerC

float() parses a string such as "70.5" into a floating-point number, satisfying the stem's requirement to convert string input before arithmetic. Applying it directly to input() wraps the read value, so weight becomes numeric and BMI division works.

Why this answer

`float(input())` first reads the user's input as a string via `input()`, then converts that string to a floating-point number using the `float()` function. This is the standard Python pattern for converting user input to a numeric type.

Exam trap

Python Institute often tests the distinction between calling a function (`float(input())`) versus referencing it (`float(input)`) or chaining a non-existent method (`input().float()`), exploiting the common confusion that methods and functions are interchangeable.

How to eliminate wrong answers

Option A is wrong because `float(input)` passes the function object `input` itself, not the result of calling it, causing a TypeError. Option B is wrong because `input().float()` attempts to call a method named `float` on a string object, but strings have no such method; the correct approach is to use the built-in `float()` function. Option D is wrong because `input(float())` tries to call `input()` with a float argument (the result of `float()`), which is meaningless and will raise a TypeError since `input()` expects an optional string prompt, not a number.

88
MCQmedium

A developer writes a script that records a product price. The line is: price = 19.99 Later, the script runs print(type(price)). What is displayed?

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

Any numeric literal containing a decimal point in Python is a float, regardless of how many digits appear after it. Assigning 19.99 to price makes the variable reference a float object, and the built-in type function returns the class object for that type. Printing it displays the class name inside angle brackets, so the script outputs <class 'float'>.

Why this answer

Python infers a variable's type from the value assigned to it, and any numeric literal with a decimal point becomes a float. The type function returns the class of the object, and printing that class shows the type name in angle brackets. Since 19.99 includes a decimal point, the output is the float class.

Exam trap

The trap here is thinking a number with few decimal digits might be stored as an integer or a special decimal type rather than a plain float.

89
Multi-Selectmedium

Which three of the following are Python arithmetic operators? (Choose three.)

Select 3 answers
A.+
B.|
C.-
D.&
E.*
AnswersA, C, E

Addition operator

Why this answer

The plus sign (+) is a standard Python arithmetic operator used for addition. It performs numeric addition when both operands are numbers, and also supports string concatenation, but its primary role in arithmetic contexts is addition.

Exam trap

Python Institute often tests the distinction between arithmetic operators and bitwise operators, trapping candidates who mistake the vertical bar or ampersand for arithmetic symbols due to their visual similarity to plus or multiplication signs.

90
MCQeasy

A Python script stores a product identifier as id = '0042'. A developer needs to print the numeric value 42 followed by the type of the converted value in one line. Which code produces the output '42 <class 'int'>'?

A.print(float(id), type(float(id)))
B.print(int(id), type(int(id)))
C.print(str(id), type(id))
D.print(int(id) + type(int(id)))
AnswerB

int('0042') strips the leading zeros and returns the integer 42; type(int(id)) returns <class 'int'>. print() separates the two arguments with a space, so the output matches exactly. This is correct because int() accepts a numeric string with leading zeros and because type() reflects the converted object, not the original string.

Why this answer

Converting the string '0042' with int() yields the integer 42, discarding leading zeros, and wrapping that same call in type() reports <class 'int'>. Passing both results to print() inserts a space between them, matching the required output. The other choices either skip the numeric conversion or produce a float instead of an int.

Exam trap

The trap here is assuming that int('0042') raises an error because of the leading zeros, when in fact Python accepts leading zeros in int() string conversion.

91
MCQeasy

A programmer writes: x = 5; y = "10"; z = x + y. What will happen?

A.Prints error but continues execution
B.Prints 510
C.TypeError: unsupported operand type(s) for +: 'int' and 'str'
D.Prints 15
AnswerC

Python binds the + operator to the operand types at runtime, and no implicit coercion exists between int and str. Adding 5 to "10" therefore raises TypeError, satisfying the stem's requirement that mixed-type addition without explicit conversion fails rather than silently concatenating or coercing.

Why this answer

Python does not implicitly convert between incompatible types for the '+' operator. When an integer (int) and a string (str) are used with '+', Python raises a TypeError, as it cannot decide whether to perform arithmetic addition or string concatenation without explicit conversion.

Exam trap

Python Institute often tests the misconception that Python will automatically convert types to make the operation work, either by treating the integer as a string (concatenation) or the string as a number (addition), when in fact Python raises a TypeError for mixed-type '+' operations.

How to eliminate wrong answers

Option A is wrong because Python does not print an error and continue execution; it raises an unhandled TypeError that stops the program unless caught with a try/except block. Option B is wrong because it assumes Python will automatically convert the integer to a string and concatenate them as '510', but Python does not perform implicit type coercion for '+' between int and str. Option D is wrong because it assumes Python will convert the string '10' to an integer and perform numeric addition to get 15, but Python does not implicitly convert strings to integers for arithmetic operations.

92
MCQmedium

What is the output of the code?

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

Dividing with the `/` operator in Python 3 always returns a float, even when both operands are integers and divide evenly. Since the expression uses true division, the result's type is float, so `type()` reports `<class 'float'>`, satisfying the stem's request for the exact printed output.

Why this answer

The code uses the `type()` function to determine the data type of the result of the expression `10 / 3`. In Python 3, the `/` operator always performs true division, which returns a floating-point number even if the operands are integers. Therefore, `10 / 3` evaluates to `3.3333333333333335` (a float), and `type()` returns `<class 'float'>`.

Option C is correct.

Exam trap

Python Institute often tests the distinction between `/` (true division) and `//` (floor division) in Python 3, and the trap here is that candidates mistakenly think integer division with `/` yields an integer, confusing it with Python 2 behavior or the `//` operator.

How to eliminate wrong answers

Option A is wrong because the result of `10 / 3` is not a string; the `/` operator does not produce a string type. Option B is wrong because true division (`/`) in Python 3 never returns an integer; it always returns a float, even when the division is exact (e.g., `4 / 2` returns `2.0`). Option D is wrong because the result is not a Boolean; division does not yield a `bool` type, and the expression is not a comparison or logical operation.

93
Multi-Selectmedium

A Python developer is reviewing a script that contains several variable declarations. They want to identify which assignments use valid variable names according to Python's naming rules. Which TWO of the following variable names are valid? (Choose two.)

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

`my_var` is a valid Python identifier because it starts with a letter (m), contains only letters, digits, and underscores, and is not a reserved keyword. It follows the naming convention of using lowercase letters with underscores for readability. Therefore, it is a valid variable name.

Why this answer

Valid Python variable names must start with a letter or underscore, followed by letters, digits, or underscores, and must not be a reserved keyword. `my_var` and `_private` satisfy these rules, while `2nd_place` starts with a digit, `class` is a keyword, and `my-var` contains a hyphen.

Exam trap

The trap here is assuming that any descriptive name is valid, overlooking rules like starting with a digit or using a hyphen, or forgetting that keywords are reserved.

94
MCQhard

Given 'a = 10; b = 3; c = a // b; d = a % b', what is the value of c + d?

A.4
B.5
C.7
D.6
AnswerA

Integer floor division truncates 10 // 3 to 3, and modulo returns the remainder 1, so c + d equals 4. This satisfies the stem's requirement to evaluate both operators together, since Python's // discards the fractional part while % yields what is left over.

Why this answer

In Python, the // operator performs floor division, so a // b = 10 // 3 = 3. The % operator returns the remainder, so a % b = 10 % 3 = 1. Therefore, c + d = 3 + 1 = 4, making option A correct.

Exam trap

Python Institute often tests the distinction between floor division (//) and true division (/), and the trap here is that candidates may mistakenly use regular division (10 / 3 ≈ 3.33) and then add the remainder incorrectly, or forget that // and % are complementary operations that together reconstruct the original dividend.

How to eliminate wrong answers

Option B (5) is wrong because it might result from incorrectly using regular division (10 / 3 ≈ 3.33) and rounding up, or from adding the quotient (3) and remainder (1) incorrectly as 4, not 5. Option C (7) is wrong because it could come from adding the quotient (3) and the divisor (3) plus the remainder (1), or from miscomputing the remainder as 4 (10 % 3 = 1, not 4). Option D (6) is wrong because it might arise from adding the quotient (3) and the divisor (3) together, ignoring the remainder, or from a miscalculation of floor division as 2.

95
MCQeasy

Which of the following is a valid Python variable name?

A.2var
B._var
C.my-var
D.var$name
AnswerB

Underscores are permitted as the first character in Python identifiers, so `_var` satisfies the naming rules. Unlike digits, which cannot start a name, and reserved keywords such as `class`, the underscore prefix is valid. This makes `_var` a legal variable name.

Why this answer

(_var) is correct because Python variable names must start with a letter or an underscore, and can contain letters, digits, or underscores. The underscore is a valid starting character, making _var a legal identifier.

Exam trap

Python Institute often tests the misconception that hyphens or special characters like '$' are allowed in variable names, or that digits can start a name, because candidates confuse Python's rules with those of other languages like JavaScript or PHP.

How to eliminate wrong answers

Option A is wrong because Python variable names cannot begin with a digit; '2var' starts with '2', which violates the syntax rule. Option C is wrong because the hyphen '-' is not allowed in Python identifiers; only underscores, letters, and digits are permitted. Option D is wrong because the dollar sign '$' is not a valid character in Python variable names; identifiers are limited to alphanumeric characters and underscores.

96
MCQmedium

A cashier script stores a discount rate and a price, then computes the final amount. The developer writes: rate = 0.15 price = 200 final = price - price * rate print(final) What is printed?

A.30.0
B.170.0
C.200.15
D.170
AnswerB

Multiplication is evaluated before subtraction, so price * rate computes 200 * 0.15, which equals 30.0. Subtracting that from 200 gives 170.0. Because rate is a float, Python promotes the entire expression to float, so the printed value includes the decimal point even though the fractional part is zero.

Why this answer

Python evaluates multiplication before subtraction, so price * rate is computed first as 200 * 0.15, giving 30.0. That product is then subtracted from price, yielding 170.0. Because one operand is a float, the final result is a float and is displayed with a decimal point, distinguishing it from an integer result.

Exam trap

The trap here is treating the discount product as the final answer or expecting an integer output despite a float operand in the expression.

97
MCQeasy

A data analyst needs to read two integers from the user and compute their average as a float. The current code: a = int(input()) b = int(input()) avg = a + b / 2 print(avg) The output is always incorrect when a=5 and b=7 (expected 6.0, actual 8.5). The analyst cannot identify the bug. What is the root cause and correct fix?

A.The input function is not converting correctly; use float(input()) instead.
B.The print function is rounding the result; use print("{:.1f}".format(avg)).
C.The addition and division have wrong operator precedence; use parentheses: (a + b) / 2.
D.The division operator / always returns an integer; use // instead.
AnswerC

Division binds tighter than addition, so a + b / 2 computes a + (b/2) = 5 + 3.5 = 8.5. Parenthesising as (a + b) / 2 forces the sum first, giving 12 / 2 = 6.0, the expected float average.

Why this answer

In Python, the division operator `/` has higher precedence than addition `+`, so `a + b / 2` is evaluated as `a + (b / 2)`, not `(a + b) / 2`. For a=5 and b=7, this computes `5 + (7 / 2) = 5 + 3.5 = 8.5` instead of the expected `(5 + 7) / 2 = 12 / 2 = 6.0`. Adding parentheses around `a + b` forces the addition to occur first, yielding the correct average as a float.

Exam trap

Python Institute often tests operator precedence by presenting a simple arithmetic expression without parentheses, leading candidates to overlook the order of operations and incorrectly blame input conversion or output formatting.

How to eliminate wrong answers

Option A is wrong because the issue is not about input conversion; `int(input())` correctly reads integers, and using `float(input())` would not fix the operator precedence bug. Option B is wrong because the print function does not round the result; the actual computed value is 8.5, not 6.0, so formatting the output would still show 8.5. Option D is wrong because the `/` operator in Python 3 always returns a float (e.g., 7/2 = 3.5), and using `//` would perform floor division, yielding an integer result (e.g., 12//2 = 6) but would break for odd sums (e.g., 5+6=11, 11//2=5, not 5.5), so it is not the correct fix.

98
Multi-Selectmedium

Which TWO of the following Python data types are mutable?

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

Lists are mutable because their elements can be reassigned, appended or removed in place after creation, with the same object identity retained. This satisfies the stem's requirement for mutability, unlike tuples or strings, which return new objects on modification.

Why this answer

Option A (list) is correct because Python lists are mutable sequence types: you can change, add, or remove elements in place (e.g., append(), item assignment) without creating a new object. Option E (dict) is correct because dictionaries are mutable mappings: key-value pairs can be added, updated, or deleted in place (e.g., d['k'] = v, del d['k']). The unmarked options are immutable: str (B) cannot be modified in place since strings are immutable sequences, tuple (C) is an immutable sequence whose contents cannot be reassigned, and int (D) is an immutable numeric type where any arithmetic produces a new object rather than modifying the original.

Exam trap

Python Institute often tests the misconception that strings or tuples are mutable because they support indexing and slicing, but candidates must remember that these operations return new objects rather than modifying the original.

99
MCQeasy

A developer wants to store a person's age. Which of these variable names is invalid?

A._age
B.3rd_age
C.Age
D.age_3
AnswerB

Python identifiers cannot begin with a digit, so `3rd_age` fails at the lexer stage before any assignment occurs. The stem asks which name is invalid, and this constraint on the first character makes it the only option that cannot be parsed as a valid identifier.

Why this answer

In Python, variable names must start with a letter or an underscore, not a digit. Option B (`3rd_age`) begins with a digit, which violates Python's identifier naming rules and will raise a `SyntaxError` if used in code.

Exam trap

Python Institute often tests the rule that variable names cannot start with a digit, tricking candidates who focus on case sensitivity or underscores instead of the initial character restriction.

How to eliminate wrong answers

Option A is wrong because `_age` starts with an underscore, which is allowed in Python variable names. Option C is wrong because `Age` starts with a letter and is case-sensitive but valid. Option D is wrong because `age_3` starts with a letter and contains an underscore and digit, both permitted after the first character.

100
MCQeasy

A junior developer is writing a script to calculate the total cost of items in a shopping cart. The script uses variables item_price (float) and quantity (int). The code is: item_price = 2.5 quantity = 3 total = item_price * quantity print("Total: " + total) When run, this code raises a TypeError. The developer is confused because the multiplication seems correct. What is the most likely issue and the correct fix?

A.The variable total is being overwritten by the print statement; use a different variable name.
B.The multiplication should be written as int(item_price) * quantity to ensure integer result.
C.The variable names are too descriptive; rename them to a and b to avoid confusion.
D.The print function cannot concatenate a string with a float; convert total to string using str(total).
AnswerD

Python's + operator cannot concatenate str with float, so print raises TypeError regardless of the arithmetic being valid. Wrapping total in str() converts the numeric result to text, satisfying the concatenation requirement and producing the intended output.

Why this answer

The `print` function in Python expects all arguments to be strings when using the `+` operator for concatenation. The variable `total` is a float (result of multiplying a float by an int), and Python does not implicitly convert it to a string. The error is a `TypeError: can only concatenate str (not 'float') to str`.

The fix is to explicitly convert `total` to a string using `str(total)` before concatenation.

Exam trap

Python Institute often tests the distinction between arithmetic operations (which work across numeric types) and string concatenation (which requires explicit type conversion), trapping candidates who assume Python will automatically convert a float to a string when using the `+` operator.

How to eliminate wrong answers

Option A is wrong because the `print` statement does not overwrite the variable `total`; it only reads its value. The error is a type mismatch in concatenation, not a variable naming issue. Option B is wrong because converting `item_price` to an integer would lose the decimal precision (2.5 becomes 2), and the multiplication result would be incorrect for a shopping cart total.

The error is not about integer vs. float multiplication; it's about string concatenation. Option C is wrong because variable names being descriptive is a best practice, not a cause of errors. Renaming them to `a` and `b` would not fix the `TypeError` and would reduce code readability.

101
MCQmedium

You are a data analyst at a retail company. You have a list of sales figures stored as strings in a list: sales = ['100', '200', '300']. You need to calculate the total sum. A colleague suggests using: total = sum(sales). However, this raises a TypeError because sum() requires numeric values. Which approach should you take to correctly calculate the total as an integer?

A.Use total = sum(sales) and catch TypeError
B.Use total = sum(int(s) for s in sales)
C.Use total = sum(map(str, sales))
D.Use total = 0; for s in sales: total += s
AnswerB

Converting each string to an integer with `int(s)` before summation satisfies the numeric-type constraint that `sum()` enforces, since the built-in rejects strings outright. The generator expression feeds integers one at a time, avoiding an intermediate list, and returns the total as an `int` exactly as the stem requires.

Why this answer

Option B uses a generator expression to convert each string element to an integer before passing them to sum(). Option A attempts to catch the TypeError but doesn't convert the strings to numbers. Option C uses str() to convert the numbers to strings, so sum() still receives strings and raises a TypeError.

Option D attempts to concatenate strings with +=, resulting in a string, not a numeric total.

Exam trap

Python Institute often tests the misconception that `sum()` can implicitly convert strings to numbers, or that catching an exception is a valid workaround, when in fact explicit conversion via `int()` is required.

How to eliminate wrong answers

Option A is wrong because catching a `TypeError` does not fix the underlying problem—the strings are still not converted to numbers, so the sum would still fail or require additional handling. Option D is wrong because `total += s` attempts to add a string to an integer, which raises a `TypeError` due to incompatible types; the loop must convert each `s` to an integer first.

102
MCQhard

Which of the following is an invalid variable name in Python?

A._myVar
B.myVar
C.my-var
D.my_var
AnswerC

Hyphens are parsed as the subtraction operator, so `my-var` reads as `my` minus `var` rather than a single identifier. Python identifiers permit letters, digits and underscores only, and cannot begin with a digit. The stem asks for an invalid name, which this satisfies.

Why this answer

'my-var' contains a hyphen, which is not allowed in Python variable names. Python identifiers can only include letters, digits, and underscores, and cannot start with a digit. The hyphen is interpreted as a minus operator, making 'my-var' a syntax error.

Exam trap

The PCEP exam often tests the misconception that hyphens are acceptable in variable names because they appear in other languages (like JavaScript object keys) or in file names, but Python strictly prohibits them in identifiers.

How to eliminate wrong answers

Option A is wrong because '_myVar' is a valid variable name; underscores are allowed and commonly used for private or internal variables. Option B is wrong because 'myVar' follows Python naming rules (letters and underscores, no special characters). Option D is wrong because 'my_var' is valid; underscores are permitted and often used in snake_case naming conventions.

103
Multi-Selecteasy

Which TWO data types are immutable in Python?

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

Strings store an immutable sequence of Unicode code points, so any operation that appears to modify one — concatenation, slicing, `replace()` — returns a new `str` object rather than altering the original in place. This satisfies the stem's immutability constraint, since no method can change an existing string's contents after creation.

Why this answer

Option A (str) is correct because Python strings are immutable: once created, their characters cannot be changed in place, and operations like concatenation or replace() return new string objects rather than modifying the original. Option E (int) is correct because integers are immutable numeric objects; any arithmetic operation such as x += 1 rebinds the name to a new int object instead of altering the existing one. The unmarked options do not belong because set (B), list (C), and dict (D) are all mutable container types whose contents can be modified in place via methods like add(), append(), and item assignment.

Exam trap

The PCEP exam often tests the misconception that 'immutable' means the variable cannot be reassigned, but immutability refers to the object itself, not the variable binding; candidates may incorrectly think lists or dicts are immutable because they can reassign the variable.

104
MCQmedium

A developer writes: print(10 * '5'). What is the output?

A.10
B.50
C.5
D.5555555555
AnswerD

Multiplying a string by an integer repeats it: `'5' * 10` yields ten concatenated copies, giving `5555555555`. Python's `*` operator overloads this way for sequence types, satisfying the stem's requirement that the operand order places the string second and the integer first.

Why this answer

In Python, the multiplication operator (*) when used with a string and an integer performs string repetition. The expression 10 * '5' repeats the string '5' ten times, resulting in the string '5555555555'. The print() function then outputs this concatenated string without quotes.

Exam trap

The trap here is that candidates often confuse the string repetition operator with arithmetic multiplication, leading them to mistakenly compute 10 * 5 = 50 instead of recognizing that the operand is a string literal.

How to eliminate wrong answers

Option A is wrong because it incorrectly assumes the result is the integer 10, ignoring that the string '5' is repeated, not converted to an integer. Option B is wrong because it treats the string '5' as the integer 5 and performs arithmetic multiplication (10 * 5 = 50), which is a common confusion between string repetition and numeric multiplication. Option C is wrong because it suggests only a single '5' is output, misunderstanding that the operator repeats the string multiple times.

105
Multi-Selecthard

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

Select 3 answers
A.str
B.boolean
C.int
D.list
E.array
AnswersA, C, D

str is a built-in Python data type representing immutable sequences of Unicode characters, created with quotes or the str() constructor. It is one of the fundamental scalar types available without importing any module, satisfying the question's criterion for a built-in type.

Why this answer

Option A, str, is correct because str is a built-in Python type representing immutable Unicode text strings, created via literals like 'abc' or the str() constructor. Option C, int, is correct because int is a built-in Python type for arbitrary-precision integers, produced by literals like 42 or int(). Option D, list, is correct because list is a built-in Python type for mutable ordered sequences, created with literals like [1, 2] or list().

Option B, boolean, is not a built-in Python type name; the actual built-in type is bool (a subclass of int), so 'boolean' is not a valid Python type. Option E, array, is not a built-in Python type; arrays are provided by the standard-library array module (array.array) or third-party libraries such as NumPy, not as a core built-in type.

Exam trap

Python Institute often tests the distinction between built-in types and types available only through modules, so candidates mistakenly choose `array` or `boolean` because they sound familiar, but Python uses `bool` and requires importing `array`.

106
MCQeasy

A student writes the following code to calculate the average of two numbers: ```python num1 = input("Enter first number: ") num2 = input("Enter second number: ") avg = (num1 + num2) / 2 print("Average:", avg) ``` When executed, the code raises a TypeError. What is the most likely cause?

A.The division operator '/' is not allowed for integers
B.The input() function returns a string, not a number, so arithmetic operations are invalid without conversion
C.The addition operator '+' cannot be used with strings
D.The variable names num1 and num2 are reserved keywords
AnswerB

The `input()` function always returns a string, so `num1 + num2` performs string concatenation rather than numeric addition, and dividing that concatenated string by 2 raises a TypeError. Converting both values with `int()` or `float()` before the arithmetic satisfies the requirement for numeric operands.

Why this answer

The `input()` function in Python always returns a string, regardless of what the user types. Attempting to use the `+` operator on two strings performs concatenation, not numeric addition, and then dividing a concatenated string by an integer with `/` raises a `TypeError` because the `/` operator is not defined for strings. To fix this, the inputs must be explicitly converted to numbers using `int()` or `float()` before arithmetic operations.

Exam trap

Python Institute often tests the misconception that `input()` returns a numeric type when the user types digits, leading candidates to overlook the need for explicit type conversion with `int()` or `float()`.

How to eliminate wrong answers

Option A is wrong because the division operator '/' is fully allowed for integers in Python and performs true division, returning a float. Option C is wrong because the addition operator '+' can be used with strings for concatenation; the error arises from the subsequent division, not the addition itself. Option D is wrong because 'num1' and 'num2' are not reserved keywords in Python; they are valid variable names.

107
MCQeasy

A developer writes the following code: x = 5; y = x; x = 10. What are the values of x and y after execution?

A.x = 10, y = 5
B.x = 5, y = 10
C.x = 5, y = 5
D.x = 10, y = 10
AnswerA

Assignment binds the name y to the integer object 5, not to the variable x. Rebinding x to 10 therefore leaves y untouched, so x = 10 and y = 5. This satisfies the stem's constraint that integers are immutable and assignment copies the reference, not a live link.

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 = 10` is executed, it binds the name `x` to a new integer object 10, while `y` still references the original object 5. Thus, after execution, `x` is 10 and `y` is 5.

Exam trap

Python Institute often tests the misconception that `y = x` creates a persistent link between variables, leading candidates to incorrectly assume `y` changes when `x` is reassigned.

How to eliminate wrong answers

Option B is wrong because it suggests `x = 5` and `y = 10`, which would require `y` to be reassigned after `x` changed, but no such reassignment occurs. Option C is wrong because it implies `x` remains 5, ignoring the explicit reassignment `x = 10`. Option D is wrong because it assumes `y` is updated when `x` changes, which would only happen if integers were mutable or if `y` were a reference to `x` itself, but Python integers are immutable and assignment creates a new binding.

108
Multi-Selecthard

Which TWO of the following expressions evaluate to 0? (Select two.)

Select 2 answers
A.False * 1
B.5 // 2 * 2
C.True == 0
D.int(0.5)
E.5 % 2
AnswersA, D

In Python, `False` is a bool subclass of int with numeric value 0, so `False * 1` yields integer 0. This satisfies the stem's requirement for an expression evaluating to 0, since multiplying zero by one returns zero regardless of operand order.

Why this answer

Option A (False * 1) is correct because in Python, False is a bool that behaves as the integer 0 in arithmetic, so 0 * 1 evaluates to 0. Option D (int(0.5)) is correct because int() truncates toward zero, discarding the fractional part of 0.5 and returning 0. Option B (5 // 2 * 2) evaluates to 4, since floor division 5 // 2 gives 2 and 2 * 2 is 4, not 0.

Option C (True == 0) evaluates to False, because True equals 1, not 0. Option E (5 % 2) evaluates to 1, the remainder of 5 divided by 2, so it is not 0.

Exam trap

Python Institute often tests the distinction between boolean values in arithmetic versus comparison contexts, tricking candidates into thinking `True == 0` evaluates to the integer 0 rather than the boolean `False`.

109
MCQeasy

A program prompts a user for their age using input(). Which line of code correctly stores the age as an integer?

A.age = str(input("Enter age: "))
B.age = float(input("Enter age: "))
C.age = int(input("Enter age: "))
D.age = input("Enter age: ")
AnswerC

input() returns a string, so int() must wrap the call to convert the entered text into an integer before assignment. This satisfies the stem's requirement to store the age as an integer, enabling arithmetic rather than string concatenation.

Why this answer

The `int()` function explicitly converts the string returned by `input()` into an integer, which is required for storing a numeric age value. The `input()` function always returns a string in Python, so without conversion, arithmetic operations would fail or produce unexpected results.

Exam trap

The trap here is that candidates often forget `input()` returns a string and assume the user's typed digits are automatically stored as a number, leading them to pick option D without any conversion.

How to eliminate wrong answers

Option A is wrong because `str()` converts the input to a string, but `input()` already returns a string, so this adds unnecessary conversion and does not produce an integer. Option B is wrong because `float()` converts the input to a floating-point number, which is not appropriate for an age that should be a whole number and may introduce decimal precision issues. Option D is wrong because it stores the raw string from `input()` without any type conversion, so the variable remains a string and cannot be used directly in integer arithmetic.

110
MCQhard

What is the output of the following code? config = {} print('Not set' if config.get('timeout') is None else config.get('timeout'))

A.KeyError: 'timeout'
B.Not set
C.None
D.False
AnswerB

Since `config` is empty, `config.get('timeout')` returns `None` rather than raising a `KeyError`, so the conditional expression evaluates the true branch and prints `Not set`. The `is None` comparison confirms the missing key, satisfying the stem's requirement to avoid an exception.

Why this answer

The code attempts to access a dictionary key 'timeout' that does not exist. Using square bracket access on a missing key raises a KeyError, but the code uses the .get() method, which returns None by default if the key is missing. Since the key 'timeout' is not in the dictionary, .get('timeout') returns None, and the print statement outputs 'Not set' because the condition `config.get('timeout') is None` evaluates to True.

Exam trap

Python Institute often tests the distinction between dict[key] (which raises KeyError) and dict.get(key) (which returns None) to trap candidates who assume all dictionary access methods behave the same way.

How to eliminate wrong answers

Option A is wrong because a KeyError would only occur if square brackets (config['timeout']) were used on a missing key, but the code uses .get() which safely returns None. Option C is wrong because None is the actual return value of .get(), but the code prints the string 'Not set' due to the if condition, not None itself. Option D is wrong because False is a boolean value, not the output; the condition checks for None, not False, and prints a string.

111
MCQhard

A script calculates total cost: price = 49.95, quantity = 3, tax_rate = 0.08. The developer writes: total = price * quantity * (1 + tax_rate). The result is printed as 161.838. Which best practice is being violated?

A.Using parentheses unnecessarily.
B.Not using an f-string to format the output.
C.Not rounding the result to two decimal places for currency.
D.Using multiplication instead of addition for tax.
AnswerC

Currency values require two decimal places, but the calculation produces 161.838, an unrounded float. Floating-point arithmetic introduces representation error, so monetary results must be rounded, typically with round() or Decimal, to avoid displaying fractional cents. This violates the best practise of rounding currency output.

Why this answer

When dealing with currency values, best practice dictates rounding to two decimal places to represent cents. The raw result 161.838 is not a valid monetary amount; it should be rounded to 161.84 using `round(total, 2)` or formatted with `:.2f`. This ensures accuracy and avoids confusion in financial calculations.

Exam trap

Python Institute often tests the misconception that any arithmetic result is acceptable as long as the formula is correct, but the trap is that currency values require explicit rounding to two decimal places to follow financial best practices.

How to eliminate wrong answers

Option A is wrong because the parentheses are necessary to ensure the tax multiplier (1 + tax_rate) is computed before multiplication; without them, the expression would be evaluated incorrectly due to operator precedence. Option B is wrong because using an f-string is a formatting preference, not a best practice violation; the core issue is the lack of rounding, not the output method. Option D is wrong because the tax calculation correctly uses multiplication to apply the tax rate as a percentage; addition would incorrectly add a flat value instead of a proportional tax.

112
MCQmedium

A developer needs to read an integer from user input and store it. Which code snippet accomplishes this?

A.x = int(input())
B.x = read_int()
C.x = input(int())
D.x = int(input)
AnswerA

input() returns a string, so int() converts that string into an integer before assignment to x. This satisfies the requirement to read and store an integer, whereas storing the raw input would leave x as a string and break later arithmetic.

Why this answer

`int(input())` first calls `input()` to read a string from the user, then passes that string to `int()` to convert it to an integer. This is the standard Python pattern for reading an integer from standard input.

Exam trap

Python Institute often tests the distinction between calling a function (with parentheses) and referencing it (without parentheses), so candidates mistakenly write `int(input)` instead of `int(input())`.

How to eliminate wrong answers

Option B is wrong because `read_int()` is not a built-in Python function; it would raise a NameError unless explicitly defined. Option C is wrong because `input(int())` attempts to call `int()` with no argument (which returns 0) and then passes that integer to `input()`, which expects a string prompt, causing a TypeError. Option D is wrong because `int(input)` passes the function object `input` (not its result) to `int()`, which raises a TypeError since `int()` expects a string or number, not a function.

113
MCQmedium

A script starts with: name = "Ada" age = 36 Which line correctly prints: Ada is 36 years old

A.print("name is age years old")
B.print(name + " is " + int(age) + " years old")
C.print(name, "is", age, "years old")
D.print(name + " is " + age + " years old")
AnswerC

Passing multiple arguments to print automatically separates them with a single space, so the string name, the word is, the integer age, and the phrase years old are joined into the desired sentence. Python converts age to its text form during printing, avoiding any type error. The resulting output is exactly Ada is 36 years old.

Why this answer

The print function accepts multiple arguments and inserts a space between each one, so it can mix strings and numbers without manual conversion. Concatenation with + requires both operands to be strings, so it fails when an integer is involved unless str is applied. The multi-argument form is the simplest correct way to produce the sentence.

Exam trap

The trap here is assuming the + operator can join strings and integers directly, when Python requires an explicit str conversion for concatenation.

114
MCQeasy

A Python script contains: print(10 / 4) print(10 // 4) print(10 % 4) What output does this produce?

A.2, 2, 2
B.2.5, 2, 2
C.2.5, 2.5, 2
D.2.5, 2, 0.5
AnswerB

The true division operator / always returns a float, so 10 / 4 gives 2.5. Floor division // returns the whole-number part of the quotient, so 10 // 4 gives 2. The modulo % returns the remainder, and 4 goes into 10 twice with 2 left over, so 10 % 4 gives 2. All three lines match these expected results.

Why this answer

True division with / yields a float result, while floor division with // discards the fractional part to give a whole number, and the modulo operator % gives the remainder. For 10 and 4, these produce 2.5, 2, and 2 respectively. Recognizing that / and // behave differently is essential when predicting numeric output in Python.

Exam trap

The trap here is assuming that the single slash / truncates like floor division, when it actually returns a float even for evenly divisible integers.

115
MCQmedium

A programmer writes the following code: `x = 7` then `y = 2` then `z = x / y`. What is the data type and value of `z`?

A.`float` with value `3.5`
B.`int` with value `4`
C.`int` with value `3`
D.`float` with value `3.0`
AnswerA

In Python 3, the `/` operator performs true division and always returns a `float`, regardless of operand types. With `x = 7` and `y = 2`, the result is `3.5`, a floating-point number. This is a key difference from Python 2, where integer division with `/` would yield an integer. Here, the type is `float` and the value is `3.5`.

Why this answer

In Python 3, the division operator `/` always returns a float, even when dividing two integers that yield a whole number. For `x = 7` and `y = 2`, the result is `3.5`, stored as a `float`. This behavior differs from Python 2, where `/` performed integer division for integers.

The `//` operator performs floor division and returns an integer when both operands are integers, but that is not used here.

Exam trap

The trap here is assuming that division of two integers returns an integer, perhaps due to experience with other programming languages or Python 2.

116
MCQmedium

A program contains this code: print(1 and 2 or 3). What is the output?

A.3
B.1
C.True
D.2
AnswerD

Python's `and` binds tighter than `or`, so `1 and 2` evaluates first. Since 1 is truthy, `and` returns its second operand, 2. That truthy result short-circuits the `or`, so 3 is never evaluated, satisfying the stem's precedence and short-circuit constraints.

Why this answer

In Python, the `and` and `or` operators short-circuit and return the last evaluated operand, not a boolean. `1 and 2` evaluates to `2` because both are truthy and `and` returns the last truthy value. Then `2 or 3` short-circuits because `2` is truthy, so `or` returns `2` without evaluating `3`. Thus, the output is `2`.

Exam trap

Python Institute often tests the misconception that `and`/`or` always return `True` or `False`, leading candidates to pick `True` (option C) instead of the actual operand value `2`.

How to eliminate wrong answers

Option A is wrong because `3` would only be returned if both `1` and `2` were falsy in an `or` chain, but here `2` is truthy and short-circuits the `or`. Option B is wrong because `1` is not the final result; `and` returns the last truthy operand (`2`), not the first. Option C is wrong because the expression does not return a boolean `True`; it returns the actual operand value `2`, which is truthy but not the boolean `True`.

117
MCQeasy

Refer to the exhibit. What is the output of the Python code?

A.['abc', 'abc', 'abc']
B.abcabc abc
C.abc abc abc
D.abcabcabc
AnswerD

String repetition with the `*` operator concatenates the original sequence three times, producing `abcabcabc`. This satisfies the stem's requirement to determine the exact output of the multiplication expression, since `"abc" * 3` yields the repeated string rather than raising an error or returning a numeric result.

Why this answer

The code `print('abc' * 3)` uses the multiplication operator on a string. In Python, multiplying a string by an integer repeats the string that many times, concatenating the copies without any separator. Therefore, `'abc' * 3` produces the string `'abcabcabc'`, which is printed.

The correct output is `abcabcabc` (without quotes).

Exam trap

The trap here is that candidates often confuse string multiplication with list multiplication or expect spaces between repetitions, but Python's string multiplication concatenates the string directly without any separator.

How to eliminate wrong answers

Option A is wrong because it shows a list with three 'abc' strings, which would be the output if the code used `['abc'] * 3` and printed the list, but the correct code uses string multiplication, not list multiplication. Option B is wrong because it shows 'abcabc abc' with a space, which would result from printing a list or using incorrect concatenation, but string multiplication does not insert spaces. Option C is wrong because it shows 'abc abc abc' with spaces, which would be the output of `print('abc', 'abc', 'abc')` or using `join` with spaces, not string multiplication.

118
MCQhard

A developer writes: a = 3; b = 4; c = a + b / 2. What is the value of c?

A.3
B.3.5
C.5
D.5.0
AnswerD

Division precedes addition, so b / 2 evaluates first as 4 / 2, yielding the float 2.0. Adding a (3) gives 5.0, and because true division always returns a float, the result is 5.0 rather than integer 5.

Why this answer

In Python, the division operator `/` always returns a float, and operator precedence dictates that division is performed before addition. Thus, `b / 2` evaluates to `4 / 2 = 2.0`, then `a + 2.0` yields `3 + 2.0 = 5.0`. Option D is correct because the result is a float value of 5.0.

Exam trap

Python Institute often tests the combination of operator precedence and the fact that `/` always returns a float in Python 3, trapping candidates who expect integer division or who incorrectly group the expression as `(a + b) / 2`.

How to eliminate wrong answers

Option A is wrong because it incorrectly assumes integer division or that the expression evaluates to 3, ignoring the division and addition. Option B is wrong because it suggests the result is 3.5, which would occur if the expression were `(a + b) / 2` due to incorrect grouping. Option C is wrong because it gives the integer 5, but Python's `/` operator always returns a float, so the result is 5.0, not the int 5.

119
MCQhard

A developer needs to convert a string '25' to an integer and then add 10. Which code correctly performs this?

A.print(int('25') + 10)
B.print('25' + 10)
C.print(int('25') + '10')
D.print('25' + str(10))
AnswerA

Correct conversion and addition.

Why this answer

`int('25')` converts the string '25' to the integer 25, and then `+ 10` performs integer addition, resulting in 35. The `print()` function outputs the result. This follows Python's type conversion rules where explicit conversion is required to combine a string and an integer in arithmetic.

Exam trap

Python Institute often tests the misconception that Python will automatically convert types in arithmetic expressions, leading candidates to choose options that mix strings and integers without explicit conversion.

How to eliminate wrong answers

Option B is wrong because it attempts to add a string ('25') and an integer (10) directly, which raises a TypeError in Python as the `+` operator is not defined for mixed string-integer operands. Option C is wrong because it adds an integer (from `int('25')`) to a string ('10'), which also raises a TypeError for the same reason. Option D is wrong because it concatenates the string '25' with the string '10' (from `str(10)`), producing '2510' rather than performing arithmetic addition.

120
MCQmedium

A cashier script stores a price as a string and needs to apply a 10 percent discount. The code is: price = "19.99" discount = 0.10 final = price * (1 - discount) print(final) What happens when this code runs?

A.It prints "19.99" repeated zero times, resulting in an empty string.
B.It prints 199.9 because the decimal point is ignored during multiplication.
C.It raises a TypeError because a string cannot be multiplied by a float.
D.It prints 17.991 because Python converts the string automatically.
AnswerC

Multiplying a str by an int repeats the string, but multiplying a str by a float is unsupported and raises TypeError. Since price is still the string "19.99" and (1 - discount) evaluates to the float 0.9, the * operator fails. The script must convert price with float(price) before the arithmetic can succeed.

Why this answer

The * operator supports string repetition only when the other operand is an integer. Here the other operand is the float 0.9, so Python raises TypeError. To compute the discounted price the code must first convert the string to a number, for example float(price) * (1 - discount), and only then print the result.

Exam trap

The trap here is expecting Python to convert numeric-looking strings to numbers automatically during arithmetic, which it never does.

121
Multi-Selecthard

Given the following code, which of the following statements are true after execution? (Choose three.) x = 10 y = 3.0 z = x / y w = x // y

Select 3 answers
A.The expression x % y is valid.
B.The value of z is approximately 3.33 (type float).
C.The type of w is int.
D.The expression x / y returns an integer.
E.The value of w is 3.0.
AnswersA, B, E

The modulo operator accepts mixed numeric types in Python, so `x % y` with an integer and a float is valid and evaluates to 1.0. This satisfies the stem's requirement for true statements after execution, since no type restriction prevents combining int and float operands in arithmetic.

Why this answer

Option A is correct because x % y uses the modulo operator on an int and a float, which is valid in Python and yields the float remainder 1.0. Option B is correct because x / y performs true division (10 / 3.0), producing the float value approximately 3.3333333333333335. Option E is correct because x // y performs floor division; with a float operand the result is a float, so 10 // 3.0 equals 3.0.

Option C is not correct because w is a float (3.0), not an int, since one operand is a float. Option D is not correct because the / operator always returns a float in Python 3, not an integer.

Exam trap

The PCEP exam often tests the misconception that floor division (//) returns an int when one operand is a float, or that true division (/) can return an integer, leading candidates to incorrectly select options C or D.

122
MCQmedium

A program needs to read a user's age and print a message if they are 18 or older. Which code snippet correctly accomplishes this?

A.age = int(input('Age: ')) if age >= '18': print('Adult')
B.age = int(input('Age: ')) if age >= 18: print('Adult')
C.age = input('Age: ') if age >= 18: print('Adult')
D.age = input('Age: ') if age == 18: print('Adult')
AnswerB

int(input('Age: ')) converts the string returned by input() into an integer, enabling numeric comparison. The condition age >= 18 then prints 'Adult' when the age is 18 or above, satisfying the stem's requirement of handling users aged 18 or older.

Why this answer

It uses `int()` to convert the user input to an integer, then compares it with the integer `18` using the `>=` operator. This ensures a proper numeric comparison, and if the condition is true, it prints 'Adult'.

Exam trap

Python Institute often tests the distinction between string and integer types, and the trap here is that candidates forget to convert the input to an integer, leading to a type mismatch error when using comparison operators like `>=`.

How to eliminate wrong answers

Option A is wrong because it compares an integer (`age`) with a string `'18'`, which in Python 3 raises a `TypeError` (or in some contexts may produce unexpected results). Option C is wrong because `input()` returns a string, and comparing a string to the integer `18` with `>=` raises a `TypeError` (strings and integers cannot be compared with relational operators). Option D is wrong because it uses `==` instead of `>=`, so it only prints 'Adult' when the age is exactly 18, not for ages greater than 18, and also compares a string (from `input()`) to an integer, which would raise a `TypeError`.

123
MCQeasy

A student is analyzing Python code and wants to understand the result of the expression `2 ** 3 ** 2` in Python 3. What value does this expression produce?

A.36
B.512
C.128
D.64
AnswerB

The exponentiation operator (**) in Python is right-associative, so 2 ** 3 ** 2 is evaluated as 2 ** (3 ** 2). First, 3 ** 2 equals 9; then 2 ** 9 equals 512. Thus, the expression yields 512, demonstrating the right-associative grouping of the ** operator.

Why this answer

The exponentiation operator (**) in Python is right-associative, meaning that in a chain like 2 ** 3 ** 2, the rightmost operation is performed first. This gives 2 ** (3 ** 2) = 2 ** 9 = 512. Understanding associativity prevents errors when chaining exponentiation without parentheses.

Exam trap

The trap here is assuming that exponentiation is left-associative, which would lead to computing (2 ** 3) ** 2 = 64 instead of the correct right-associative result.

124
MCQmedium

A junior developer writes: x = 10; y = 3; print(x % y). What will be printed?

A.3.33
B.1
C.0
D.3
AnswerB

The modulo operator returns the remainder after integer division, so 10 % 3 evaluates to 1 because 3 divides into 10 three times with 1 left over. This satisfies the stem's requirement to predict the printed output of the expression.

Why this answer

The modulo operator (%) returns the remainder of the division of the left operand by the right operand. Here, 10 divided by 3 equals 3 with a remainder of 1, so print(x % y) outputs 1.

Exam trap

Python Institute often tests the distinction between the modulo operator (%) and integer division (//) or floating-point division (/), trapping candidates who confuse remainder with quotient or decimal result.

How to eliminate wrong answers

Option A is wrong because 3.33 would be the result of floating-point division (10 / 3), not the modulo operation. Option C is wrong because 0 would only occur if the division had no remainder (e.g., 9 % 3). Option D is wrong because 3 is the quotient of integer division (10 // 3), not the remainder from modulo.

125
MCQeasy

A student writes the following code: name = "Alice" age = 25 print("Name: " + name + ", Age: " + age) What happens when the code runs?

A.It raises a SyntaxError before execution.
B.It prints: Name: Alice, Age: age
C.It prints: Name: Alice, Age: 25
D.A TypeError is raised because you cannot concatenate a string and an integer.
AnswerD

The + operator between a string and an integer is not allowed. Python raises a TypeError with a message like 'can only concatenate str (not "int") to str'. The age variable is an integer, so the concatenation fails at runtime.

Why this answer

In Python, the + operator cannot combine a string and an integer. The expression attempts to concatenate the string literal with the integer variable age, which raises a TypeError. To fix this, the integer must be converted to a string using str(age) or formatted using an f-string or the format() method.

Exam trap

The trap here is thinking that Python automatically converts types during string concatenation, as some languages do, when in fact it requires explicit conversion.

126
MCQeasy

A Python script contains the following code: price = 19.99 quantity = 3 total = price * quantity print(type(total)) What is displayed when this script runs?

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

In Python, when an int and a float are combined with the multiplication operator, the int is converted to a float and the result is a float. Since price is 19.99, a float, multiplying it by the integer quantity produces a float value, and type() reports the class of that result as float.

Why this answer

The multiplication of a float and an int in Python produces a float because Python applies numeric type promotion, converting the integer operand to a float before the operation. The variable total therefore holds a float, and type(total) displays the class object for floats. Integer output would require both operands to be int, and string output would require quoted text.

Exam trap

The trap here is assuming that multiplying a decimal literal by a whole number returns an integer merely because the product has no fractional part shown.

127
MCQhard

Given 's = "Hello"; t = s[0:3]; print(t)', what is the output?

A.ello
B.H
C.Hell
D.Hel
AnswerD

Slicing extracts characters from index 0 up to, but excluding, index 3, yielding "Hel". The start index defaults to 0, and the stop index is exclusive, so the character at position 3 ("l") is omitted. This satisfies the stem's requirement to print the first three characters of "Hello".

Why this answer

String slicing in Python uses the syntax `s[start:stop]`, where the stop index is exclusive. For `s = "Hello"`, `s[0:3]` extracts characters from index 0 up to but not including index 3, resulting in indices 0 ('H'), 1 ('e'), and 2 ('l'), giving the substring "Hel".

Exam trap

The trap here is that candidates often confuse the exclusive stop index with an inclusive one, leading them to select "Hell" (option C) because they mistakenly include index 3, or they misremember the starting index and pick "ello" (option A).

How to eliminate wrong answers

Option A is wrong because it represents `s[1:5]` (or `s[1:]`), which would skip the first character, not the slice `s[0:3]`. Option B is wrong because it represents `s[0:1]`, which extracts only the first character, not the first three. Option C is wrong because it represents `s[0:4]`, which includes index 3 ('l') and would output "Hell", but the correct slice stops at index 3 (exclusive), so only "Hel" is produced.

128
MCQeasy

A developer writes a script to read user input using input() and then prints it. However, the program crashes when the user enters a number. What is the most likely cause?

A.The input is read as a string, but the code treats it as a number without conversion.
B.The script uses Python 2, where input() evaluates input as code.
C.The print() function expects a string, but the input is a number.
D.The input() function cannot handle numeric input.
AnswerA

The crash occurs because `input()` always returns a string, so any arithmetic or numeric comparison on that value raises a `TypeError`. The stem's constraint is unhandled numeric use of raw input; converting with `int()` or `float()` before operating on the value resolves it.

Why this answer

The `input()` function in Python 3 always returns a string, regardless of what the user types. If the user enters a number, the program may crash if the code later performs an operation (like arithmetic or comparison) on that string without first converting it to an integer or float using `int()` or `float()`. This mismatch between the string type and the expected numeric type causes a `TypeError`.

Exam trap

Python Institute often tests the misconception that `input()` can return different types based on the input, when in Python 3 it always returns a string, leading candidates to overlook the need for explicit conversion.

How to eliminate wrong answers

Option B is wrong because in Python 2, `input()` evaluates the input as Python code, which could cause crashes with numeric input, but the question context (PCEP exam) assumes Python 3, where `input()` returns a string. Option C is wrong because `print()` can handle any data type, including numbers, by converting them to strings automatically. Option D is wrong because `input()` can handle numeric input perfectly fine; it just stores it as a string, which is not a crash in itself.

129
Multi-Selecteasy

Which THREE of the following are Python data types?

Select 3 answers
A.str
B.math
C.bool
D.float
E.None
AnswersA, C, D

`str` is a built-in Python data type representing immutable sequences of Unicode characters, satisfying the stem's requirement for a genuine data type. It is a core text type created via literals or `str()`, distinct from containers like `list` and `dict`, and is recognised by `isinstance("x", str)`.

Why this answer

Option A, str, is correct because str is Python's built-in immutable text/string type, used for sequences of Unicode characters. Option C, bool, is correct because bool is a built-in subclass of int representing the two truth values True and False. Option D, float, is correct because float is Python's built-in floating-point type, typically implemented as a C double for real numbers.

Option B, math, is not a data type but a standard-library module that provides mathematical functions. Option E, None, is not a data type but the singleton object None, whose type is NoneType.

Exam trap

The PCEP exam often tests the distinction between a data type and a module or a value, so candidates may mistakenly select `math` (a module) or `None` (a value) as data types because they appear frequently in Python code.

130
MCQmedium

Which data type is most appropriate to store a user's age in a Python program?

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

Age is a whole-number count of years, so int stores it exactly without floating-point rounding artefacts. A float would permit nonsensical fractional ages, while str would prevent arithmetic; int matches the discrete, countable nature of the value.

Why this answer

A user's age is a whole number without a fractional component, so the integer type (int) is the most appropriate choice. Python's int can represent any integer value, including ages like 25 or 0, without the overhead or precision issues of floating-point numbers.

Exam trap

Python Institute often tests the distinction between numeric types by presenting a scenario where a float seems plausible (e.g., 'age could be 25.5 years'), but the PCEP expects you to recognize that age is conventionally an integer and that Python's int is the correct choice for whole-number data.

How to eliminate wrong answers

Option B (float) is wrong because age is always a whole number; using float would introduce unnecessary decimal precision and potential rounding errors, such as representing 25 as 25.0. Option C (bool) is wrong because a boolean can only store True or False (1 or 0), which cannot represent the full range of possible ages. Option D (str) is wrong because while a string could store an age like '25', it would prevent arithmetic operations (e.g., age + 1) and is semantically incorrect for a numeric value.

131
MCQhard

Which of the following expressions will evaluate to True?

A.3 == 3.0
B.2 + 2 * 2 == 8
C.10 / 3 == 3
D.'a' > 'b'
AnswerA

Python's numeric equality compares values across int and float types, so 3 and 3.0 are equal despite differing types. The expression therefore evaluates to True, satisfying the question's requirement for an expression that yields True.

Why this answer

Python's `==` operator performs value equality comparison, and the integer `3` and the float `3.0` represent the same numeric value. Python automatically converts the integer to a float for comparison, so `3 == 3.0` evaluates to `True`.

Exam trap

Python Institute often tests the misconception that `==` requires identical data types, leading candidates to think `3 == 3.0` is `False`, or that operator precedence is left-to-right without considering multiplication before addition.

How to eliminate wrong answers

Option B is wrong because operator precedence in Python dictates that multiplication (`*`) is evaluated before addition (`+`), so `2 + 2 * 2` equals `2 + 4 = 6`, not `8`, making `6 == 8` evaluate to `False`. Option C is wrong because the division operator `/` in Python 3 always returns a float, and `10 / 3` yields `3.3333333333333335`, which is not equal to the integer `3`, so `10 / 3 == 3` is `False`. Option D is wrong because string comparison in Python uses lexicographic order based on ASCII/Unicode code points; the character `'a'` has a Unicode code point of 97, while `'b'` has 98, so `'a' > 'b'` evaluates to `False`.

132
MCQeasy

A junior developer writes: result = input("Enter first: ") + input("Enter second: ") and then prints result. When entering 5 and 3, the output is '53'. Which explanation is correct?

A.The code uses the wrong operator; it should use the & operator for addition.
B.The input() function automatically selects the correct type, but the + operator is overloaded to concatenate.
C.Python automatically converts strings to numbers when using +, but only for integers.
D.The input() function returns a string, so + performs string concatenation.
AnswerD

input() always yields a str, never a number, so the + operator concatenates the two strings rather than adding them. Entering 5 and 3 therefore produces '53', confirming that string concatenation, not arithmetic addition, is performed.

Why this answer

The `input()` function in Python always returns a string, regardless of what the user types. When the `+` operator is used with two strings, it performs concatenation, not arithmetic addition. Thus, entering 5 and 3 results in the strings '5' and '3' being joined to produce '53'.

Exam trap

The trap here is that candidates may assume `input()` returns a numeric type when numbers are entered, or that Python's dynamic typing will automatically convert strings to numbers for addition, leading them to choose option B or C instead of recognizing the default string behavior.

How to eliminate wrong answers

Option A is wrong because the `&` operator is a bitwise AND operator in Python, not an arithmetic addition operator; using it would produce a different, incorrect result. Option B is wrong because `input()` does not automatically select the correct type; it always returns a string, and the `+` operator is overloaded to concatenate strings, but that is not an automatic type selection. Option C is wrong because Python does not automatically convert strings to numbers when using `+`; attempting to add a string and a number with `+` raises a TypeError, and the statement about 'only for integers' is false.

133
MCQeasy

Which of the following variable names is valid in Python?

A.1st_value
B._count
C.my-var
D.class
AnswerB

A leading underscore is a legal identifier character in Python, so `_count` satisfies the naming rules. It is not a keyword, starts with a letter or underscore rather than a digit, and contains no illegal symbols, making it a valid variable name.

Why this answer

(_count) is valid because Python allows identifiers to start with an underscore, and it contains only letters and underscores. Python variable names must start with a letter or underscore, followed by letters, digits, or underscores, and cannot be a reserved keyword.

Exam trap

Python Institute often tests the misconception that underscores are not allowed or that hyphens are acceptable in variable names, leading candidates to reject _count or accept my-var.

How to eliminate wrong answers

Option A is wrong because variable names cannot start with a digit; '1st_value' begins with '1', which violates Python's identifier rules. Option C is wrong because hyphens are not allowed in Python identifiers; 'my-var' uses a hyphen, which Python interprets as a subtraction operator. Option D is wrong because 'class' is a reserved keyword in Python used to define classes, so it cannot be used as a variable name.

134
MCQeasy

A developer writes: x = 5; y = 2.0; z = x / y; print(type(z)). What is the output?

A.<class 'str'>
B.<class 'int'>
C.TypeError
D.<class 'float'>
AnswerD

Dividing an int by a float invokes Python's true division, which always yields a float regardless of whether the result is whole. Here 5 / 2.0 produces 2.5, so type(z) returns <class 'float'>. This satisfies the stem's mixed-type operand constraint, since int/float promotes to float.

Why this answer

In Python, the division operator (/) always returns a float, even when dividing two integers. Here, x is an integer (5) and y is a float (2.0), so the result is a float (2.5). The type() function returns <class 'float'>, making D correct.

Exam trap

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

How to eliminate wrong answers

Option A is wrong because the result of division is a number, not a string; type() would never return <class 'str'> for a numeric operation. Option B is wrong because Python 3's / operator always produces a float, even if the division is exact (e.g., 5/5 returns 1.0, not 1). Option C is wrong because there is no TypeError; Python allows division between int and float without issue, implicitly converting the int to a float for the operation.

135
MCQmedium

An accountant uses a Python script to calculate tax: tax = price * 0.08. For price=19.99, tax results in 1.5992. However, the output should be rounded to two decimal places. Which expression should replace the current one?

A.tax = round(price * 0.08)
B.tax = round(price * 0.08, 2)
C.tax = price * 0.08
D.tax = int(price * 0.08 * 100) / 100
AnswerB

The built-in round() function returns a float rounded to the specified number of decimal places, so round(price * 0.08, 2) yields 1.6 for price=19.99, satisfying the two-decimal constraint. Unlike formatting, it changes the numeric value itself, keeping tax usable in further arithmetic.

Why this answer

The built-in `round()` function with a second argument of 2 rounds the floating-point result of `price * 0.08` to exactly two decimal places, which matches the requirement for currency formatting. The other options either omit rounding, round to an integer, or use integer truncation that can produce incorrect results for negative numbers or edge cases.

Exam trap

Python Institute often tests the distinction between `round(x)` (rounds to integer) and `round(x, n)` (rounds to n decimal places), and the trap here is that candidates may choose Option A thinking it rounds to two decimals, or Option D thinking integer truncation is equivalent to rounding.

How to eliminate wrong answers

Option A is wrong because `round(price * 0.08)` with no second argument rounds to the nearest integer (0 decimal places), producing 2 instead of 1.60. Option C is wrong because it simply computes the raw floating-point value 1.5992 without any rounding, leaving extra decimal places. Option D is wrong because `int(price * 0.08 * 100) / 100` truncates toward zero, which for positive values works here but fails for negative numbers (e.g., -19.99 would give -1.59 instead of -1.60) and does not perform proper rounding.

136
MCQmedium

A student writes a program to classify a number: num = 7 result = num > 5 and num < 10 or num == 0 print(result) What is printed, and why?

A.True, because comparison operators are evaluated after logical operators.
B.False, because or is evaluated before and, making the expression False.
C.True, because and has higher precedence than or, so (num > 5 and num < 10) is evaluated first and is True.
D.False, because num == 0 is False and that makes the whole expression False.
AnswerC

Python gives and higher precedence than or, so the expression groups as (num > 5 and num < 10) or (num == 0). For num = 7, both comparisons in the first group are true, making the group True. Since True or anything is True, the whole expression evaluates to True. The precedence rule is the key to understanding the result.

Why this answer

Python's logical operators follow a precedence order with and binding tighter than or, and comparison operators binding tighter than both. The expression is grouped as (num > 5 and num < 10) or (num == 0). With num = 7, the first group is True, so the entire expression short-circuits to True, and that value is printed.

Exam trap

The trap here is misremembering operator precedence and assuming or is evaluated before and, which would flip the grouping and change the result.

137
MCQmedium

Refer to the exhibit. Which of the following shows the correct output?

A.3.3333333333333335 4 1
B.3.3333333333333335 3 1
C.3.0 3.0 1.0
D.3 3 0
AnswerB

Python's `/` operator always performs true division, yielding a float, so `10/3` produces 3.3333333333333335. The `//` operator performs floor division, truncating toward negative infinity, giving `10//3 == 3`. The `%` operator returns the remainder, so `10%3 == 1`. Printing each result on its own line matches the exhibit's expected output exactly.

Why this answer

The code `print(10/3)` performs floating-point division in Python 3, yielding `3.3333333333333335`; `print(10//3)` performs floor division, which truncates to the nearest integer less than or equal to the result, giving `3`; and `print(10%3)` computes the remainder of the division, which is `1`.

Exam trap

The trap here is that candidates often confuse the behavior of the `/` operator (which always returns a float in Python 3) with integer division from Python 2, or they misapply floor division and remainder operations, especially when dealing with positive integers.

How to eliminate wrong answers

Option A is wrong because it shows `4` for the floor division `10//3`, but floor division of 10 by 3 correctly yields `3`, not `4`. Option C is wrong because it shows `3.0` for both `10/3` and `10//3`, but `10/3` is a float with a fractional part, not exactly `3.0`, and `10//3` returns an integer `3`, not a float `3.0`. Option D is wrong because it shows `3` for `10/3`, but `10/3` returns a float `3.3333333333333335`, not an integer `3`, and it shows `0` for `10%3`, but the remainder of 10 divided by 3 is `1`, not `0`.

138
Multi-Selectmedium

Which TWO of the following are valid ways to create a variable with the integer value 100?

Select 2 answers
A.x = 0100
B.x = 100.0
C.x = int('100')
D.x = 100
E.x = '100'
AnswersC, D

Calling `int('100')` converts the string literal `'100'` into an integer object, which is then bound to the name `x`. This satisfies the stem's requirement for a variable holding the integer value 100, since `int()` parses the numeric characters and returns a genuine `int`, not a string.

Why this answer

Option C, x = int('100'), is correct because the int() constructor parses the string '100' and returns a genuine integer object with the value 100. Option D, x = 100, is correct because an unquoted numeric literal without a decimal point is directly an integer in Python, so x is bound to the int value 100. Option A, x = 0100, is not a valid way to get the integer 100 in Python 3, where a leading zero on a decimal literal is a syntax error (and in Python 2 it would denote octal 64, not 100).

Option B, x = 100.0, creates a float, not an integer, even though its numeric value equals 100. Option E, x = '100', creates a string containing the characters 1, 0, 0, not an integer.

Exam trap

Python Institute often tests the distinction between numeric literals (like `100`), string literals (like `'100'`), and type conversion functions (like `int()`), and the trap here is that candidates may mistakenly think a string with digits is automatically an integer or that a float literal like `100.0` is equivalent to an integer.

139
MCQeasy

What is the output from the interactive Python session?

A.3.333 1
B.3 1
C.1 3
D.3 0
AnswerB

Slicing `s[1:4]` extracts characters at indices 1, 2 and 3, giving `'ell'`, whose length is 3. The expression `s[0]` returns the first character `'h'`, not a count. Printing both yields `3 1`, satisfying the stem's request for the session's exact output.

Why this answer

The expression `10 // 3` performs integer (floor) division, which discards the fractional part and returns the integer quotient 3. The expression `10 % 3` returns the remainder of the division, which is 1. Therefore, the output is `3 1`, making option B correct.

Exam trap

Python Institute often tests the distinction between true division (`/`) and floor division (`//`), knowing that candidates may confuse the two or forget that integer division in Python 3 returns an integer, not a float.

How to eliminate wrong answers

Option A is wrong because it suggests `10 // 3` yields 3.333, which would be the result of true division (`10 / 3`) in Python 3, not floor division. Option C is wrong because it reverses the order of the results, outputting `1 3` instead of `3 1`. Option D is wrong because it claims the remainder is 0, but `10 % 3` correctly yields 1, not 0.

140
Drag & Dropmedium

Order the steps to debug a Python script using print statements.

Drag or tap steps into the slots.

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

Why this order

Debugging with print involves inserting prints, running, analyzing, and cleaning up.

141
MCQmedium

A developer writes the following code: a = 3; b = 2; c = a / b; d = a // b; e = a % b. What are the values of c, d, e?

A.c=1, d=1, e=1
B.c=1.5, d=1, e=0
C.c=1.5, d=1, e=1
D.c=1.5, d=1.5, e=0
AnswerC

True division a / b yields 1.5 as a float, floor division a // b yields 1, and modulo a % b yields 1. These three results match the stem's expected values c=1.5, d=1, e=1, correctly distinguishing the three division-related operators.

Why this answer

In Python, the / operator performs true division, yielding a float result (3/2 = 1.5). The // operator performs floor division, which for positive numbers truncates the decimal part, giving 1. The % operator returns the remainder of the division, which is 3 - (1 * 2) = 1.

Thus c=1.5, d=1, e=1.

Exam trap

The trap here is that candidates often confuse the / operator (true division) with the // operator (floor division) and mistakenly think // returns a float, or they miscalculate the remainder by assuming it is always the fractional part of the division.

How to eliminate wrong answers

Option A is wrong because it incorrectly uses integer division for c (c should be 1.5, not 1) and miscomputes e (e should be 1, not 1). Option B is wrong because it incorrectly states e=0; the remainder of 3 divided by 2 is 1, not 0. Option D is wrong because it incorrectly uses floor division for d (d should be 1, not 1.5) and misstates e=0.

142
MCQhard

Consider: x = True; y = False; z = x and not y or x. What is the value of z?

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

Python evaluates 'not' first, giving not False = True; 'and' then yields True and True = True; finally 'or' gives True or True = True. So z is True, satisfying the boolean expression's precedence order.

Why this answer

The expression `x and not y or x` is evaluated with operator precedence: `not` has the highest precedence, then `and`, then `or`. Given `x = True` and `y = False`, `not y` evaluates to `True`. Then `x and True` is `True and True`, which is `True`.

Finally, `True or x` (where `x` is `True`) short-circuits to `True`. Thus, `z` is `True`.

Exam trap

Python Institute often tests operator precedence by combining `and`, `or`, and `not` in a single expression, trapping candidates who incorrectly assume left-to-right evaluation without respecting that `not` binds first, then `and`, then `or`.

How to eliminate wrong answers

Option B is wrong because `None` is a special value representing the absence of a value, but the expression always yields a boolean result, never `None`. Option C is wrong because there is no syntax or runtime error; all variables are defined and the operators are valid for boolean values. Option D is wrong because the expression evaluates to `True`, not `False`; a common mistake is misordering precedence or incorrectly evaluating `not y` as `False`.

143
MCQmedium

What is the output of 'print(3 * "ab")'?

A.ab3
B.3ab
C.ababab
D.Error
AnswerC

String repetition by integer: the * operator repeats the string operand three times, concatenating "ab" with itself to yield "ababab". Python defines this for str multiplied by int, so no type error occurs and the six-character result prints directly.

Why this answer

In Python, the multiplication operator (*) when used with a string and an integer performs string repetition. The expression 3 * "ab" repeats the string "ab" three times, concatenating the copies into a single string "ababab". The print() function then outputs this resulting string to the console.

Exam trap

Python Institute often tests the distinction between the multiplication operator (*) for repetition and the plus operator (+) for concatenation, leading candidates to mistakenly think the integer is placed adjacent to the string rather than the string being repeated.

How to eliminate wrong answers

Option A is wrong because it suggests the integer 3 is appended to the string, which would require concatenation with +, not multiplication. Option B is wrong because it implies the integer is prepended, which is also a concatenation misconception. Option D is wrong because string repetition with an integer is a valid Python operation; it does not raise an error.

144
MCQeasy

Which function is used to read user input as a string?

A.read()
B.scan()
C.get()
D.input()
AnswerD

input() reads a line from standard input, strips the trailing newline, and returns it as a string. That matches the stem's requirement to read user input as a string, unlike functions that evaluate the entered text or read from files.

Why this answer

The `input()` function is the correct answer because it is the built-in Python function specifically designed to read a line of text from the user via standard input (stdin). It always returns the input as a string, regardless of whether the user types digits or other characters, making it the standard tool for console input in Python.

Exam trap

Python Institute often tests the distinction between `input()` and `raw_input()` (the Python 2 equivalent) or confuses candidates by listing file or dictionary methods like `read()` or `get()` as plausible input functions.

How to eliminate wrong answers

Option A is wrong because `read()` is a method of file objects (e.g., `file.read()`) used to read the contents of a file, not to read user input from the console. Option B is wrong because `scan()` is not a built-in Python function; it resembles the `scanf()` function from C, but Python has no such built-in. Option C is wrong because `get()` is a method of dictionary objects (e.g., `dict.get(key)`) used to retrieve a value for a given key, not for reading user input.

145
MCQhard

What is the result of 'bool(0) and bool(1)'?

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

Evaluating `bool(0)` yields `False`, and Python's `and` operator short-circuits: when the left operand is falsy, it returns that operand immediately without evaluating `bool(1)`. The expression therefore evaluates to `False`, satisfying the question's requirement for the result of this boolean conjunction.

Why this answer

The expression `bool(0) and bool(1)` evaluates to `False` because `bool(0)` converts the integer 0 to `False` (since 0 is falsy in Python), and `bool(1)` converts 1 to `True`. The `and` operator returns `True` only if both operands are truthy; here, `False and True` yields `False`.

Exam trap

Python Institute often tests the distinction between boolean values and their integer equivalents (0 and 1), tricking candidates into thinking the result is an integer like `0` or `1` instead of the boolean `False` or `True`.

How to eliminate wrong answers

Option B is wrong because `True` would only result if both operands were truthy, but `bool(0)` is `False`, so the `and` operation short-circuits and returns `False`. Option C is wrong because `1` is an integer, but the result of `and` with boolean operands is a boolean (`False`), not an integer. Option D is wrong because `0` is an integer, but the expression returns the boolean `False`, not the integer `0`, even though `False` is falsy.

146
MCQmedium

A programmer writes the following code to calculate the average of two numbers: a = 5 b = 2 avg = a / b print(avg) What is the output?

A.Error: division by zero
B.2
C.2.0
D.2.5
AnswerD

The division operator / in Python performs true division, returning a float result even when both operands are integers. Here, 5 / 2 equals 2.5. Therefore, the print statement outputs 2.5. This is the correct behavior for the / operator, which always returns a floating-point number.

Why this answer

In Python 3, the / operator performs true division and always returns a float. With a = 5 and b = 2, a / b evaluates to 2.5. The other options reflect common mistakes: confusing / with //, truncating the result, or assuming an error where none exists.

The correct output is 2.5.

Exam trap

The trap here is assuming that division of two integers yields an integer, as in some other programming languages, but Python's / operator always returns a float.

147
MCQmedium

A student is learning Python and writes a program to compute the area of a rectangle. The code: length = input("Enter length: ") width = input("Enter width: ") area = length * width print("Area:", area) When the user enters 5 and 3, the program crashes with a TypeError: can't multiply sequence by non-int of type 'str'. The student is puzzled because they thought input returns numbers. What is the correct explanation and fix?

A.The input function returns a string, so use int(input("Enter length: ")) and int(input("Enter width: ")).
B.The error is due to variable names length and width conflicting with built-in functions; rename them to l and w.
C.The print function cannot handle the multiplication result because area is a string; convert area to int.
D.The error can be fixed by using the eval function to directly evaluate the input as Python code.
AnswerA

`input()` always returns a `str`, so `length` and `width` hold `"5"` and `"3"`. Multiplying two strings is invalid, hence the `TypeError`. Wrapping each call in `int()` converts the text to integers, satisfying the arithmetic the area calculation requires.

Why this answer

The `input()` function in Python always returns a string, even if the user types a number. When you try to multiply two strings (or a string by a string), Python raises a `TypeError` because it cannot multiply sequences by non-integers. The fix is to explicitly convert the input to an integer using `int()` before performing arithmetic.

Exam trap

Python Institute often tests the misconception that `input()` returns a number when the user types digits, leading candidates to forget explicit type conversion, and they may incorrectly choose options that suggest renaming variables or using `eval()`.

How to eliminate wrong answers

Option B is wrong because `length` and `width` are not built-in function names; the error is purely a type mismatch, not a naming conflict. Option C is wrong because the error occurs during the multiplication, not in `print()`; converting `area` to `int` after the multiplication does not fix the root cause (the inputs are still strings). Option D is wrong because using `eval()` is dangerous and unnecessary; it evaluates arbitrary code and is not a recommended or safe way to convert input to numbers.

148
MCQmedium

A program uses 'x = 3.14' and 'y = int(x)'. What is the value of y?

A.4
B.3.14
C.Error
D.3
AnswerD

Calling `int()` on a float truncates toward zero, discarding the fractional part rather than rounding to the nearest integer. For `x = 3.14`, the decimal `.14` is dropped, leaving exactly `3`. This satisfies the stem's requirement that `y` holds the integer conversion result of the float value.

Why this answer

The int() function in Python truncates the decimal part of a float, converting 3.14 to the integer 3. It does not round to the nearest whole number.

Exam trap

The trap here is that candidates often confuse int() with round() and assume it performs rounding to the nearest integer, leading them to choose option A (4) instead of the correct truncation result (3).

How to eliminate wrong answers

Option A is wrong because int() does not round up; it truncates toward zero, so 3.14 becomes 3, not 4. Option B is wrong because int() returns an integer, not a float; the value 3.14 would remain a float only if no conversion occurred. Option C is wrong because converting a float to an integer using int() is a valid operation in Python and does not raise an error.

149
MCQhard

Given the code: x = 10; y = 3.0; z = x / y; print(type(z)). What is the output?

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

Dividing an integer by a float in Python always yields a float, because the true division operator promotes the result to the wider numeric type. Here 10 / 3.0 evaluates to 3.333..., so type(z) returns <class 'float'>, satisfying the stem's request for the printed type.

Why this answer

In Python, when you divide an integer by a float using the / operator, the result is always a float. Here, x is an integer (10) and y is a float (3.0), so z = 10 / 3.0 evaluates to 3.3333333333333335, which is of type float. The print(type(z)) outputs <class 'float'>, making option B correct.

Exam trap

Python Institute often tests the distinction between / (true division) and // (floor division), trapping candidates who mistakenly think dividing an integer by a float returns an integer or that the result type depends on exact divisibility.

How to eliminate wrong answers

Option A is wrong because the result of division is a numeric type, not a string; <class 'str'> would only appear if the variable were explicitly assigned a string value. Option C is wrong because a complex number requires an imaginary part (e.g., 3+2j), and dividing an int by a float never produces a complex type. Option D is wrong because the / operator always returns a float in Python 3, even if the division is exact (e.g., 10 / 2.0 returns 5.0 as a float); integer division requires the // operator.

150
MCQmedium

A Python developer writes the following code to concatenate two strings: first = 'Hello' second = 'World' result = first + ' ' + second print(result) What is the output?

A.Hello World
B.HelloWorld
C.'Hello' 'World'
D.Error: cannot concatenate str and int
AnswerA

The + operator concatenates strings. The expression first + ' ' + second combines 'Hello', a space, and 'World', resulting in 'Hello World'. The space is explicitly added as a string literal. Therefore, the print statement outputs 'Hello World' with a space between the words. This is the correct result.

Why this answer

The + operator concatenates strings when both operands are strings. Here, first is 'Hello', then a space string ' ', then second is 'World'. The result is 'Hello World'.

The other options either omit the space, include quotes, or predict an error that does not occur because all operands are strings.

Exam trap

The trap here is forgetting that the space is explicitly included as a separate string, leading to the assumption that the output would be 'HelloWorld' without a space.

← PreviousPage 2 of 3 · 181 questions totalNext →

Ready to test yourself?

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