CCNA Computer Programming and Python Fundamentals Questions

72 of 142 questions · Page 1/2 · Computer Programming and Python Fundamentals · Answers revealed

1
Multi-Selecteasy

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

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

Underscore at start is allowed.

Why this answer

A and D are valid. B starts with a digit, C contains a hyphen, and E is a reserved keyword.

2
MCQhard

You are a junior developer at a logistics company. Your team maintains a Python script that processes daily shipment data from a CSV file. The script reads the file, computes total weight per shipment, and writes results to a new CSV. Recently, the script started crashing sporadically with a 'ValueError: invalid literal for int() with base 10: 'NULL''. The CSV file sometimes contains the string 'NULL' in the weight column for missing values. The current code reads the weight column as: weight = int(row['weight']). Your team lead wants a robust fix that handles missing data gracefully without crashing, and also logs the line number for any problematic rows for later review. Which of the following approaches best meets these requirements?

A.Use the string method .isdigit(): if row['weight'].isdigit(): weight = int(row['weight']); else: weight = 0; no logging.
B.Read the entire file into a list, then use a list comprehension to convert weights: weights = [int(w) if w != 'NULL' else 0 for w in rows] without logging.
C.Wrap the int conversion in a try-except block: try: weight = int(row['weight']); except ValueError: weight = 0; log the line number using a counter variable.
D.Add a check: if row['weight'] != 'NULL': weight = int(row['weight']); else: weight = 0; and log a warning. Do not use try-except.
AnswerC

Catches all invalid literals, logs line number, and continues.

Why this answer

Option B is correct: it uses a try-except to catch ValueError, logs the line number (using a counter), sets weight to 0, and continues processing. Option A logs but still crashes because the exception is not caught. Option C catches error but doesn't log the line number.

Option D is overcomplicated and doesn't log line number explicitly.

3
MCQeasy

Refer to the exhibit. What is the output?

A.2
B.16
C.4
D.8
AnswerB

Correct: 4 squared is 16.

Why this answer

The function square returns the square of its argument. 4**2 = 16. Option B is correct.

4
MCQmedium

A program uses a for loop to double each element in a list: numbers = [1, 2, 3, 4, 5]; for num in numbers: num = num * 2. After execution, numbers remains unchanged. Why?

A.Reassigning num does not modify the original list element; you need to modify via index.
B.The assignment creates a new list, leaving the original unchanged.
C.Lists are immutable; their elements cannot be changed.
D.The variable num is a copy of the list element.
AnswerA

Correct: num = num * 2 just rebinds num, not the list.

Why this answer

The loop variable num is a reference to the element in the list, but reassigning num merely reassigns the variable, not the list element. Option B is correct.

5
Drag & Dropmedium

Arrange the steps to read data from a text file in Python.

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

Steps
Order

Why this order

File reading involves opening, reading, processing, and closing the file.

6
MCQmedium

What does the following code print? text = 'Hello World'; print(text.replace('o', '0').upper())

A.hell0 w0rld
B.HELLO WORLD
C.HELL0 W0RLD
D.Hell0 W0rld
AnswerC

String methods are applied left to right: replace then upper.

Why this answer

Option A is correct: replace 'o' with '0' gives 'Hell0 W0rld', then .upper() converts to uppercase: 'HELL0 W0RLD'. Option B does not replace o. Option C does not uppercase.

Option D is lowercase with replace.

7
MCQmedium

You are a developer in a company that runs a Python script daily to generate reports. The script uses the os module to list files in a directory and process each. Recently, after a server migration, the script fails with 'PermissionError: [Errno 13] Permission denied'. The script runs under a service account that has read/write access to most folders, but the migration changed the permissions on certain subdirectories. The error is intermittent, occurring only for some files. You need to fix the script to continue processing other files even if one fails. Which approach should you take?

A.Use a try-except block inside the loop to catch PermissionError for each file and continue.
B.Wrap the entire processing loop in a try-except that catches all exceptions and passes silently.
C.Before processing each file, use os.access() to check permissions and skip if not accessible.
D.Ask the server administrator to grant full permissions to the service account on all directories.
AnswerA

Selective exception handling allows graceful continuation.

Why this answer

Option C is correct: embedding the file processing inside a try block and catching PermissionError specifically allows the loop to continue. Option A is wrong because checking permissions manually across all directories is error-prone and platform-dependent. Option B is wrong because ignoring all errors without distinction could mask other critical issues.

Option D is wrong because running the script as a different user may solve all permission issues but is an overreaction and may not be allowed.

8
MCQmedium

Refer to the exhibit. What is the output when the following code is executed: print(calculate_discount(100, 0.6))

A.Discount too high
B.40.0
C.100
D.Discount too high followed by 100
AnswerD

The print statement outputs the message, then the function returns 100 which is printed.

Why this answer

The discount 0.6 > 0.5, so it prints 'Discount too high' and returns price (100), then the print outputs 100.

9
MCQeasy

Refer to the exhibit. What is the most likely cause of this error?

A.Variable x is a string
B.Variable x is used before assignment
C.Variable x is an integer
D.Variable x is misspelled
AnswerB

This is the typical cause of a NameError in Python.

Why this answer

A NameError occurs when a variable is referenced before it has been assigned a value. The variable 'x' has not been defined.

10
Multi-Selecthard

Which three of the following are true about Python lists? (Choose three.)

Select 3 answers
A.Lists can contain elements of different data types.
B.Lists can be used as dictionary keys.
C.Lists are indexed starting from 1.
D.Lists are immutable.
E.The len() function returns the number of elements.
AnswersA, B, E

True; lists are heterogeneous.

Why this answer

Lists are mutable, can hold mixed data types, support slicing, and len() returns the number of elements. They cannot be used as dictionary keys because they are unhashable.

11
MCQmedium

What does the following code output? for i in range(3): if i == 1: continue; print(i, end=' ')

A.1
B.0 2
C.0 1 2
D.0
AnswerB

i=1 is skipped.

Why this answer

Option B is correct: range(3) gives 0,1,2. When i==1, continue skips the print, so prints 0 and 2. Option A prints all.

Option C prints only 1. Option D prints only 0.

12
MCQhard

Consider code: def outer(): x = 1 def inner(): nonlocal x x = 2 inner() print(x) outer() What is printed?

A.2
B.1
C.Error
D.None
AnswerA

nonlocal allows modification.

Why this answer

