PCEP Computer Programming and Python Fundamentals • Complete Question Bank
Complete PCEP Computer Programming and Python Fundamentals question bank — all 0 questions with answers and detailed explanations.
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 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?
Refer to the exhibit. ``` x = '10' y = 5 result = x + y print(result) ```
Refer to the exhibit. ``` my_list = [1, 2, 3, 4, 5] my_list[1:3] = [10, 20] print(my_list) ```
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?
Drag steps to the numbered slots on the right, or tap a step then tap a slot.
Drag steps to the numbered slots on the right, or tap a step then tap a slot.
Drag steps to the numbered slots on the right, or tap a step then tap a slot.
Drag a concept onto its matching description — or click a concept then click the description.
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
Drag a concept onto its matching description — or click a concept then click the description.
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
Drag a concept onto its matching description — or click a concept then click the description.
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
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?
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 function is defined as:
def add(a, b=5):
return a + bWhat is the result of add(10)?
A developer writes:
try:
x = int('hello') except ValueError: x = 0 except TypeError: x = -1 finally: x = x + 1 What is the final value of x?
Consider code:
def outer():
x = 1
def inner():
nonlocal x x = 2 inner()
print(x)
outer() What is printed?
Refer to the exhibit.
# Python script: convert.py
x = input('Enter number: ')
y = x * 2
print(y)
--- End of exhibit ---Refer to the exhibit. A network engineer runs 'ipconfig' on Windows and observes: Ethernet adapter Local Area Connection: IPv4 Address. . . . . . . . . . . : 192.168.1.10 Subnet Mask . . . . . . . . . . . : 255.255.255.0 Default Gateway . . . . . . . . . : 192.168.1.1 The Python code: import re output = "..." # contains the above text pattern = r"\d+\.\d+\.\d+\.\d+" match = re.findall(pattern, output) print(match) --- End of exhibit ---
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?
Refer to the exhibit.
{
"name": "Alice",
"age": 30,
"city": "New York",
"languages": ["Python", "Java"]
}
--- End of exhibit ---A programmer writes the following code:
if x > 5:
print('Greater')What is the most likely cause of an IndentationError?
What is the output of the following code?
print('Hello'.upper())Consider the following function definition:
def add(a, b):
return a + bWhat is the value of add(3, '4')?
Refer to the exhibit.
x = 10
if x > 5:
print('Greater')
else:
print('Less or equal')Refer to the exhibit.
Traceback (most recent call last):
File "script.py", line 3, in <module>
print(result)
NameError: name 'result' is not definedRefer to the exhibit.
{
"name": "config",
"version": 2,
"settings": {
"debug": true,
"port": 8080
}
}def calculate(a, b=2):
return a * b
print(calculate(3))
print(calculate(3,4))x = 10
y = 5
if x > y:
print("x greater")
elif x == y:
print("equal")
else:
print("y greater")NameError: name 'x' is not defined
def square(x):
return x ** 2
result = square(4)
print(result)numbers = [1, 2, 3, 4, 5]
for i in range(len(numbers)):
if numbers[i] % 2 == 0:
numbers[i] = numbers[i] ** 2
print(numbers)try:
x = int("abc")
except ValueError as e:
print("Error:", e)
finally:
print("Done")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?
def calculate_discount(price, discount):
if discount > 0.5:
print("Discount too high")
return price
return price * (1 - discount)try:
x = int("hello")
except ValueError:
print("Invalid integer")
except:
print("Some error")config = {
'env': 'prod',
'debug': False,
'max_retries': 3
}
if config.get('debug', False):
print("Debug mode active")
else:
print("Running in normal mode")Refer to the exhibit.
Error output from a Python script:
Traceback (most recent call last):
File "script.py", line 3, in <module>
result = 10 / 0
ZeroDivisionError: division by zeroA 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 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 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.)
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?
You are a developer in a financial firm. Your team is building a Python module that performs complex calculations on large datasets. To improve performance, you are using list comprehensions and built-in functions. Your code passes all unit tests, but during integration testing, the memory usage spikes unexpectedly. The problematic area is a function that constructs a large list of intermediate results using a list comprehension that references a generator. The code is:
def process(data):
results = [expensive_transform(x) for x in data]
# further processing on results
You suspect that the list comprehension stores all results in memory at once, but you need to keep the function's output as a list for subsequent operations. What is the best solution to reduce memory without changing the function's return type?