Computer Science
Find the Error. Consider the following code, which runs correctly at times but gives error at other times. Find the error and its reason.
Lst1 = [23, 34, 12, 77, 34, 26, 28, 93, 48, 69, 73, 23, 19, 88]
Lst2 = []
print("List1 originally is: ", Lst1)
ch = int(input("Enter 1/2/3 and \
predict which operation was performed?"))
if ch == 1:
Lst1.append(100)
Lst2.append(100)
elif ch == 2:
print(Lst1.index(100))
print(Lst2.index(100))
elif ch == 3:
print(Lst1.pop())
print(Lst2.pop())
Linear Lists
4 Likes
Answer
Lst1 = [23, 34, 12, 77, 34, 26, 28, 93, 48, 69, 73, 23, 19, 88]
Lst2 = []
print("List1 originally is: ", Lst1)
ch = int(input("Enter 1/2/3 and \
predict which operation was performed?"))
if ch == 1:
Lst1.append(100)
Lst2.append(100)
elif ch == 2:
print(Lst1.index(100)) # Error 1
print(Lst2.index(100)) # Error 2
elif ch == 3:
print(Lst1.pop())
print(Lst2.pop()) # Error 3
When the user selects option 1 (ch == 1), the code works correctly, i.e., it appends 100 to both Lst1 and Lst2 at the end. However, errors occur when the user selects option 2 (ch == 2) or option 3 (ch == 3). The errors are as follows:
- Error 1 — Attempting to find the index of 100 in the list
Lst1
usingLst1.index(100)
, an error occurs because 100 is not present inLst1
. - Error 2 — Attempting to find the index of 100 in the list
Lst2
usingLst2.index(100)
, an error occurs because 100 is not present inLst2
. - Error 3 — Attempting to remove an item from an empty list
Lst2
usingLst2.pop()
, an error occurs because there are no items to remove.
Answered By
3 Likes
Related Questions
Predict the output.
b = [[9, 6], [4, 5], [7, 7]] x = b[:2] x.append(10) print(x)
Predict the output.
b = [[9, 6], [4, 5], [7, 7]] x = b[:2] x[1].append(10) print(x)
Suggest the correction for the error(s) in previous question's code.
Find the error. Consider the following code and predict the error(s):
y for y in range(100) if y % 2 == 0 and if y % 5 == 0