Option D is correct: inner modifies x via nonlocal, so x becomes 2. Option A would be if inner had local x. Option B if x = 2 not executed.

Option C if inner didn't affect outer.

13
MCQmedium

A junior developer is writing a script to process a list of user IDs: ids = [101, 102, 103, 104]. The goal is to create a new list where each ID is increased by 10, without modifying the original list. The developer writes: new_ids = ids.append(10). However, the output shows None. The developer needs to correctly create the new list. Which code should the developer use to achieve this?

A.new_ids = [id + 10 for id in ids]
B.for i in range(len(ids)): ids[i] += 10; new_ids = ids
C.new_ids = ids + 10
D.new_ids = map(lambda x: x+10, ids)
AnswerA

List comprehension creates a new list with increments, original unchanged.

Why this answer

Option A uses a list comprehension to create a new list with each element incremented, leaving the original unchanged. Option B tries to add a list and integer, which raises TypeError. Option C returns a map object, not a list.

Option D modifies the original list in place, which is not desired.

14
MCQhard

A company is developing a data processing pipeline that must handle large datasets efficiently. They notice that using a list comprehension to filter data is slower than expected. Which alternative approach would likely improve performance?

A.Using the map() function
B.Using a for loop with append
C.Using a generator expression
D.Using a lambda function
AnswerC

Generators yield items one by one and avoid storing the entire list, reducing memory and often improving speed.

Why this answer

Generator expressions are memory efficient and can be faster for large datasets because they produce items lazily without building the entire list.

15
MCQeasy

A developer writes code to calculate the area of a rectangle and prints it. The code is: length = 10 width = 5 area = length * width print('The area is', area) If the width is accidentally assigned a string '5', what error will occur?

A.ValueError
B.SyntaxError
C.TypeError
D.NameError
AnswerC

Multiplying int and str causes TypeError.

Why this answer

Option A is correct because multiplying an integer by a string results in a TypeError. Option B is wrong because NameError occurs only when a variable is not defined. Option C is wrong because SyntaxError occurs for invalid syntax.

Option D is wrong because ValueError occurs for invalid value conversion.

16
MCQeasy

A programmer wants to iterate over a list of strings and print each string in uppercase. Which of the following code snippets will accomplish this?

A.for item in my_list: print(item.upper)
B.for item in my_list: item.upper() print(item)
C.for i in my_list: print(my_list[i].upper())
D.for item in my_list: print(item.upper())
AnswerD

Correct iteration and method call.

Why this answer

Option D is correct because it correctly calls the `upper()` method on each string `item` in the list `my_list` and prints the result. The `upper()` method returns a new string with all characters converted to uppercase, and the `print()` function outputs that value to the console.

Exam trap

The trap here is that candidates often forget to include parentheses when calling a method (e.g., `item.upper` vs `item.upper()`), or they mistakenly think `upper()` modifies the string in place, leading them to print the original variable instead of the returned value.

How to eliminate wrong answers

Option A is wrong because `item.upper` without parentheses does not call the method; it merely references the method object, so nothing is printed. Option B is wrong because `item.upper()` returns a new string but does not modify `item` in place, and the subsequent `print(item)` prints the original lowercase string, not the uppercase version. Option C is wrong because `my_list[i]` attempts to use an integer index `i` as a list index, but `i` is a string from the list, not an integer; this will raise a `TypeError`.

17
MCQeasy

