Courseiva

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

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

151
MCQmedium

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

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

String repetition: 'ab' * 3 = 'ababab'.

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.

152
MCQeasy

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

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

input() always returns a string.

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.

153
MCQhard

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

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

False and True = False.

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.

154
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

Conversion to int allows multiplication.

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.

155
Multi-Selectmedium

Which TWO of the following are valid Python variable names?

Select 2 answers
A.var name
B.1var
C.var2
D._var
E.my-var
AnswersC, D

Letters and digits allowed.

Why this answer

'var2' starts with a letter and contains only alphanumeric characters and underscores, which satisfies Python's variable naming rules. Python variable names must begin with a letter or underscore, and can be followed by letters, digits, or underscores.

Exam trap

Python Institute often tests the misconception that hyphens or spaces are acceptable separators in variable names, similar to other languages, but Python strictly requires underscores and no whitespace.

156
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

int() truncates the float to the integer part.

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.

157
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

Correct: division always returns float.

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.

158
MCQhard

What is the most appropriate fix for the error shown in the exhibit?

A.Either A or C are valid fixes.
B.Use the comma syntax: print("The answer is", 42).
C.Use int("The answer is ") to convert the string to an integer.
D.Use str(42) to convert the integer to a string.
AnswerD

Correct. Converting the integer to a string using str() directly resolves the TypeError and is the standard approach for concatenating strings with integers.

Why this answer

The error is a TypeError caused by attempting to concatenate a string with an integer using the + operator. The most direct fix is to convert the integer to a string with str(), as shown in option D. While option B (using comma syntax) also resolves the error because print() can accept multiple arguments, the question asks for the 'most appropriate' fix, which typically refers to the explicit type conversion.

Option A is incorrect because it claims that option C is a valid fix, which it is not (int() cannot convert a non-numeric string). Option C is invalid. Therefore, option D is the correct answer.

Exam trap

Candidates may think that only the comma syntax (option B) or only str() (option D) is correct. However, both are valid, but the question asks for the most appropriate fix. The trap is to recognize that str() is the standard way to concatenate different types.

How to eliminate wrong answers

Option B is wrong because it is actually a valid fix, not a wrong option — the comma syntax correctly prints the string and integer without concatenation. Option C is wrong because int("The answer is ") will raise a ValueError, as the string contains non-numeric characters and cannot be converted to an integer. Option D is wrong because it is also a valid fix — str(42) converts the integer to a string, enabling concatenation with the other string — so it is not incorrect.

159
MCQeasy

What is the result of 17 % 5 in Python?

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

Correct remainder of 17/5

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

160
MCQmedium

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

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

Correct: f-string with .2f formats to two decimals.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

161
Multi-Selecthard

Which THREE of the following are arithmetic operators in Python?

Select 3 answers
A.//
B.@
C.&
D.+
E.**
AnswersA, D, E

Floor division operator.

Why this answer

The double slash `//` is Python's floor division operator, which performs division and rounds down to the nearest integer. It is one of the standard arithmetic operators in Python, alongside `+`, `-`, `*`, `/`, `%`, and `**`.

Exam trap

The PCEP exam often tests the distinction between arithmetic operators and bitwise or special-purpose operators, so candidates may mistakenly select `&` or `@` because they resemble arithmetic symbols, but they are not part of the core arithmetic operator set.

162
MCQhard

A user enters 'Alice' for name and '30' for age. What is the output?

A.Alice is 30 years old.
B.Alice is 30 years old
C.Error: cannot concatenate str
D.Name: Alice, Age: 30
AnswerA

Correct concatenation.

Why this answer

The code `print(name + ' is ' + age + ' years old.')` concatenates the string `'Alice '`, the string `' is '`, the string `'30'`, and the string `' years old.'` using the `+` operator. In Python, the `+` operator performs string concatenation when both operands are strings, and since `input()` always returns a string, both `name` and `age` are strings, so no type error occurs. The output is exactly `Alice is 30 years old.` including the period at the end.

Exam trap

The trap here is that candidates mistakenly think `input()` returns an integer for numeric input, leading them to expect a `TypeError` when concatenating a string with an integer, but in Python `input()` always returns a string, so no error occurs.

How to eliminate wrong answers

Option B is wrong because it omits the period at the end of the sentence, but the code explicitly includes `' years old.'` with a period, so the output must include the period. Option C is wrong because it suggests a `TypeError` about concatenating `str` and `int`, but `age` is a string (from `input()`), not an integer, so no type mismatch occurs. Option D is wrong because the code does not use an f-string or `print` with commas; it uses explicit `+` concatenation, so the output format is `Alice is 30 years old.` not `Name: Alice, Age: 30`.

163
MCQeasy

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

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

2 ** 3 = 2^3 = 8.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

164
MCQmedium

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

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

No type restrictions.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

165
Multi-Selectmedium

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

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

3 squared equals 9.

Why this answer

