Courseiva
Knowledge + Practice
CertificationsVendorsCareer RoadmapsLabs & ToolsStudy GuidesGlossaryPractice Questions
C
Courseiva

Free IT certification practice questions with explained answers for CCNA, CompTIA, AWS, Azure, Google Cloud, and more.

Certification Practice Questions

CCNA practice questionsSecurity+ SY0-701 practice questionsAWS SAA-C03 practice questionsAZ-104 practice questionsAZ-900 practice questionsCLF-C02 practice questionsA+ Core 1 practice questionsGoogle Cloud ACE practice questionsCySA+ CS0-003 practice questionsNetwork+ N10-009 practice questions
View all certifications →

Product

CertificationsCertification PathsExam TopicsPractice TestsExam Dumps vs Practice TestsStudy HubComparisons

Company

AboutContactEditorial PolicyQuestion Writing PolicyTrust Center

Legal

Privacy PolicyTerms of Service

Courseiva is a free IT certification practice platform offering original exam-style practice questions, detailed explanations, topic-based practice, mock exams, readiness tracking, and study analytics for Cisco, CompTIA, Microsoft, AWS, and other technology certifications.

© 2026 Courseiva. Courseiva is operated by JTNetSolutions Ltd. All rights reserved.

Courseiva is an independent certification practice platform and is not affiliated with, endorsed by, or sponsored by Cisco, Microsoft, AWS, CompTIA, Google, ISC2, ISACA, or any other certification vendor. Vendor names and certification marks are used only to identify the exams learners are preparing for.

← Computer Programming and Python Fundamentals practice sets

PCEP Computer Programming and Python Fundamentals • Complete Question Bank

PCEP Computer Programming and Python Fundamentals — All Questions With Answers

Complete PCEP Computer Programming and Python Fundamentals question bank — all 0 questions with answers and detailed explanations.

139
Questions
Free
No signup
Certifications/PCEP/Practice Test/Computer Programming and Python Fundamentals/All Questions
Question 1easymultiple choice
Study the full Python automation breakdown →

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?

Question 2easymultiple choice
Study the full Python automation breakdown →

Which of the following is the correct way to define a function that takes no arguments and returns the value 42?

Question 3mediummultiple choice
Study the full Python automation breakdown →

A program uses a variable named 'list' that shadows the built-in list type. Later, the code tries to create a new list using list([1,2,3]) but gets a TypeError. What is the most likely cause?

Question 4mediummultiple choice
Study the full Python automation breakdown →

A programmer writes: x = 5; y = 2; result = x / y. What is the type of result?

Question 5hardmultiple choice
Study the full Python automation breakdown →

Given the code: a = [1, 2, 3]; b = a; b.append(4). What is the value of a?

Question 6easymultiple choice
Study the full Python automation breakdown →

Which of the following statements about Python indentation is true?

Question 7mediummultiple choice
Study the full Python automation breakdown →

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?

Question 8hardmultiple choice
Study the full Python automation breakdown →

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

Question 9mediummultiple choice
Study the full Python automation breakdown →

A student writes the code: x = 10; if x > 5: print("big"); else: print("small"). What is the output?

Question 10easymulti select
Study the full Python automation breakdown →

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

Question 11mediummulti select
Study the full Python automation breakdown →

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

Question 12hardmulti select
Study the full Python automation breakdown →

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

Question 13mediummulti select
Study the full Python automation breakdown →

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

Question 14hardmultiple choice
Study the full Python automation breakdown →

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?

Question 15mediummultiple choice
Study the full Python automation breakdown →

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?

Question 16mediummultiple choice
Study the full Python automation breakdown →

A developer writes a Python script that calculates the average of a list of numbers. The script sometimes produces a ZeroDivisionError. Which of the following is the MOST appropriate way to handle this error to keep the script running?

Question 17hardmultiple choice
Study the full Python automation breakdown →

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?

Question 18easymultiple choice
Study the full Python automation breakdown →

A Python script contains the following line: x = 5. Later in the script, the programmer wants to check if x is an integer. Which of the following is the BEST way to perform this check?

Question 19mediummulti select
Study the full Python automation breakdown →

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

Question 20hardmulti select
Study the full Python automation breakdown →

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