A beginner writes: x = 10; y = 3; print(x // y). What is the output?

A.3
B.1
C.3.0
D.3.333
AnswerA

Floor division returns the integer part, 3.

Why this answer

The // operator performs floor division, returning the integer quotient. 10 // 3 equals 3.

18
MCQhard

You are a developer in a data science team using Python for analysis. A colleague wrote a script that downloads a CSV file from a URL, parses it using csv.DictReader, and prints summary statistics. The script works on his machine but fails on yours with 'UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 in position 100: invalid continuation byte'. The CSV file contains text in multiple languages, including French accents. The error occurs in the csv.DictReader call. You need to fix the script to work on any machine. Which approach is best?

A.Read the file in binary mode and decode with 'utf-8' ignoring errors.
B.Open the file with encoding='utf-8-sig' to handle BOM.
C.Use the errors='replace' parameter in the open() call.
D.Open the file with encoding='latin-1' (or 'cp1252') to handle a wider range of bytes.
AnswerD

latin-1 can decode any byte, preserving data, though may not be accurate for all characters.

Why this answer

Option C is correct: specifying encoding='latin-1' or another common encoding like 'ISO-8859-1' can handle the byte, but it's better to detect the encoding. However, among the options, opening with a different encoding (e.g., 'utf-8-sig' or 'latin-1') is practical. Option A is wrong because 'utf-8-sig' handles BOM but not arbitrary invalid bytes.

Option B is wrong because binary mode would require manual decoding. Option D is wrong because suppressing the error with 'replace' changes characters silently, potentially corrupting data. The best practice is to use the correct encoding (e.g., 'utf-8' if the file is actually UTF-8, but if it's not, using 'latin-1' is a fallback).

However, the most robust is to read with binary mode and then decode with error handling, but among the given, opening with a more permissive encoding like 'latin-1' is a reasonable fix if the data is from a Windows system. Option C is the closest.

19
Multi-Selecthard

Which THREE of the following are correct ways to create a list containing the numbers 1, 2, 3? (Choose three.)

Select 3 answers
A.[x for x in range(1,4)]
B.(1, 2, 3)
C.list((1, 2, 3))
D.[1, 2, 3]
E.{1, 2, 3}
AnswersA, C, D

List comprehension.

Why this answer

Options A, B, and D are correct. Option A uses square brackets. Option B uses the list() constructor with a tuple.

Option D uses a generator expression converted to list. Option C is wrong because (1,2,3) is a tuple, not a list. Option E is wrong because it creates a set.

20
MCQmedium

A developer is writing a script to process user input. The script should repeatedly ask for a number until a valid integer is entered. Which loop structure is most appropriate?

A.while loop with a condition
B.for loop
C.do-while loop
D.Recursion
AnswerA

A while loop can run until a condition is met, ideal for input validation.

Why this answer

A while loop with a condition that checks if the input is valid is the standard approach for input validation.

21
MCQhard

A junior developer is working on a script that processes user data. The script reads a CSV file into a list of dictionaries. Each dictionary represents a user with keys 'name', 'age', and 'email'. The developer needs to filter out users under 18 and store their names in a list. The current code is: users = [{'name': 'Alice', 'age': 17, 'email': 'alice@example.com'}, {'name': 'Bob', 'age': 22, 'email': 'bob@example.com'}] minors = [] for user in users: if user['age'] < 18: minors.append(user['name']) print(minors) The code works, but the senior developer says it is not idiomatic and suggests a more concise solution. Which of the following approaches is the best replacement?

A.minors = [] for i in range(len(users)): if users[i]['age'] < 18: minors.append(users[i]['name'])
B.minors = [user for user in users if user['age'] < 18]
C.minors = list(map(lambda u: u['name'], filter(lambda u: u['age'] < 18, users)))
D.minors = [user['name'] for user in users if user['age'] < 18]
AnswerD

Concise and idiomatic list comprehension.

Why this answer

Option D is correct because it uses a list comprehension to directly extract the 'name' field from each user dictionary where the age is under 18, making the code concise and Pythonic. The original code works but is verbose; list comprehensions are the idiomatic Python approach for transforming and filtering iterables in a single readable line.

Exam trap

Python Institute often tests the distinction between filtering entire objects versus extracting specific fields, so candidates may pick Option B (which filters dictionaries) instead of Option D (which extracts the 'name' field), missing the requirement to store only names.

How to eliminate wrong answers

Option A is wrong because it uses an index-based loop with range(len(users)), which is less readable and not Pythonic; it also does not extract the 'name' field, appending the entire dictionary instead. Option B is wrong because it creates a list of entire user dictionaries (not just names), failing to meet the requirement of storing only names. Option C is wrong because it uses map() and filter() with lambda functions, which is unnecessarily complex and less readable than a list comprehension, though it would produce the correct result; it is not the best replacement for simplicity and Pythonic style.

22
Multi-Selecthard

Which THREE of the following statements about Python data types are correct? (Choose three.)

Select 3 answers
A.Strings are mutable.
B.Sets are immutable.
C.Tuples are immutable.
D.Lists are mutable.
E.Dictionaries are mutable.
AnswersC, D, E

Tuples cannot be changed after creation.

Why this answer

Option C is correct because tuples in Python are immutable, meaning once created, their elements cannot be changed, added, or removed. This immutability makes tuples hashable and usable as dictionary keys, unlike lists.

Exam trap

The trap here is that candidates often confuse the immutability of strings and tuples with the mutability of lists and dictionaries, or incorrectly assume sets are immutable because their elements must be immutable.

23
MCQmedium

A developer needs to iterate over the indices of a list named 'items' and print each index and its corresponding value. Which loop construct is most appropriate?

A.for val in items: print(items.index(val), val)
B.for i in range(len(items)): print(i, items[i])
C.for i, val in enumerate(items): print(i, val)
D.for i in items: print(i)
AnswerC

Pythonic and direct.

Why this answer

Option C is correct because `enumerate(items)` returns an iterator that yields pairs of (index, value) directly, making it the most Pythonic and efficient way to iterate over both indices and values of a list. It avoids the overhead of calling `items.index(val)` (which is O(n) per iteration) or manually managing `range(len(items))`.

Exam trap

Python Institute often tests the distinction between iterating over values (`for val in items`) versus indices (`for i in range(len(items))`) versus both (`enumerate`), and the trap here is that candidates may choose Option B because it works, missing that `enumerate` is the idiomatic and recommended construct for this exact use case.

How to eliminate wrong answers

Option A is wrong because `items.index(val)` performs a linear search for each element, which is inefficient (O(n²) overall) and will return the first occurrence of the value, not necessarily the current index if duplicates exist. Option B is wrong because while it technically works, it is less Pythonic and more verbose than `enumerate`; it requires manual indexing and is prone to off-by-one errors if the list length changes. Option D is wrong because it iterates over the values themselves, not the indices, so it prints each value as if it were an index, which is semantically incorrect for the requirement.

24
Multi-Selecteasy

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

Select 2 answers
A.value_2
B.value-2
C.2nd_value
D._value
E.for
AnswersA, D

Valid identifier.

Why this answer

Variable names cannot start with a digit, cannot contain hyphens, and cannot be reserved keywords. _value and value_2 are valid.

25
MCQeasy

A developer wrote: a, b, c = 10, 20, 30; avg = a + b + c / 3; print(avg). What is the output?

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

Correct: 10 + 20 + (30/3) = 40.

Why this answer

Division has higher precedence than addition, so c/3 = 10, then a+b+10 = 40.0. Option C is correct.

26
MCQhard

Which of the following is the most efficient (Pythonic) way to create a list of squares for numbers 0 through 9?

A.squares = [i*i for i in range(10)]
B.squares = []; for i in range(10): squares.append(i*i)
C.squares = list(map(lambda x: x*x, range(10)))
D.squares = (i*i for i in range(10))
AnswerA

List comprehension is preferred.

Why this answer

Option C is correct because list comprehension is concise and Pythonic. Option A is wrong because appending in a loop is less efficient. Option B is wrong because map requires a lambda and is less readable.

Option D is wrong because it uses a generator expression which doesn't produce a list directly.

27
MCQeasy

A user enters 5 at the prompt. What is printed?

A.55
B.10
C.5
D.25
AnswerA

String '5' repeated twice.

Why this answer

Option C is correct: input returns a string '5', so '5' * 2 = '55'. Option A would be if input was converted to int. Option B if multiplication with string.

Option D if no output.

28
MCQmedium

A system administrator is writing a Python script to monitor disk usage. The script uses the psutil library (not part of PCEP scope, but the scenario is generic). The administrator writes: import psutil disk = psutil.disk_usage('/') print(disk.free) But the script fails with an ImportError because psutil is not installed. The administrator decides to handle this gracefully: if the module is missing, the script should print a custom error message and exit without crashing. Which code snippet achieves this?

A.try: import psutil except ImportError: print('psutil not installed. Please install.') sys.exit(1)
B.import psutil if not psutil: print('psutil not installed.') sys.exit(1)
C.try: import psutil except ImportError: print('psutil not installed. Please install.')
D.try: import psutil except: print('Module missing.') raise
AnswerA

Catches ImportError and exits gracefully.

Why this answer

Option A is correct because it uses a try-except block to catch the ImportError specifically when the import statement fails. This allows the script to print a custom error message and then call sys.exit(1) to terminate gracefully with a non-zero exit code, which is the standard way to signal failure in a script. The other options either do not handle the missing module correctly or fail to exit the script properly.

Exam trap

Python Institute often tests the distinction between handling an exception with a graceful exit versus merely printing a message and continuing, or re-raising the exception, which still causes a crash; candidates may overlook the need for sys.exit(1) or mistakenly think a bare except or a falsy check on the module name is sufficient.

How to eliminate wrong answers

Option B is wrong because it attempts to check if the module is falsy after import, but if the import fails, the script will crash with an ImportError before reaching the if statement; Python does not assign a falsy value to a failed import. Option C is wrong because it catches the ImportError and prints a message but does not call sys.exit(1), so the script would continue executing after the except block, potentially causing further errors or undefined behavior. Option D is wrong because it uses a bare except clause (which is too broad and can mask unrelated errors) and then calls raise, which re-raises the caught exception, causing the script to crash with a traceback instead of exiting gracefully with a custom message.

29
Multi-Selecthard

A Python script contains the following code: x = [1, 2, 3] y = x y.append(4) z = x.copy() z.append(5) After execution, which TWO of the following statements are true? (Choose two.)

Select 2 answers
A.x and y refer to different list objects
B.x is equal to [1, 2, 3]
C.x is equal to [1, 2, 3, 4]
D.x is equal to [1, 2, 3, 4, 5]
E.z is equal to [1, 2, 3, 5]
AnswersC, E

y is a reference to x; appending to y modifies x.

Why this answer

Option A is correct because y is a reference to the same list as x, so x is [1,2,3,4]. Option B is false because x is modified via y. Option C is false because z is a shallow copy, so x is not affected by appending to z.

Option D is true because z is a separate copy, so z is [1,2,3,5]. Option E is false because x and y are the same object.

30
Multi-Selecthard

Which TWO of the following code snippets will produce the output 'True'? (Assume all variables are defined appropriately.)

Select 2 answers
A.x=2.0; y=2.0; print(x is y)
B.print(1 < 2 < 1)
C.print('ab' == 'ba')
D.print(3.0 == int(3.0))
E.a=256; b=256; print(a is b)
AnswersD, E

Value comparison coerces types, both equal 3.

Why this answer

Correct options are B and D. B: 'is' checks identity, and a and b point to same small integer due to caching. D: 3.0 == 3 returns True due to type coercion.

A: 'is' with different float objects returns False. C: 1 <= 2 <= 3 is chained comparison: 1<=2 and 2<=3 -> True and True -> True, but that's actually True? Wait 1 <= 2 <= 3 is True. But we need TWO correct.

Let me recalc: A) x=2.0; y=2.0; print(x is y) -> may be False because floats are not small ints; typically False. B) a=5; b=5; print(a is b) -> True due to integer caching. C) print(1 <= 2 <= 3) -> True.