The exponentiation operator `**` computes 3 raised to the power of 2, which equals 9, and the `==` operator checks equality, so `3 ** 2 == 9` evaluates to `True`.

Exam trap

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

166
MCQeasy

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

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

Correct. 5 + 3.0 = 8.0, a float.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

167
MCQmedium

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

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

Correct. The string 'Hello, ' is concatenated with 'Alice'.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

168
MCQeasy

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

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

Product of int and float is float.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

169
Multi-Selectmedium

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

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

Correct. The sep parameter sets a custom separator between arguments.

Why this answer

Options B, C, D, and E are all correct uses of the print() function in Python 3. Option B demonstrates the use of the sep parameter to set a custom separator between arguments. Option C shows printing two string arguments separated by the default space.

Option D shows printing a single string. Option E shows printing a string and an integer, which is perfectly valid; the print() function automatically converts non-string arguments to strings. Option A is incorrect because it uses the Python 2 print statement syntax (missing parentheses) and will raise a SyntaxError in Python 3.

Exam trap

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

170
Drag & Dropmedium

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

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

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

Why this order

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

171
Multi-Selectmedium

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

Select 2 answers
A.for
B.2nd_value
C.value_2
D.val-ue
E._value
AnswersC, E

Valid: underscore and digits allowed (not at start)

Why this answer

`value_2` starts with a letter and contains only letters, digits, and underscores, which satisfies Python's identifier rules. Python variable names must begin with a letter or underscore, and can include letters, digits, and underscores; `value_2` meets all these criteria.

Exam trap

Python Institute often tests the distinction between hyphens and underscores, as candidates mistakenly think hyphens are allowed in variable names because they are common in other contexts like file names or URLs.

172
MCQeasy

A developer writes code to compute the average of two numbers entered by the user: x = input('Enter first number: '); y = input('Enter second number: '); avg = (x + y) / 2. The program produces an error. What is the best practice to fix the code?

A.Convert the result to int after the operation: avg = int((x + y) / 2)
B.Use int() on the input() values: x = int(input(...)); y = int(input(...))
C.Use type casting in the division: avg = (float(x) + float(y)) / 2
D.Convert x and y to float before the operation: x = float(input(...)); y = float(input(...))
AnswerD

This ensures the addition and division work on numeric values.

Why this answer

The `input()` function in Python always returns a string. When you use the `+` operator on two strings, it concatenates them (e.g., '5' + '3' = '53'), not adds them numerically. Dividing a concatenated string by 2 raises a TypeError.

The best practice is to convert both inputs to `float` immediately after receiving them, ensuring the subsequent arithmetic works correctly.

Exam trap

Python Institute often tests the misconception that `input()` returns a numeric type, leading candidates to pick Option B (using `int`) or Option C (casting inside the expression), but the trap is that string concatenation happens before any conversion, so the error occurs at the `+` operator, not at the division.

How to eliminate wrong answers

Option A is wrong because it attempts to convert the result after the operation, but the error occurs earlier: `x + y` concatenates strings, and dividing a string by 2 raises a TypeError, so `int()` never executes. Option B is wrong because converting to `int` truncates any decimal input (e.g., 5.5 becomes 5), losing precision; for an average, `float` is more appropriate. Option C is wrong because while it converts inside the expression, it still concatenates strings first (`x + y` before `float()` is applied), causing the same TypeError; the conversion must happen before the addition.

173
MCQmedium

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

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

float() converts the string to a number.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

174
MCQhard

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

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

Correct; see calculation.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

175
MCQeasy

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

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

Correct: operator precedence gives 10+20+10.0 = 40.0.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

176
MCQhard

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

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

Correct: accesses first rule's action value.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

177
Matchingmedium

Match each Python data structure to its characteristic.

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

Concepts
Matches

Ordered, immutable sequence of items

Unordered collection of unique items

Mapping of key-value pairs

Ordered, mutable sequence of items

Immutable sequence of characters

Why these pairings

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

178
MCQmedium

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

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

Correct, logical operators return bool.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

179
MCQmedium

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

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

Converts integer 5 to string and concatenates.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

180
MCQeasy

Refer to the exhibit. What is the output?

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

Correct.

Why this answer

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

Thus the output is '3 1'.

Exam trap

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

How to eliminate wrong answers

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

181
MCQhard

A company runs a script that processes user input temperatures. The script expects integers but sometimes users enter floats. The current code is: temp = int(input("Enter temperature: ")). When a user enters "36.5", the script crashes with a ValueError. The developer needs to modify the script to handle both integer and float inputs gracefully, converting the input to an integer (by truncation) for processing. Which of the following is the best course of action?

A.Use temp = int(float(input()))
B.Use input with a regex check to ensure only integers are entered.
C.Use a try-except block to catch ValueError and ask the user to re-enter.
D.Use float(input()) and do not convert to int, store as float.
AnswerA

Correct; float() accepts both int and float strings, int() truncates.

Why this answer