Question 21mediummultiple choice
Study the full Python automation breakdown →

What is the output of the code in the exhibit?

Exhibit

Refer to the exhibit.

```
x = '10'
y = 5
result = x + y
print(result)
```
Question 22hardmultiple choice
Study the full Python automation breakdown →

What is the output of the code in the exhibit?

Exhibit

Refer to the exhibit.

```
my_list = [1, 2, 3, 4, 5]
my_list[1:3] = [10, 20]
print(my_list)
```
Question 23easymultiple choice
Study the full Python automation breakdown →

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?

Question 24hardmultiple choice
Study the full Python automation breakdown →

A Python script uses the following code to open a file: f = open('data.txt', 'w'). The programmer then writes multiple lines to the file. After writing, which of the following is the BEST practice to ensure data integrity?

Question 25mediummultiple choice
Study the full Python automation breakdown →

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?

Question 26mediumdrag order
Study the full Python automation breakdown →

Arrange the steps to write and run a Python script from the command line in the correct order.

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
5Step 5
Question 27mediumdrag order
Study the full Python automation breakdown →

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
1Step 1
2Step 2
3Step 3
4Step 4
5Step 5
Question 28mediumdrag order
Study the full Python automation breakdown →

Arrange the steps to slice a list in Python.

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
5Step 5
Question 29mediummatching
Study the full Python automation breakdown →

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

Question 30mediummatching
Study the full Python automation breakdown →

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

Question 31mediummatching
Study the full Python automation breakdown →

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

Question 32easymultiple choice
Study the full Python automation breakdown →

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?

Question 33easymultiple choice
Study the full Python automation breakdown →

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?

Question 34easymultiple choice
Study the full Python automation breakdown →

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

Question 35mediummultiple choice
Study the full Python automation breakdown →

A data scientist has a list: scores = [88, 92, 79, 93, 85]. They want to add 5 bonus points to each score and store the new scores. Which code accomplishes this?

Question 36mediummultiple choice
Study the full Python automation breakdown →

A developer wants to extract the file extension from a filename: 'report.pdf'. Which string method will return 'pdf'?

Question 37mediummultiple choice
Study the full Python automation breakdown →

A function is defined as:

def add(a, b=5):
    return a + b

What is the result of add(10)?

Question 38hardmultiple choice
Study the full Python automation breakdown →

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?

Question 39hardmultiple choice
Study the full Python automation breakdown →

Consider code:

def outer():

x = 1

def inner():

nonlocal x x = 2 inner()

print(x)

outer() What is printed?

Question 40hardmultiple choice
Study the full Python automation breakdown →

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

Question 41easymulti select
Study the full Python automation breakdown →

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

Question 42mediummulti select
Study the full Python automation breakdown →

Which TWO statements about Python lists are true?

Question 43hardmulti select
Study the full Python automation breakdown →

Which THREE of the following will correctly iterate over all keys and values of a dictionary d = {'a':1, 'b':2}?

Question 44easymultiple choice
Study the full Python automation breakdown →

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

Exhibit

Refer to the exhibit.
# Python script: convert.py
x = input('Enter number: ')
y = x * 2
print(y)
--- End of exhibit ---
Question 45mediummultiple choice
Study the full Python automation breakdown →

What will be printed?

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 ---
Question 46hardmultiple choice
Study the full Python automation breakdown →

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?

Exhibit

Refer to the exhibit.
{
  "name": "Alice",
  "age": 30,
  "city": "New York",
  "languages": ["Python", "Java"]
}
--- End of exhibit ---
Question 47easymultiple choice
Study the full Python automation breakdown →

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

Question 48mediummultiple choice
Study the full Python automation breakdown →

A programmer writes the following code:

if x > 5:
print('Greater')

What is the most likely cause of an IndentationError?

Question 49hardmultiple choice
Study the full Python automation breakdown →

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

Question 50easymultiple choice
Study the full Python automation breakdown →

What is the output of the following code?

print('Hello'.upper())
Question 51mediummultiple choice
Study the full Python automation breakdown →

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

Question 52hardmultiple choice
Study the full Python automation breakdown →

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

Question 53easymultiple choice
Study the full Python automation breakdown →

What function is used to read input from the user in Python 3?