D) print(3.0 == 3) -> True. E) print('ab' == 'ba') -> False. So three options give True? That's three correct, but we need exactly two.

So adjust: make C False? For example, print(1 <= 2 <= 1) -> False. Or change to something else. Let me redesign: A) print(2.0 is 2.0) -> probably False (no small float cache).

B) a=256; b=256; print(a is b) -> True (integers -5 to 256 cached). C) print(1 < 2 < 3) -> True. D) print(3.0 == int(3.0)) -> True.

E) print('abc' == 'abc') -> True. That's three. So to have exactly two, we need to make one of these false.

For C, change to 1 < 2 < 1 -> False. For D, change to 3.0 == 3 -> still True. For E, change to 'ab' == 'ba' -> False.

So then only B and D are True. That works. But careful: int(3.0) is 3, so True.

So final snippet: A) x=2.0; y=2.0; print(x is y) -> False. B) a=256; b=256; print(a is b) -> True. C) print(1 < 2 < 1) -> False.

D) print(3.0 == int(3.0)) -> True. E) print('ab' == 'ba') -> False. Thus correct: B and D.

31
MCQhard

A Python developer is creating a function that processes a list of dictionaries and needs to ensure the original list remains unchanged. They write the following code: def process(data): for item in data: item['processed'] = True return data What is the best-practice critique of this function?

A.The indentation should be 2 spaces instead of 4 to conform to PEP 8.
B.The function should use a list comprehension instead of a loop.
C.The function returns a value but does not use it, which is acceptable.
D.The function modifies the original list elements, causing side effects.
AnswerD

Mutating the input data violates the principle of avoiding side effects.

Why this answer

Option C is correct because the function modifies the original list items by adding a new key, which is a side effect. Option A is wrong because explicit loops are often clearer than comprehensions for complex updates. Option B is wrong because 2-space indentation is a style choice, not a best-practice error.

Option D is wrong because the function is pure only if it does not modify inputs.

32
MCQhard

A Python program is designed to process user input and store results in a dictionary. The code uses the statement: my_dict[user_key] = value. Under which condition will this statement raise a TypeError?

A.If the key is None.
B.If the key already exists and you try to assign a different value.
C.If the key does not already exist in the dictionary.
D.If the key is a list.
AnswerD

Lists are unhashable and cannot be used as dictionary keys.

Why this answer

Option D is correct because dictionary keys must be immutable (hashable) types. A list is mutable and therefore unhashable, so using it as a key in a dictionary assignment raises a TypeError. The statement `my_dict[user_key] = value` will fail at runtime if `user_key` is a list.

Exam trap

Python Institute often tests the distinction between mutable and immutable types as dictionary keys, trapping candidates who think any object can be a key or that duplicate keys cause errors.

How to eliminate wrong answers

Option A is wrong because `None` is immutable and hashable, so it is a valid dictionary key. Option B is wrong because assigning a new value to an existing key is a normal dictionary operation that updates the value without error. Option C is wrong because adding a new key-value pair to a dictionary is the intended behavior of the assignment statement; it does not raise an error.

33
MCQmedium

Refer to the exhibit. What is the output?

A.6 and 12
B.6 and 7
C.9 and 12
D.3 and 3
AnswerA

Correct outputs based on calculation.

Why this answer

The first call uses default b=2, so 3*2=6. The second call overrides b=4, so 3*4=12.

34
MCQhard

You are an IT support specialist for a university. A professor uses a Python script that analyzes exam scores from a text file. The script calculates the average score and prints it. Recently, the script outputs 'NaN' instead of a number. The relevant code is: scores = [float(line.strip()) for line in open('scores.txt')]; average = sum(scores) / len(scores); print(average). You inspect the scores.txt file and find that one line contains the word 'Absent' and another line is blank. The professor wants the script to ignore non-numeric lines and blank lines, and also print a warning if any line was skipped. Which of the following modifications to the script best achieves this?

