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 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 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
Consider the following code:
x = input('Enter a number: ')
print(x + x)
A user enters 5 at the prompt. What is printed?
Refer to the exhibit.
# Python script: convert.py
x = input('Enter number: ')
y = x * 2
print(y)
--- 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?
Refer to the exhibit.
x = 10
if x > 5:
print('Greater')
else:
print('Less or equal')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")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)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 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 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?
A developer writes the following code:
x = 10 y = 3 result = x // y
print(result)
What is printed?
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?
Drag or tap steps into the slots.
Drag or tap steps into the slots.
Drag or tap steps into the slots.
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
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?
What will be printed?
```python my_list = [] my_list.append('192.168.1.10') my_list.append('255.255.255.0') my_list.append('192.168.1.1')
print(my_list)
```
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 ---
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.
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
}
}NameError: name 'x' is not defined
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?
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 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?
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 developer writes the following code:
x = 5
if x > 3:
print('A')else:
print('B')
print('C')What is the output?
A programmer writes:
x = 10 y = 4
print(x // y, x % y, x / y)
What is printed?
A Python program contains the following code:
print(10 / 4)
What is displayed when this program runs?
A developer is reviewing a script that processes user data. The script contains the following lines:
name = "Alice" age = 30
print(name + " is " + age)
When executed, the script raises a TypeError. Which of the following changes will make the script run without error and produce the output "Alice is 30"?
A student types the following into a Python 3 interactive session:
>>> greeting = 'Hello' >>> greeting = greeting + ' World' >>> print(greeting)
What is displayed?
A student runs the following code in a Python 3.11 interactive session:
>>> 7 // 2
What is displayed?
A developer writes the following code to sum a list of scores:
scores = [12, 7, 25, 18] total = 0
for s in scores:
total += s
print(total)
What is printed?
A developer writes the following code and runs it without any error:
x = 5 y = 2.0 z = x + y
What is the value and type of z?
A developer writes a short script to convert a numeric string entered at the console into a number for arithmetic:
value = input('Enter a quantity: ') total = value * 2
print(total)
A user types 7 and presses Enter. What is printed, and why?
A programmer is writing a Python script to calculate the area of a circle. They write the following code:
radius = 5 area = 3.14 * radius ** 2
print(area)
What is the output of this code?
A developer defines a function and calls it as shown:
def greet(name, greeting='Hello'):
return greeting + ', ' + name
print(greet('Ana'))What is printed?
A programmer writes the following code to convert a user's input to a number and add 5:
age = input('Enter age: ') new_age = int(age) + 5
print(new_age)
If the user enters 'twenty', what happens?
A developer is writing a Python script to compare two numbers. They write the following code:
x = 10 y = 20 result = x > y or x < y and y > 15
print(result)
What is printed?
A developer writes the following code:
values = [10, 20, 30, 40, 50] result = values[1:4]
What does the variable result contain after execution?
A programmer is debugging a Python script that uses a while loop to process a list of numbers. The code is:
numbers = [1, 2, 3, 4, 5] i = 0
while i < len(numbers):
if numbers[i] % 2 == 0:
print(numbers[i])i += 1
What is the output of this code?
A developer writes a loop to find the first even number in a list:
numbers = [3, 5, 8, 10]
for n in numbers:
if n % 2 == 0:
print(n)break else:
print('No even number')What is printed?