Question 54mediummultiple choice
Study the full Python automation breakdown →

Consider the following function definition:

def add(a, b):
    return a + b

What is the value of add(3, '4')?

Question 55hardmultiple choice
Study the full Python automation breakdown →

What is the scope of a variable defined inside a function?

Question 56mediummulti select
Study the full Python automation breakdown →

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

Question 57hardmulti select
Study the full Python automation breakdown →

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

Question 58easymulti select
Study the full Python automation breakdown →

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

Question 59mediummultiple choice
Study the full Python automation breakdown →

What is the output of the code in the exhibit?

Exhibit

Refer to the exhibit.

x = 10
if x > 5:
    print('Greater')
else:
    print('Less or equal')
Question 60hardmultiple choice
Study the full Python automation breakdown →

A developer runs the code from the exhibit and gets the error shown. Which of the following is the most likely cause?

Exhibit

Refer to the exhibit.

Traceback (most recent call last):
  File "script.py", line 3, in <module>
    print(result)
NameError: name 'result' is not defined
Question 61easymultiple choice
Study the full Python automation breakdown →

The exhibit shows a JSON configuration. Which Python data structure is best suited to represent this configuration?

Exhibit

Refer to the exhibit.

{
  "name": "config",
  "version": 2,
  "settings": {
    "debug": true,
    "port": 8080
  }
}
Question 62easymultiple choice
Study the full Python automation breakdown →

A junior developer writes the following code to swap two variables: a = 5; b = 10; a = b; b = a. When they print a and b, what is the output?

Question 63mediummultiple choice
Study the full Python automation breakdown →

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?

Question 64hardmultiple choice
Study the full Python automation breakdown →

A Python script processes a large file and runs out of memory. Which solution is most appropriate?

Question 65easymultiple choice
Study the full Python automation breakdown →

Which of the following is a correct way to comment multiple lines in Python?

Question 66mediummultiple choice
Study the full Python automation breakdown →

A programmer wants to iterate over a list and also access the index. Which built-in function should they use?

Question 67hardmultiple choice
Study the full Python automation breakdown →

What is the output of the following code? x = [1, 2, 3]; y = x; y.append(4); print(x)

Question 68easymultiple choice
Study the full Python automation breakdown →

Which of the following is an immutable data type in Python?

Question 69mediummultiple choice
Study the full Python automation breakdown →

A developer writes a function that returns multiple values. How should they return these values?

Question 70hardmultiple choice
Study the full Python automation breakdown →

What is the result of the expression: (1 and 0) or (not False and True)?

Question 71easymulti select
Study the full Python automation breakdown →

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

Question 72mediummulti select
Study the full Python automation breakdown →

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

Question 73hardmulti select
Study the full Python automation breakdown →

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

Question 74mediummultiple choice
Study the full Python automation breakdown →

Refer to the exhibit. What is the output?

Exhibit

def calculate(a, b=2):
    return a * b
print(calculate(3))
print(calculate(3,4))
Question 75hardmultiple choice
Study the full Python automation breakdown →

Refer to the exhibit. What is printed?

Exhibit

x = 10
y = 5
if x > y:
    print("x greater")
elif x == y:
    print("equal")
else:
    print("y greater")
Question 76easymultiple choice
Study the full Python automation breakdown →

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

Exhibit

NameError: name 'x' is not defined
Question 77easymultiple choice
Study the full Python automation breakdown →

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

Question 78mediummultiple choice
Study the full Python automation breakdown →

A Python function is designed to return the first element of a list. However, when passed an empty list, it raises an IndexError. Which best practice should be applied to handle this robustly?

Question 79hardmultiple choice
Study the full Python automation breakdown →

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?

Question 80easymultiple choice
Study the full Python automation breakdown →

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

Question 81mediummultiple choice
Study the full Python automation breakdown →

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?

Question 82hardmultiple choice
Study the full Python automation breakdown →

A programmer wants to create a function that can accept any number of keyword arguments and store them in a dictionary. Which function definition is correct?

Question 83easymultiple choice
Study the full Python automation breakdown →

A Python program prompts the user for their age and stores it in a variable. Which is the correct way to convert the input to an integer?

Question 84mediummultiple choice
Study the full Python automation breakdown →

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