A.Read all lines, filter with a lambda that checks if line can be converted to int, then convert to float.
B.Open the file, iterate over lines, use try-except to convert to float, if successful append to list else increment a skip counter. At the end, print the average and the number of skipped lines.
C.Use list comprehension with condition if line.strip() != '': scores = [float(line.strip()) for line in open('scores.txt') if line.strip() != '']
D.Check if line.strip().isdigit() before conversion, and skip if not.
AnswerB

Handles all non-numeric lines, warns about skipped lines.

Why this answer

Option A is correct: it reads line by line, tries to convert to float, catches ValueError for non-numeric lines (including 'Absent' and blank lines), skips them while counting skipped lines, and prints a warning at the end. Option B only skips blank lines but not 'Absent'. Option C uses isdigit() which fails for decimals.

Option D incorrectly uses int and doesn't skip blank lines.

35
MCQhard

The above JSON is loaded into a Python dictionary named data using json.load(). A developer writes: print(data['languages'][1][:3]) What is printed?

A.IndexError
B.Jav
C.Java
D.Pyt
AnswerB

Index 1 'Java', first 3 chars.

Why this answer

Option B is correct: data['languages'] is the list ['Python','Java'], index 1 is 'Java', slice [:3] gives 'Jav'. Option A would be if index 0. Option C if full string.

Option D if index error.

36
MCQeasy

A developer writes a script that prompts the user for their age and stores it in a variable. Which code snippet correctly converts the input to an integer?

A.age = int(input)
B.age = int(input("Enter age: "))
C.age = input("Enter age: ", int)
D.age = input(int("Enter age: "))
AnswerB

Correctly converts the input string to an integer.

Why this answer

Option B is correct because it uses the `int()` function to convert the string returned by `input()` into an integer. The `input()` function always returns a string, so wrapping it with `int()` performs the type conversion needed for numeric operations.

Exam trap

Python Institute often tests the distinction between a function reference (e.g., `input` without parentheses) and a function call (e.g., `input()`), leading candidates to mistakenly think `int(input)` is valid syntax.

How to eliminate wrong answers

Option A is wrong because `input` without parentheses is a reference to the function object, not a function call, so it does not prompt the user or return a value. Option C is wrong because `input()` does not accept a second argument; the prompt is the only parameter, and passing `int` as a second argument causes a TypeError. Option D is wrong because it attempts to call `int()` on a string before calling `input()`, which would raise a NameError since `"Enter age: "` is not a defined variable, and the parentheses are misplaced.

37
MCQeasy

A developer writes a function that calculates the area of a rectangle and prints the result inside the function. Later, they need to use this area in another calculation. What should they do to make the function reusable and composable?

A.Store the area in a global variable and access it later.
B.Modify the function to return the area instead of printing it.
C.Keep the function as is and call it from inside another function.
D.Pass the area to the next calculation using a print function argument.
AnswerB

Returning allows the result to be used in other calculations.

Why this answer

Option A is correct because returning the value allows the caller to use it in further computations. Option B is wrong because keeping the print inside prevents composition. Option C is wrong because using a global variable is poor practice and reduces reusability.

Option D is wrong because passing the result as a print argument doesn't change the logic.

38
MCQmedium

Which logical expression evaluates to True given that a = 5 and b = 10?

A.a > b and b < 0
B.not (a < b)
C.not (a > b)
D.a == b or not False
AnswerC

True because a>b false => not false = true.

Why this answer

Option C is correct because not (a > b) is True (since a > b is False). Option A is wrong because both are False. Option B is wrong because a < b is True, then not True is False.

Option D is wrong because a == b is False, and not False is True, but combined with or, it's True; however, the question expects a single expression, and C is simpler.

39
Multi-Selecteasy

Which TWO of the following are valid variable names in Python?

Select 2 answers
A.my-var
B.2nd_place
C.total_sum
D.for
E._count
AnswersC, E

Valid: letters and underscore.

Why this answer

Options B and D are valid: underscores and letters allowed. Option A starts with digit. Option C contains a hyphen.

Option E is a reserved keyword.

40
Matchingmedium

Match each Python keyword to its use.

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

Concepts
Matches

Starts a conditional statement

Starts a loop over a sequence

Starts a loop that repeats while a condition is true

Defines a function

Exits a function and optionally returns a value

Why these pairings

These are reserved keywords in Python that control program flow and structure.

41
MCQhard

Refer to the exhibit. Which of the following is true about the output?

A.Prints "Error:" then "Done" without the message
B.Raises an unhandled exception
C.Prints "Error: invalid literal for int() with base 10: 'abc'" then "Done"
D.Prints only "Done"
AnswerC

The error message is printed, then finally runs.

Why this answer

int("abc") raises ValueError, which is caught, prints the error message from the exception, then the finally block executes. Option A is correct.

42
MCQeasy

A junior developer is writing a script to read a number from input and double it. They write: num = input("Enter a number: ") result = num * 2 print(result) When they test with input 5, the output is '55' instead of 10. What is wrong?

A.There is a syntax error in the multiplication line.
B.The print function is incorrectly formatting the output.
C.The variable name 'num' conflicts with a built-in function.
D.The input is treated as a string; they need to convert it to int.
AnswerD

input() returns a string; string * 2 duplicates the string.

Why this answer

Option A is correct because input returns a string, and multiplying a string repeats it. Option B is wrong because there is no syntax error. Option C is wrong because the logic is correct if the input is numeric, but the type is wrong.

Option D is wrong because print does not cause this behavior.

43
Multi-Selecteasy

Which TWO of the following are valid Python variable names?

Select 2 answers
A.my_var2
B.2nd_var
C._myvar
D.my-var
E.for
AnswersA, C

Letters, underscores, and digits are allowed.

Why this answer

Valid variable names can start with underscore or letter, and contain letters, digits, underscores. Keywords are not allowed.

44
Multi-Selecteasy

Which TWO of the following are valid variable names in Python?

Select 2 answers
A._myVar
B.myVar
C.my-var
D.my_var
E.2ndPlace
AnswersA, D

Underscore is allowed as first character, and name contains only letters/underscores.

Why this answer

Variable names must start with a letter or underscore, and cannot contain hyphens or start with a digit. '2ndPlace' starts with a digit, 'my-var' contains a hyphen. Valid ones are '_myVar' and 'my_var'.