It first converts the input string to a float (handling both integer and float strings), then truncates the float to an integer via int(). This gracefully processes inputs like '36.5' without crashing, meeting the requirement to truncate rather than round.

Exam trap

Python Institute often tests the misconception that int() can directly parse a string containing a decimal point, leading candidates to overlook the need for an intermediate float conversion.

How to eliminate wrong answers

Option B is wrong because using a regex to reject non-integer inputs would still crash on '36.5' (since it's not an integer), failing to handle floats gracefully. Option C is wrong because a try-except block that catches ValueError and asks for re-entry does not convert the float input to an integer by truncation; it rejects valid float input instead of processing it. Option D is wrong because storing the value as a float does not convert it to an integer as required; the script expects an integer for processing.

182
MCQmedium

What is the output of the code in the exhibit?

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

Floor division of 10 by 3 yields 3.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

183
MCQmedium

Which of the following is a valid Python variable name?

A.my-var
B.for
C._data2
D.2nd_value
AnswerC

Starts with underscore, valid.

Why this answer

(_data2) is correct because Python variable names must start with a letter or an underscore, and can contain letters, digits, and underscores. _data2 begins with an underscore followed by valid characters, making it a legal identifier.

Exam trap

Python Institute often tests the rule that hyphens are invalid in variable names (confusing them with underscores) and that keywords like 'for' cannot be used as identifiers, leading candidates to mistakenly choose options that look familiar from other languages.

How to eliminate wrong answers

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

184
MCQmedium

A company needs to process user input that must be a whole number between 1 and 100. Which code snippet correctly validates and converts the input?

A.num = int(input("Enter: ")); if 1 <= num <= 100: ...
B.num = int(input("Enter: ")); if num in range(1,101): ...
C.num = input("Enter: "); if num.isdigit() and 1 <= int(num) <= 100: ...
D.All of the above are correct.
AnswerC

Checks if input is digit first, then converts safely.

Why this answer

It first checks that the input string consists only of digits using `isdigit()`, which prevents `ValueError` from non-numeric input, and then safely converts to `int` only after validation. This ensures the input is a whole number between 1 and 100 before any further processing.

Exam trap

Python Institute often tests the misconception that `int(input(...))` is safe as long as you later check the value, but the trap is that the conversion itself can raise a `ValueError` before any validation occurs, making Options A and B incorrect.

How to eliminate wrong answers

Option A is wrong because calling `int(input(...))` directly will raise a `ValueError` if the user enters non-numeric input (e.g., letters or symbols), crashing the program before any validation occurs. Option B is wrong for the same reason — it also calls `int()` on raw input without checking, leading to a `ValueError` on invalid input. Option D is wrong because not all of the above are correct; only Option C handles input validation safely.

185
MCQmedium

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

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

ZeroDivisionError is caught.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

186
MCQmedium

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

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

Correct: Python's tuple unpacking swaps values.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

187
MCQmedium

A developer is writing a program to calculate the average of three test scores. The current code reads scores as integers: a=int(input()); b=int(input()); c=int(input()); avg = (a+b+c)/3; print(avg). For scores 7, 8, and 9, the output is 8.0, but the requirement is to print the integer average (8), rounded to the nearest whole number. Which modification should the developer make to meet the requirement?

A.Use integer division after multiplying sum
B.Use integer division: avg = (a+b+c)//3
C.Use int(avg): print(int(avg))
D.Use round(avg): print(round(avg))
AnswerD

Correct; round rounds to nearest integer.

Why this answer

The requirement is to print the integer average rounded to the nearest whole number. Using `round(avg)` correctly rounds the floating-point result (8.0) to the nearest integer (8) and prints it as an integer, satisfying the requirement. Option D is correct because `round()` performs standard rounding (banker's rounding in Python 3) and returns an integer when called with a single argument.

Exam trap

Python Institute often tests the distinction between truncation (`int()`) and rounding (`round()`), leading candidates to mistakenly choose `int(avg)` because they think converting to int removes decimals, but it truncates rather than rounds.

How to eliminate wrong answers

Option A is wrong because multiplying the sum and then using integer division (e.g., `(a+b+c)*1//3`) does not round to the nearest whole number; it truncates toward negative infinity, which would give 8 for 7,8,9 but fails for cases like 7,8,8 (sum 23, average 7.666, truncates to 7 instead of rounding to 8). Option B is wrong because `(a+b+c)//3` performs floor division, which truncates the decimal part (e.g., 24//3 = 8 for 7,8,9, but for 7,8,8 it gives 7 instead of the rounded 8). Option C is wrong because `int(avg)` truncates the decimal part (e.g., 8.999 becomes 8, not rounded to 9), which does not meet the 'rounded to the nearest whole number' requirement.

188
MCQeasy

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

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

Invalid; names cannot start with a digit.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

189
MCQmedium

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

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

Correct: 'Hello' and 'World' separated by '-', ending with '!' and newline

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

← PreviousPage 3 of 3 · 190 questions total

Ready to test yourself?

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