PCEP Control Flow, Loops, Lists and Logic • Complete Question Bank
Complete PCEP Control Flow, Loops, Lists and Logic question bank — all 0 questions with answers and detailed explanations.
A developer writes the following code snippet:
for i in range(3):
for j in range(2):
if i == j:break else:
print(i, 'outer')
What is the output?
Given the code: x = [1, 2, 3] y = x y.append(4)
print(x)
What is the output?
Refer to the exhibit.
for i in range(5):
if i == 3:
continue
print(i, end=' ')Refer to the exhibit.
# config.py
allowed_ports = [80, 443, 8080]
def check_port(port):
if port in allowed_ports:
return True
else:
return False
# main.py
from config import check_port
print(check_port(80))You are working on a network automation script that reads a configuration file containing firewall rules. Each rule is a dictionary with keys 'source_ip', 'dest_ip', 'action'. The script must iterate over the rules and print all rules where action is 'allow'. However, the script is not printing any output even though there are allow rules in the file. The code snippet is:
rules = [{'source_ip':'10.0.0.1','dest_ip':'10.0.0.2','action':'allow'},
{'source_ip':'10.0.0.2','dest_ip':'10.0.0.3','action':'deny'}]
for rule in rules:
if rule('action') == 'allow':
print(rule)What is the most likely cause of the problem?
You are writing a script to parse a log file. Each line in the log contains a timestamp and a message separated by a colon. You need to extract only the messages that contain the word 'ERROR'. The script uses a list comprehension to filter lines. However, the script crashes with a 'ValueError: not enough values to unpack' when processing some lines. The code is:
lines = ['2024-01-01 12:00:00: INFO: all good', '2024-01-01 12:01:00: ERROR: something wrong'] errors = [msg for timestamp, msg in line.split(': ') for line in lines if 'ERROR' in msg]
What is the correct fix?
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.
Raised when a function receives an argument of correct type but inappropriate value
Raised when an operation is applied to an object of inappropriate type
Raised when a sequence subscript is out of range
Raised when a mapping key is not found in a dictionary
Raised when division or modulo operation is performed with zero as divisor
Drag a concept onto its matching description — or click a concept then click the description.
A name that references a value in memory
A block of reusable code that performs a specific task
A file containing Python definitions and statements
A collection of modules organized in directories
A blueprint for creating objects
numbers = [5, 2, 8, 1, 9]
for i in range(len(numbers)):
for j in range(0, len(numbers)-i-1):
if numbers[j] > numbers[j+1]:
numbers[j], numbers[j+1] = numbers[j+1], numbers[j]
print(numbers[0])data = [1, 2, 3, 4, 5]
result = []
for x in data:
if x % 2 == 0:
result.append(x * 2)
else:
result.append(x * 3)
print(result[2])count = 0
while count < 5:
count += 1
if count == 3:
continue
print(count, end=' ')Refer to the exhibit.
nums = [1, 2, 3, 4, 5]
for n in nums:
if n == 3:
break
print(n)
else:
print('Done')Refer to the exhibit.
def check(num):
if num > 0:
return 'Positive'
elif num == 0:
return 'Zero'
else:
return 'Negative'
numbers = [10, 0, -5]
results = []
for n in numbers:
results.append(check(n))
print(results)Refer to the exhibit.
data = [{'name': 'Alice', 'age': 30}, {'name': 'Bob', 'age': 25}]
for person in data:
if person['age'] >= 26:
print(person['name'])
elif person['age'] < 20:
print('Too young')
else:
print('Check')numbers = [1, 2, 3, 4, 5]
for i in range(len(numbers)):
if numbers[i] % 2 == 0:
numbers[i] = numbers[i] * 2
print(numbers)x = 10
y = 5
if x > 5 and y < 10:
result = 'A'
elif x == 10 or y == 5:
result = 'B'
else:
result = 'C'
print(result)mylist = [0, 1, 2, 3] print(mylist[1:3])
How many times will the following loop print 'Hi'?
for i in range(3):
print('Hi')A program reverses a string using a while loop. The code is:
text = "hello" reversed_text = "" index = len(text) - 1
while index > 0:
reversed_text += text[index] index -= 1
print(reversed_text)
It prints 'olle' instead of 'olleh'. What is the error?
A student grades system:
score = 85
if score >= 90:
grade = 'A' elif score >= 80: grade = 'B' elif score >= 70: grade = 'C' else: grade = 'F'
What grade is assigned?
A program uses a while loop to find the largest number in a list until a negative number is encountered. What is wrong with this code?
numbers = [3, 7, 2, -1, 5] max_num = 0 i = 0
while numbers[i] >= 0:
if numbers[i] > max_num:max_num = numbers[i] i += 1
print(max_num)
What is the output of the code?
numbers = [1, 2, 3, 4] result = [x**2 for x in numbers if x % 2 == 0]
print(result)
What does the following code print?
x = 10
if x > 5:
if x > 15:
print("A")else:
print("B")else:
print("C")A data analyst is processing a large dataset of customer transactions. The dataset is stored as a list of dictionaries, each with keys 'amount' and 'date'. The analyst needs to compute the total revenue for 2024. They write:
total = 0
for t in transactions:
if t['date'].year == 2024:total += t['amount']
They then run it and get a KeyError: 'date'. After inspection, they notice that some records have a 'Date' key (capital D) instead. The analyst wants to fix this without modifying the data. Which approach will correctly sum amounts regardless of key case?
A developer is writing a simple number guessing game. The computer picks a random number between 1 and 100, and the user keeps guessing until correct. The developer implements:
secret = random.randint(1,100) guess = 0
while guess != secret:
guess = int(input("Guess: "))
if guess == secret:
print("Correct!")else:
print("Wrong, try again.")The game works, but the developer notices that if the user enters something that is not an integer, the program crashes. Which modification ensures the program handles non-integer input gracefully?
A network administrator uses a Python script to analyze firewall logs. The script reads a CSV file with columns 'src_ip', 'dst_ip', 'action', 'time'. It needs to build a list of source IPs that have been blocked more than 3 times. The current code:
blocked_count = {} blocked_ips = []
for row in logs:
if row['action'] == 'block':
if row['src_ip'] in blocked_count:blocked_count[row['src_ip']] += 1 else: blocked_count[row['src_ip']] = 1
for ip, count in blocked_count.items():
if count > 3:blocked_ips.append(ip)
The script runs correctly but slowly on large logs. The administrator wants to optimize it. Which change would most improve performance?
A junior developer writes a Python script to sum all numbers greater than 10 from a list. The code is:
numbers = [5, 12, 8, 15, 3] total = 0
for num in numbers:
if num > 10:total = total + 1
print(total)
The output is 2, but the expected sum is 27 (12+15). Which change will produce the correct output?
A data analyst writes a Python script to double each element in a matrix without altering the original. The code is:
original = [[1,2,3],[4,5,6]] copy = original
for i in range(len(original)):
for j in range(len(original[i])):copy[i][j] *= 2
print(original)
The output shows [[2,4,6],[8,10,12]], meaning the original was also changed. Which single modification to the line 'copy = original' ensures the original matrix remains unchanged?
Python 3.11.0 (default, Oct 24 2022, 14:48:10) [GCC 11.2.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>> x = [1, 2, 3] >>> for i in range(len(x)): ... x.insert(i, x.pop()) ... >>> x [1, 2, 3]
>>> nums = [0, 1, 2, 3, 4, 5] >>> for i in range(len(nums)): ... if nums[i] % 2 == 0: ... nums.remove(nums[i]) ... >>> nums [1, 3, 5]
>>> data = [[1,2], [3,4], [5,6]] >>> result = [] >>> for row in data: ... for item in row: ... if item % 2 == 0: ... break ... else: ... result.append(row) >>> result [[1,2], [5,6]]
>>> x = 0 >>> while x < 5: ... x += 1 ... if x == 3: ... continue ... print(x, end=' ') 1 2 4 5
>>> my_list = [1, 2, 3, 4, 5] >>> for i in range(len(my_list)): ... if my_list[i] % 2 == 0: ... my_list[i] = my_list[i] ** 2 ... else: ... my_list[i] = my_list[i] ** 3 >>> my_list [1, 4, 27, 16, 125]