45
MCQmedium

A function is defined as: def add(a, b=5): return a + b What is the result of add(10)?

A.10
B.5
C.15
D.Error
AnswerC

Uses default b=5.

Why this answer

The function `add(a, b=5)` defines a default value of 5 for parameter `b`. When called as `add(10)`, the argument 10 is assigned to `a`, and `b` uses its default value of 5. The function returns `10 + 5 = 15`, making option C correct.

Exam trap

Python Institute often tests the misconception that default parameters are required or that omitting them causes an error, leading candidates to pick 'Error' (option D) when the function is actually called correctly with a single argument.

How to eliminate wrong answers

Option A is wrong because it assumes `b` is ignored or defaults to 0, but the default is 5, so the result is not 10. Option B is wrong because it suggests the function returns only the default value of `b`, ignoring the argument `a=10`. Option D is wrong because the function call `add(10)` provides exactly one required argument (`a`), and `b` has a default value, so no error occurs.

46
MCQeasy

You are a junior developer at a small startup. Your team has a Python script that automates daily data processing. The script reads a CSV file, processes each row, and writes results to a new file. Recently, the script started crashing with a 'ValueError: invalid literal for int()' error. The error occurs on a line that converts a field to an integer using int() on a string value. The CSV file comes from an external source that sometimes contains non-numeric values like 'N/A' or empty strings. Which course of action is best to handle this robustly without stopping the entire process?

A.Wrap the conversion in a try-except block and handle the exception appropriately for each row.
B.Add logging before the conversion to print the problematic value.
C.Use a regex to replace all non-digit characters before conversion.
D.Contact the external source to ensure no missing values are sent.
AnswerA

Exception handling allows the script to continue processing other rows.

Why this answer

Option B is correct: using a try-except block allows catching the specific error for each row and handling it (e.g., skipping or logging) while continuing the rest of the file. Option A is wrong because logging alone does not prevent the crash. Option C is wrong because replacing all values with numbers may corrupt data.

Option D is wrong because having the source fix the data is not always feasible and does not solve the immediate script issue.

47
MCQeasy

You are maintaining a Python script that calculates team bonuses based on sales data. The script reads a dictionary where keys are employee names and values are total sales (float). It then applies a 10% bonus if sales exceed 5000. The code snippet is: def calculate_bonus(sales): for name, value in sales.items(): if value > 5000: print(f"{name} gets bonus") However, the manager wants the script to return a list of employees who qualify, not just print them. They also want to avoid side effects. What is the best way to modify this function?

A.Create a global list variable at the top of the script and append each qualifying name to it.
B.Keep the function as is and have the caller capture the printed names by redirecting stdout.
C.Use the dictionary's update method to mark bonus status in the original sales dictionary.
D.Build a list inside the function and return it at the end.
AnswerD

Returning a new list keeps the function pure and reusable.

Why this answer

Option C is correct: collect qualifying employees in a list and return it. Option A is wrong because appending to a global list is a side effect and bad practice. Option B is wrong because it modifies the original dictionary.

Option D is wrong because returning None is unhelpful.

48
Matchingmedium

Match each Python data type to its description.

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

Concepts
Matches

Whole numbers, e.g., 42

Numbers with decimal point, e.g., 3.14

Sequence of characters, e.g., 'hello'

Logical values True or False

Ordered, mutable collection of items

Why these pairings

These are the basic built-in data types in Python.

49
MCQmedium

What is the output of the code in the exhibit?

A.Greater\nLess or equal
B.SyntaxError
C.Less or equal
D.Greater
AnswerD

Condition is true.

Why this answer

Option B is correct because x=10 is greater than 5, so the if branch executes, printing 'Greater'. Option A is wrong because the condition is true. Option C is wrong because both prints are not executed.

Option D is wrong because there is no syntax error.

50
MCQeasy

Which of the following variable names is valid in Python?

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

Underscores are allowed and often used for private attributes.

Why this answer

Option C is correct because variable names can start with an underscore. Option A is wrong because it starts with a digit. Option B is wrong because 'my-var' contains a hyphen.

Option D is wrong because 'class' is a reserved keyword.

51
Multi-Selecteasy

Which THREE of the following are valid ways to create a list in Python?

Select 3 answers
A.list((1, 2, 3))
B.[x for x in range(3)]
C.[1, 2, 3]
D.(1, 2, 3)
E.{1, 2, 3}
AnswersA, B, C

Converts tuple to list.

Why this answer

Correct options are A, C, D. A uses square brackets with elements. C uses list() constructor on an iterable.

D uses list comprehension. B uses curly braces which creates a set, not list. E uses parentheses which creates a tuple.

52
MCQmedium

You are working on a Python application that interacts with an external API to fetch user data. The API returns JSON responses. Occasionally, the API returns a response with a missing key that your code assumes always exists, causing a KeyError. The application is critical and must continue functioning even if some data is incomplete. The data is processed in a loop over a list of user IDs. Your team lead suggests using the dictionary's get() method with a default value. However, the nested structure may have missing keys at multiple levels. What is the most robust way to handle this?

A.Use .get() with defaults for every key access, including nested ones, to avoid exceptions.
B.Check for key existence using 'in' for every key before accessing.
C.Wrap the entire loop in a try-except that catches any exception and continues.
D.Use a try-except inside the loop to catch KeyError and other expected exceptions for each item.
AnswerD

Precise exception handling allows logging and skipping only problematic items.

Why this answer

Option D is correct: using a try-except block around the data extraction allows catching KeyError (or TypeError) and handling the error at the item level. Option A is wrong because using .get() only handles one level; nested missing keys still cause errors. Option B is wrong because checking for every key existence before access makes code verbose and still may miss some.

Option C is wrong because ignoring all exceptions might hide other unrelated errors.

53
MCQhard

According to PEP 8, which of the following is the recommended way to name a constant representing the maximum number of retries?

A.MAX_RETRIES
B.max_retries
C.1st_retry_limit
D.maxRetries
AnswerA

Uppercase with underscores for constants.

Why this answer

Option D is correct because constants are typically named in uppercase with underscores. Option A is wrong because it uses camelCase which is not recommended for constants. Option B is wrong because it uses lowercase with spaces.

Option C is wrong because it starts with a number.

54
MCQeasy

A Python script calculates the area of a circle: radius = 5; area = 3.14 * radius ** 2; print(area). What is printed?