Question 85hardmultiple choice
Study the full Python automation breakdown →

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?

Question 86easymultiple choice
Study the full Python automation breakdown →

Refer to the exhibit. What is the output?

Exhibit

def square(x):
    return x ** 2
result = square(4)
print(result)
Question 87mediummultiple choice
Study the full Python automation breakdown →

Refer to the exhibit. What is the output?

Exhibit

numbers = [1, 2, 3, 4, 5]
for i in range(len(numbers)):
    if numbers[i] % 2 == 0:
        numbers[i] = numbers[i] ** 2
print(numbers)
Question 88hardmultiple choice
Study the full Python automation breakdown →

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

Exhibit

try:
    x = int("abc")
except ValueError as e:
    print("Error:", e)
finally:
    print("Done")
Question 89easymulti select
Study the full Python automation breakdown →

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

Question 90mediummulti select
Study the full Python automation breakdown →

Which two of the following are correct ways to create a dictionary in Python? (Choose two.)

Question 91hardmulti select
Study the full Python automation breakdown →

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

Question 92easymultiple choice
Study the full Python automation breakdown →

A junior developer writes a Python script to calculate the average of three numbers: avg = a + b + c / 3. What is the problem with this code?

Question 93mediummultiple choice
Study the full Python automation breakdown →

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?

Question 94hardmultiple choice
Study the full Python automation breakdown →

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?

Question 95easymultiple choice
Study the full Python automation breakdown →

A developer wants to create a list of even numbers from 0 to 10 inclusive. Which code snippet will correctly produce [0, 2, 4, 6, 8, 10]?

Question 96easymultiple choice
Study the full Python automation breakdown →

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

Question 97mediummultiple choice
Study the full Python automation breakdown →

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?

Question 98mediummultiple choice
Study the full Python automation breakdown →

A developer writes: print('Hello' + 5). What is the result?

Question 99hardmultiple choice
Study the full Python automation breakdown →

A company has a Python script that imports a module from a package. The package structure is: mypackage/__init__.py, mypackage/module.py. The script uses 'from mypackage import module'. Which file must exist for this import to work?

Question 100hardmultiple choice
Study the full Python automation breakdown →

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

Question 101mediummultiple choice
Study the full Python automation breakdown →

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

Exhibit

def calculate_discount(price, discount):
    if discount > 0.5:
        print("Discount too high")
        return price
    return price * (1 - discount)
Question 102easymultiple choice
Study the full Python automation breakdown →

Refer to the exhibit. What is the output?

Exhibit

try:
    x = int("hello")
except ValueError:
    print("Invalid integer")
except:
    print("Some error")
Question 103hardmultiple choice
Study the full Python automation breakdown →

Refer to the exhibit. A developer runs this code. What is printed?

Exhibit

config = {
    'env': 'prod',
    'debug': False,
    'max_retries': 3
}
if config.get('debug', False):
    print("Debug mode active")
else:
    print("Running in normal mode")
Question 104easymulti select
Study the full Python automation breakdown →

Which TWO of the following are valid Python variable names?

Question 105mediummulti select
Study the full Python automation breakdown →

Which THREE of the following are built-in Python data types?

Question 106hardmulti select
Study the full Python automation breakdown →

Which TWO statements correctly describe Python's dynamic typing?

Question 107easymultiple choice
Study the full Python automation breakdown →

Which of the following variable names is valid in Python?

Question 108mediummultiple choice
Study the full Python automation breakdown →

What is the result of the following expression? 3 + 4 * 2 ** 3 // 5

Question 109hardmultiple choice
Study the full Python automation breakdown →

Given the code: my_list = [1, 2, 3, 4, 5]. What is the output of print(my_list[-3:-1])?

Question 110mediummultiple choice
Study the full Python automation breakdown →

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

Question 111easymultiple choice
Study the full Python automation breakdown →

Which of the following is a floating-point literal?

Question 112hardmultiple choice
Study the full Python automation breakdown →

What is the output of the following code? try: print(1/0); except ZeroDivisionError: print('error'); finally: print('done')

Question 113easymultiple choice
Study the full Python automation breakdown →

Which keyword is used to define a function in Python?