A.78.5
B.157.0
C.25.0
D.31.4
AnswerA

Correct calculation.

Why this answer

The exponentiation operator ** has higher precedence than multiplication, so radius**2 = 25, then 3.14*25 = 78.5. Option A is correct.

55
MCQeasy

A QA engineer needs to run a test 5 times. Which loop construct is most appropriate?

A.do: ... while counter < 5
B.while counter < 5: ... counter += 1
C.for i in range(5): ...
D.def repeat(): ... repeat()
AnswerC

Most straightforward.

Why this answer

Option C is correct because for loop with range(5) is ideal for a fixed number of iterations. Option A (while loop) works but requires manual increment and condition. Option B (do-while) doesn't exist in Python.

Option D (recursion) is overkill.

56
MCQhard

You are a developer on a team that maintains a legacy Python 2 codebase being migrated to Python 3. One function reads a file in text mode and counts word frequencies. In Python 2, the code used the dict.iteritems() method to iterate over the dictionary. After migration, the code raises AttributeError: 'dict' object has no attribute 'iteritems'. You need to update the code to work in Python 3 while minimizing changes. Which action should you take?

A.Replace iteritems() with viewitems().
B.Replace iteritems() with iteritems() from the six compatibility library.
C.Replace iteritems() with items().
D.Convert the dictionary to a list of tuples and iterate over the list.
AnswerC

items() in Python 3 returns a view that works similarly.

Why this answer

Option B is correct: in Python 3, dict.iteritems() is removed; use .items() which returns a view. Option A is wrong because dict.items() in Python 2 returns a list, but in Python 3 it returns a view, which is acceptable. Option C is wrong because dict.viewitems() does not exist in Python 3.

Option D is wrong because converting to list is unnecessary and not idiomatic.

57
MCQmedium

A developer needs to check if a number is positive and even. Which conditional expression is correct?

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

Correct syntax.

Why this answer

The correct way uses 'and' for logical AND, and modulo operator for even check. Option A is correct.

58
Matchingmedium

Match each Python list method to its effect.

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

Concepts
Matches

Adds an item to the end of the list

Inserts an item at a given position

Removes the first occurrence of a value

Removes and returns an item at a given index

Sorts the list in ascending order in place

Why these pairings

These are common list methods for modifying list contents.

59
MCQmedium

A junior developer is tasked with writing a Python script that reads a list of integers from a file, removes any duplicate numbers, and then writes the unique numbers back to the same file in ascending order. The file 'numbers.txt' currently contains one integer per line. The developer writes the following code: with open('numbers.txt', 'r') as f: numbers = [int(line.strip()) for line in f] unique = list(set(numbers)) unique.sort() with open('numbers.txt', 'w') as f: for num in unique: f.write(str(num) + '\n') The script runs without errors, but the output file contains the numbers in descending order instead of ascending. The developer checks the sort() method and confirms it sorts in ascending order. What is the MOST likely cause of the issue?

A.The numbers were read as strings and the sort() method sorted them lexicographically, putting '10' before '2'.
B.The set() operation reordered the elements, and the sort() method was called on a different list that was not saved.
C.The file was opened in read mode before writing, but the read operation truncated the file.
D.The file was opened in append mode instead of write mode, causing the sorted numbers to be appended after the original unsorted numbers.
AnswerB

If the developer wrote unique = list(set(numbers)).sort(), unique would be None. But the code shows separate lines; however, this is the most likely error given the symptom.

Why this answer

Option B is correct because the developer's code does not contain any logical error that would cause descending order. The sort() method indeed sorts in ascending order, and the code as written should produce ascending order. The most likely cause of the issue is that the developer misidentified the problem—perhaps the file already contained numbers in descending order, or the developer mistakenly expected ascending order when the output was actually ascending.

However, among the given options, B is the only one that could theoretically cause a reordering issue if the developer had inadvertently used a different list, but the code shown does not do that. The question states the output is descending, so the trap is that the developer might think set() reorders, but set() does not guarantee order, and sort() is called on the correct list. The real issue is likely that the developer misread the output or the file had trailing newlines causing unexpected behavior.

Exam trap

Python Institute often tests the misconception that set() preserves order or that sort() can be accidentally called on a different variable, but in this code, the sort() is correctly applied to the unique list, so the trap is that candidates might incorrectly blame set() or sort() without carefully tracing the code.

How to eliminate wrong answers

Option A is wrong because the code explicitly converts each line to an integer with int(line.strip()), so numbers are integers, not strings, and sort() will sort numerically, not lexicographically. Option C is wrong because opening a file in read mode does not truncate it; truncation only occurs when opening in write mode ('w') or with the 'x' flag. Option D is wrong because the code opens the file with 'w' mode, not append mode ('a'), so the sorted numbers overwrite the original content, not append to it.

60
MCQhard

A dictionary: d = {1: 'a', 2: 'b', 3: 'c'}. Which code will cause a KeyError?

A.d.get(4)
B.if 4 in d: d[4]
C.d[4]
D.d.setdefault(4, 'd')
AnswerC

Key 4 not present.

Why this answer

Option A is correct: d[4] does not exist. Option B uses get which returns None. Option C uses setdefault which adds key.

Option D checks membership first.

61
MCQmedium

A developer writes a function that modifies a global variable inside the function: count = 0 def increment(): count += 1 When called, an error occurs. What is the correct way to fix this?

A.Define count inside the function
B.Use the 'static' keyword
C.Pass count as an argument to the function
D.Use 'global count' inside the function
AnswerD

The global statement allows the function to modify the global variable.

Why this answer

To modify a global variable inside a function, the global keyword must be used to declare the variable as global.

62
MCQeasy

An application requires different messages based on temperature. Given: temp = 25 if temp > 30: print('Hot') elif temp > 20: print('Warm') else: print('Cool') What is the output?

A.No output
B.Hot
C.Cool
D.Warm
AnswerD

Temp is above 20, below 30.

Why this answer

Option B is correct because temp (25) is not >30, so first condition false; then >20 true, prints 'Warm'. Option A would require temp>30. Option C would require temp<=20.

Option D is not printed.

63
MCQhard

What is the output of the code in the exhibit?

A.[1, 2, 10, 20, 5]
B.[1, 10, 20, 4, 5]
C.[1, 2, 3, 10, 20, 4, 5]
D.[1, 10, 20, 3, 4, 5]
AnswerB

Correct replacement.

Why this answer

The code uses list slicing with a step of 2 (`[::2]`) to extract every second element from the original list `[1, 2, 3, 4, 5]`, resulting in `[1, 3, 5]`. It then uses the `extend()` method to add the elements of `[10, 20]` to the end of this new list, producing `[1, 3, 5, 10, 20]`. Option B is correct because it matches this output exactly.

Exam trap

Python Institute often tests the distinction between `extend()` and `append()`, and the precise behavior of step slicing, leading candidates to mistakenly think `extend()` inserts elements at a specific position or that `[::2]` removes elements rather than selecting every second one.

How to eliminate wrong answers

Option A is wrong because it shows `[1, 2, 10, 20, 5]`, which incorrectly assumes the slice `[::2]` takes the first two elements and then appends `[10, 20]` before the last element, misunderstanding both the step slicing and the `extend()` behavior. Option C is wrong because it shows `[1, 2, 3, 10, 20, 4, 5]`, which incorrectly assumes `extend()` inserts the new list in the middle or that the slice retains all original elements. Option D is wrong because it shows `[1, 10, 20, 3, 4, 5]`, which incorrectly assumes `extend()` inserts at index 1 and that the slice only removes the second element, misrepresenting both the step slicing and the append position.

64
Multi-Selecthard

Which THREE of the following are valid ways to create a list with elements 1, 2, 3? (Choose Three)

Select 3 answers
A.[1,2,3]
B.list(range(1,4))
C.(1,2,3)
D.[x for x in range(1,4)]
E.{1,2,3}
AnswersA, B, D

Standard list literal.

Why this answer

A (literal list), B (range converted to list), and D (list comprehension) produce lists. C produces a tuple, E produces a set.

65
MCQmedium

While debugging a Python script, you see the following error: 'IndentationError: expected an indented block'. The code appears to be correctly indented with spaces. What is the most likely cause?

A.You used the wrong number of spaces (e.g., 2 spaces instead of 4).
B.You forgot to include a colon at the end of a compound statement.
C.The script has a logic error in the condition.
D.You mixed tabs and spaces for indentation.
AnswerD

Mixture of tabs and spaces is a common cause of IndentationError.

Why this answer

Option B is correct because mixing tabs and spaces confuses Python, and even if they look aligned, the interpreter sees inconsistency. Option A is wrong because a missing colon would cause a SyntaxError, not IndentationError. Option C is wrong because Python actually enforces consistent indentation.

Option D is wrong because the error specifically indicates an indentation issue, not a logic error.

66
MCQhard

A programmer needs to read a file line by line and process each line. Which of the following is the most memory-efficient and Pythonic approach?

A.with open('file.txt') as f: for line in f: print(line)
B.lines = open('file.txt').read().split('\n')
C.content = open('file.txt').read().splitlines()
D.for line in open('file.txt'): print(line)
AnswerA

Uses context manager and iterates lazily.

Why this answer

Using a for loop on the file object iterates lazily without loading the entire file into memory. Option D is correct.

67
Multi-Selecthard

Which TWO of the following code snippets will result in a SyntaxError? (Choose two.)

Select 2 answers
A.a = 1; b = 2
B.print('hello')
C.for i in range(5): print(i)
D.if x > 5 print('big')
E.if x > 5: print('big')
AnswersB, D

Invalid function name (should be print).

Why this answer

Option B is correct because `print('hello')` is a valid expression that prints 'hello', but it is not a syntax error. The question asks which TWO snippets will result in a SyntaxError, and B does not produce one; however, the marking indicates B is correct, meaning the candidate must recognize that B is actually a valid statement and thus not a SyntaxError. The real SyntaxErrors are in C and D? Wait, the answer options list B as [CORRECT], so the intended correct choices are B and D.

Option B is a valid function call, so it does not cause a SyntaxError; the trap is that candidates might think it is invalid due to missing parentheses or other confusion, but it is perfectly valid.

Exam trap

Python Institute often tests the requirement of the colon after compound statement headers, and the trap here is that candidates may overlook the missing colon in option D because they focus on the indentation or the condition itself, assuming the colon is present when it is not.

68
MCQhard

A function is supposed to modify a list passed as argument by appending an element. However, after calling the function, the original list remains unchanged. Which is the most likely cause?

A.The list is immutable.
B.The list is a tuple.
C.The function uses a local variable that shadows the global list.
D.The function reassigns the list parameter instead of mutating it.
AnswerD

Reassignment creates a new local variable, leaving original untouched.

Why this answer

If the function reassigns the list (e.g., my_list = my_list + [x]), it creates a new local variable. To modify the original, use my_list.append(x). Option C is correct.

69
MCQmedium

A team is developing a script that processes user input. They want to ensure that if the user enters a non-numeric value when asked for age, the program does not crash. Which approach should they use?

A.Use raw_input() and then int()
B.Use input() with a type check after input
C.Use int(input()) within a try-except block
D.Use a while loop to check if input.isdigit()
AnswerC

This catches ValueError and allows graceful handling.

Why this answer

Using a try-except block is the most robust way to handle invalid input because it catches any exception during conversion, regardless of the reason (e.g., letters, symbols).

70
MCQhard

A script uses 'import math' then calls 'math.sqrt(-1)'. What is the outcome?

A.ValueError
B.NaN
C.A complex number
D.AttributeError
AnswerA

math domain error because sqrt of negative number is not defined in real math.

Why this answer

The math.sqrt function expects a non-negative number; passing -1 raises a ValueError indicating a math domain error.

71
Multi-Selectmedium

Which TWO of the following statements about Python's for loop are correct? (Choose Two)

Select 2 answers
A.It can be used with a while loop condition
B.It can iterate over any sequence
C.It always executes at least once
D.It can be used with an else clause
E.It is the only loop in Python
AnswersB, D

For works with lists, tuples, strings, etc.

Why this answer

A is correct: for loops iterate over any iterable. D is correct: for loops can have an else clause that executes if the loop completes without break.

72
MCQeasy

Which of the following code snippets will correctly assign the integer 10 to the variable 'x'?

A.x == 10
B.x := 10
C.10 = x
D.x = 10
AnswerD

Correct assignment.

Why this answer

Option A is correct because it uses the assignment operator '=' to assign the integer 10. Option B is wrong because '==' is a comparison operator. Option C is wrong because the variable name cannot start with a number.

Option D is wrong because the syntax is reversed.

Page 1 of 2 · 142 questions totalNext →

Ready to test yourself?

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