Question 114mediummultiple choice
Study the full Python automation breakdown →

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

Question 115hardmultiple choice
Study the full Python automation breakdown →

Consider the code: x = 10; def func(): x = 5; print(x); func(); print(x). What is the output?

Question 116mediummulti select
Study the full Python automation breakdown →

Which TWO of the following are immutable data types in Python?

Question 117hardmulti select
Study the full Python automation breakdown →

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

Question 118easymulti select
Study the full Python automation breakdown →

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

Question 119mediummultiple choice
Study the full Python automation breakdown →

Refer to the exhibit. What type of error occurred, and which line caused it?

Exhibit

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 zero
Question 120hardmultiple choice
Study the full Python automation breakdown →

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?

Question 121hardmultiple choice
Study the full Python automation breakdown →

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?

Question 122easymultiple choice
Study the full Python automation breakdown →

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?

Question 123mediummultiple choice
Study the full Python automation breakdown →

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?

Question 124hardmultiple choice
Study the full Python automation breakdown →

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?

Question 125easymultiple choice
Study the full Python automation breakdown →

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?

Question 126mediummultiple choice
Study the full Python automation breakdown →

A team is writing a Python script that reads a large log file and counts occurrences of ERROR. The script works but is very slow. They profile it and find that most time is spent reading the file line by line. Which optimization technique is most appropriate?

Question 127easymulti select
Study the full Python automation breakdown →

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

Question 128mediummulti select
Study the full Python automation breakdown →

Which THREE of the following code snippets will successfully print the string 'Hello, World!'? (Choose three.)

Question 129hardmulti select
Study the full Python automation breakdown →

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.)

Question 130easymultiple choice
Study the full Python automation breakdown →

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?

Question 131easymultiple choice
Study the full Python automation breakdown →

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?

Question 132mediummultiple choice
Study the full Python automation breakdown →

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?

Question 133mediummultiple choice
Study the full Python automation breakdown →

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?

Question 134hardmultiple choice
Study the full Python automation breakdown →

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?

Question 135hardmultiple choice
Study the full Python automation breakdown →

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?

Question 136hardmultiple choice
Study the full Python automation breakdown →

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?

Question 137easymulti select
Study the full Python automation breakdown →

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

Question 138mediummultiple choice
Study the full Python automation breakdown →

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?

Question 139hardmultiple choice
Study the full Python automation breakdown →

A system administrator is automating server configuration using Python. She has a dictionary: config = {'host': 'localhost', 'port': 8080, 'debug': True}. She needs to add a new key 'timeout' with value 30 if it does not already exist, but only if the 'debug' key is False. If 'debug' is True, she should not add 'timeout'. Additionally, she wants to ensure that the ordering of keys in the dictionary remains stable (insertion order). Which code snippet correctly implements this logic?

Practice tests

Scored 10-question sessions with instant feedback and explanations.

PCEP Practice Test 1 — 10 Questions→PCEP Practice Test 2 — 10 Questions→PCEP Practice Test 3 — 10 Questions→PCEP Practice Test 4 — 10 Questions→PCEP Practice Test 5 — 10 Questions→PCEP Practice Exam 1 — 20 Questions→PCEP Practice Exam 2 — 20 Questions→PCEP Practice Exam 3 — 20 Questions→PCEP Practice Exam 4 — 20 Questions→Free PCEP Practice Test 1 — 30 Questions→Free PCEP Practice Test 2 — 30 Questions→Free PCEP Practice Test 3 — 30 Questions→PCEP Practice Questions 1 — 50 Questions→PCEP Practice Questions 2 — 50 Questions→PCEP Exam Simulation 1 — 100 Questions→

Practice by domain

Each domain maps to a weighted exam section. Focus on the domain where you are weakest.

Computer Programming and Python FundamentalsData Types, Variables, Basic I/O and OperatorsControl Flow, Loops, Lists and LogicFunctions, Tuples, Dictionaries and Exceptions

Practice by scenario

Filter questions by type — troubleshooting, exhibit, drag-and-drop, PBQ, ACLs, OSPF, and more.

Browse scenarios→

Continue studying

All Computer Programming and Python Fundamentals setsAll Computer Programming and Python Fundamentals questionsPCEP Practice Hub