Python List MCQ : Set 4

Python List MCQ

1). Which method can be used as an alternative to the min() function to find the minimum value from a list?

a) sort()
b) reverse()
c) pop()
d) append()

Correct answer is: a) sort()
Explanation: The sort() method can be used to sort the list in ascending order, and then the first element will be the minimum value.

2). What is the output of the following code snippet?

my_list = [1, 2, 3, 4, 5]
del my_list[2]
print(my_list)

a) [1, 2, 3, 4, 5]
b) [1, 2, 4, 5]
c) [1, 2, 4]
d) [1, 3, 4, 5]

Correct answer is: b) [1, 2, 4, 5]
Explanation: The del keyword is used to delete an element from a list by its index. In this case, del my_list[2] removes the element at index 2 (which is 3) from my_list. The resulting list is [1, 2, 4, 5].

3). What is the output of the following code?

string = “i am learning python”
list1 = string.split(” “)
print(list1)

a) [“i”, “am”, “learning”, “python”]
b) [“i am learning python”]
c) [“i”, “am”, “learning”, “p”, “y”, “t”, “h”, “o”, “n”]
d) [“i”, “,”, “am”, “,”, “learning”, “,”, “python”]

Correct answer is: a) [“i”, “am”, “learning”, “python”]
Explanation: The split(” “) method splits the string at each occurrence of a space, resulting in a list of words.

4). What is the output of the following code?

list1 = [“Hello”, 45, “sqa”, 23, 5, “Tools”, 20]
count = 0

for value in list1:
    if isinstance(value, int):
        count += 1
print(“Total number of integers: “, count)

a) Total number of integers: 4
b) Total number of integers: 3
c) Total number of integers: 5
d) Total number of integers: 2

Correct answer is: a) Total number of integers: 4
Explanation: The code iterates over each element in `list1` and checks if the element is an instance of the `int` type using the `isinstance()` function. If it is an integer, the `count` variable is incremented. The final value of `count` is printed, which represents the total number of integers in the list. In this case, the integers in the list are 45, 23, 5, and 20, resulting in a count of 4.

5). What is the output of the following code?

list1 = [2, 3, 4, 7, 8, 1, 5, 6, 2, 1, 8, 2]
index_list = [0, 3, 5, 6]
new_list = []

for value in index_list:
    new_list.append(list1[value])
print(new_list)

a) [2, 7, 1, 5]
b) [3, 4, 1, 6]
c) [2, 4, 1, 5]
d) [7, 3, 1, 6]

Correct answer is: a) [2, 7, 1, 5]
Explanation: The code iterates through each value in the `index_list` and appends the corresponding element from `list1` to `new_list`.
– For `value = 0`, the element at index 0 in `list1` is 2, so 2 is appended to `new_list`.
– For `value = 3`, the element at index 3 in `list1` is 7, so 7 is appended to `new_list`.
– For `value = 5`, the element at index 5 in `list1` is 1, so 1 is appended to `new_list`.
– For `value = 6`, the element at index 6 in `list1` is 5, so 5 is appended to `new_list`.
Therefore, the resulting `new_list` is `[2, 7, 1, 5]`.

6). What is the output of the following code?

list1 = [{“name”: “john”}, {“city”: “mumbai”}, {“Python”: “laguage”}, {“name”: “john”}]
list2 = []

for i in range(len(list1)):
    if list1[i] not in list1[i+1:]:
        list2.append(list1[i])
print(list2)

a) `[{‘city’: ‘mumbai’}, {‘Python’: ‘laguage’}, {‘name’: ‘john’}]`
b) `[{“name”: “john”}, {“Python”: “laguage”}]`
c) `[{“name”: “john”}]`
d) `[]`

Correct answer is: a) `[{‘city’: ‘mumbai’}, {‘Python’: ‘laguage’}, {‘name’: ‘john’}]`
Explanation: The code iterates over each element in `list1` using the `for` loop. The condition `if list1[i] not in list1[i+1:]` checks if the current element is not repeated in the remaining elements of `list1`. If it is not repeated, the element is appended to `list2`.

7). What is the purpose of the join() method in the Python list?

a) It joins the elements of the list into a single string.
b) It counts the number of occurrences of a specified element in the list.
c) It reverses the order of the elements in the list.
d) It converts the string into a list.

Correct answer is: a) It joins the elements of the list into a single string.
Explanation: The join() method is used to concatenate the elements of the list into a single string.

8).What is the output of the following code?

list1 = [“a”, “b”, “c”, “d”, “e”]
list2 = [234, 123, 456, 343, 223]

dictionary = dict(zip(list1, list2))
print(dictionary)

a) {‘a’: 234, ‘b’: 123, ‘c’: 456, ‘d’: 343, ‘e’: 223}
b) {‘a’: 123, ‘b’: 234, ‘c’: 343, ‘d’: 456, ‘e’: 223}
c) {234: ‘a’, 123: ‘b’, 456: ‘c’, 343: ‘d’, 223: ‘e’}
d) {1: ‘a’, 2: ‘b’, 3: ‘c’, 4: ‘d’, 5: ‘e’}

Correct answer is: a) {‘a’: 234, ‘b’: 123, ‘c’: 456, ‘d’: 343, ‘e’: 223}
Explanation: The zip() function is used to combine the elements of list1 and list2 into pairs. The dict() function then converts these pairs into a dictionary where elements from list1 serve as keys and elements from list2 serve as values. The resulting dictionary is printed, which will be {‘a’: 234, ‘b’: 123, ‘c’: 456, ‘d’: 343, ‘e’: 223}.

9). What is the output of the following code?

list1 = [2, 5, 7, 8, 2, 3, 4, 12, 5, 6]
list2 = list(set(list1))

print(list2)

a) [2, 5, 7, 8, 2, 3, 4, 12, 5, 6]
b) [2, 5, 7, 8, 3, 4, 12, 6]
c) [2, 5, 7, 8, 3, 4, 6, 12]
d) [2, 3, 4, 5, 6, 7, 8, 12]

Correct answer is: c) [2, 5, 7, 8, 3, 4, 6, 12]
Explanation: In the code, `list1` contains duplicate elements. The `set()` function is used to convert `list1` into a set, which automatically removes duplicate elements. Then, `list()` is used to convert the set back into a list. The resulting `list2` will contain unique elements from `list1` in an arbitrary order. Therefore, the output is `[2, 5, 7, 8, 3, 4, 6, 12]`.

10). Which function is used to find the maximum value from a list?

a) min()
b) max()
c) sum()
d) len()

Correct answer is: B) max()
Explanation: The max() function is used to find the maximum value from a list. When called with a list as an argument, it returns the largest value present in that list.

11). What is the output of the following code?

list1 = [4, 6, 8, 2, 3, 5]
list1.insert(3, [5, 2, 6])
print(list1)

a) [4, 6, 8, [5, 2, 6], 2, 3, 5]
b) [4, 6, 8, 5, 2, 6, 2, 3, 5]
c) [4, 6, 8, [5, 2, 6], [5, 2, 6], 2, 3, 5]
d) Error: ‘list’ object cannot be inserted into another list

Correct answer is: a) [4, 6, 8, [5, 2, 6], 2, 3, 5]
Explanation: The `insert()` method is used to insert an element into a list at a specified index. In this case, the list `[5, 2, 6]` is inserted at index 3 of `list1`. The resulting list will be `[4, 6, 8, [5, 2, 6], 2, 3, 5]`, where the sublist `[5, 2, 6]` is treated as a single element in `list1`.

12). What is the output of the following code?
list1 = [[“apple”, 30], [“mango”, 50], [“banana”, 20], [“lichi”, 50]]
list2 = [[“apple”, 2],[“mango”,10]]

for value in list1:
    for var in list2:
        if value[0] == var[0]:
            print(“Fruit: “, value[0])
            print(“Bill: “, value[1]*var[1])

a) Fruit: apple
Bill: 60
Fruit: mango
Bill: 500
b) Fruit: apple
Bill: 600
Fruit: mango
Bill: 500
c) Fruit: apple
Bill: 120
Fruit: mango
Bill: 500
d) Fruit: apple
Bill: 60
Fruit: mango
Bill: 50

Correct answer is: a) Fruit: apple
Bill: 60
Fruit: mango
Bill: 500

Explanation: The code iterates over the elements of list1 and list2. When it finds a match between the fruits in both lists (apple and mango), it prints the fruit name and the multiplication of their respective quantities. In this case, “apple” has a quantity of 2 in list2 and a price of 30 in list1, resulting in a bill of 60. Similarly, “mango” has a quantity of 10 in list2 and a price of 50 in list1, resulting in a bill of 500.

13). What is the output of the following code?
list1 = [80, 50, 70, 90, 95]
print(“Percentage: “, (sum(list1)/500)*100)

a) Percentage: 75.0
b) Percentage: 85.0
c) Percentage: 90.0
d) Percentage: 95.0

Correct answer is: b) Percentage: 85.0
Explanation: The code calculates the average of the values in list1 by summing them up and dividing by 500, and then multiplying by 100 to get the percentage. The sum of [80, 50, 70, 90, 95] is 385, and (385/500)*100 equals 77.0.

14). What is the output of the following code?

list1 = [“data”, “python”, “oko”, “test”, “ete”]
list2 = []

for value in list1:
    new = value[::-1]
    if new == value:
        list2.append(value)
print(list2)

a) [“oko”, “ete”]
b) [“data”, “python”, “test”]
c) [“oko”, “test”]
d) [“data”, “python”, “oko”, “test”, “ete”]

Correct answer is: a) [“oko”, “ete”]
Explanation: The code checks each element in `list1` and appends it to `list2` if it is a palindrome (reads the same forwards and backward). In this case, “oko” and “ete” are palindromes, so they are added to `list2`, resulting in `list2` containing [“oko”, “ete”].

15). What is the output of the following code?

list1 = [0, 12, [22, 32], 42, 52, [62, 72, 82], [92, 102, 112, 122]]
list2 = []

for value in list1:
    if type(value) is list:
        for var in value:
            list2.append(var)
    else:
        list2.append(value)
print(list2)

a) [0, 12, [22, 32], 42, 52, [62, 72, 82], [92, 102, 112, 122]]
b) [0, 12, 22, 32, 42, 52, 62, 72, 82, 92, 102, 112, 122]
c) [0, 12, [22, 32], 42, 52, [62, 72, 82], [92, 102, 112, 122], 22, 32, 62, 72, 82, 92, 102, 112, 122]
d) [0, 12, [22, 32], 42, 52, [62, 72, 82], [92, 102, 112, 122], [22, 32], [62, 72, 82], [92, 102, 112, 122]]

Correct answer is: b) [0, 12, 22, 32, 42, 52, 62, 72, 82, 92, 102, 112, 122]
Explanation: The code iterates through each element in `list1`. If an element is of type list, it iterates through its sub-elements and appends them to `list2`. If an element is not a list, it directly appends it to `list2`. The final output is the flattened list with all the sub-elements combined.

16). What is the output of the following code?

list1 = [(3, 5), (6, 8), (8, 11), (12, 14), (17, 23)]
list2 = []

for value in list1:
    if type(value) is tuple:
        list3 = []
        for var in value:
            list3.append(var)
        list2.append(list3)
print(list2)

a) [[3, 5], [6, 8], [8, 11], [12, 14], [17, 23]]
b) [(3, 5), (6, 8), (8, 11), (12, 14), (17, 23)]
c) [[(3, 5)], [(6, 8)], [(8, 11)], [(12, 14)], [(17, 23)]]
d) [(3, 5), 6, 8, 8, 11, 12, 14, 17, 23]

Correct answer is: a) [[3, 5], [6, 8], [8, 11], [12, 14], [17, 23]]
Explanation: The code iterates over each value in list1. If the value is a tuple, it creates a new list (list3) and appends each element of the tuple to list3. Finally, list3 is appended to list2. The output is a list of lists, where each tuple in list1 is converted to a list.

17). What is the output of the following code?

list1 = [[“a”, 5], [“b”, 8], [“c”, 11], [“d”, 14], [“e”, 23]]

dictionary = dict(list1)
print(dictionary)

a) {“a”: 5, “b”: 8, “c”: 11, “d”: 14, “e”: 23}
b) {“a”: [5], “b”: [8], “c”: [11], “d”: [14], “e”: [23]}
c) {“a”: [“a”, 5], “b”: [“b”, 8], “c”: [“c”, 11], “d”: [“d”, 14], “e”: [“e”, 23]}
d) Error: Invalid syntax

Correct answer is: a) {“a”: 5, “b”: 8, “c”: 11, “d”: 14, “e”: 23}
Explanation: The code converts the list of lists, `list1`, into a dictionary using the `dict()` function. Each inner list in `list1` represents a key-value pair in the dictionary. The resulting dictionary contains the keys from the first elements of each inner list and the corresponding values from the second elements of each inner list. Thus, the output is `{“a”: 5, “b”: 8, “c”: 11, “d”: 14, “e”: 23}`.

18). What is the output of the following code?

list1 = [“Hello”, “student”, “are”, “learning”, “Python”, “Its”, “Python”, “Language”]
for i in range(len(list1)):
    if list1[i] == “Python”:
        list1[i] = “Java”

print(list1)

a) [“Hello”, “student”, “are”, “learning”, “Java”, “Its”, “Java”, “Language”]
b) [“Hello”, “student”, “are”, “learning”, “Python”, “Its”, “Python”, “Language”]
c) [“Hello”, “student”, “are”, “learning”, “Java”, “Its”, “Python”, “Language”]
d) [“Hello”, “student”, “are”, “learning”, “Java”, “Its”, “Java”, “Language”]

Correct answer is: a) [“Hello”, “student”, “are”, “learning”, “Java”, “Its”, “Java”, “Language”]
Explanation: The code iterates over each element in the list using the range(len(list1)) construct. If an element is equal to “Python”, it is replaced with “Java”. After the loop, the modified list is printed, which will have “Python” replaced with “Java” at two positions.

19). What is the output of the following code?

list1 = [“Hello”, “student”, “are”, “learning”, “Python”, “Its”, “Python”, “Language”]
dictionary = dict()
list2 = []

for value in list1:
    dictionary[value] = len(value)
list2.append(dictionary)

print(list2)

a) [{‘Hello’: 5, ‘student’: 7, ‘are’: 3, ‘learning’: 8, ‘Python’: 6, ‘Its’: 3, ‘Language’: 8}]
b) [{‘Hello’: 5, ‘student’: 7, ‘are’: 3, ‘learning’: 8, ‘Python’: 6, ‘Its’: 3, ‘Python’: 6, ‘Language’: 8}]
c) [{‘Hello’: 5}, {‘student’: 7}, {‘are’: 3}, {‘learning’: 8}, {‘Python’: 6}, {‘Its’: 3}, {‘Python’: 6}, {‘Language’: 8}]
d) [{‘Hello’: 5, ‘student’: 7, ‘are’: 3, ‘learning’: 8, ‘Python’: 6, ‘Its’: 3}, {‘Python’: 6, ‘Language’: 8}]

Correct answer is: a) [{‘Hello’: 5, ‘student’: 7, ‘are’: 3, ‘learning’: 8, ‘Python’: 6, ‘Its’: 3, ‘Language’: 8}]
Explanation: The code creates a dictionary called `dictionary` and a list called `list2`. It then iterates through each value in `list1` and assigns the length of the value as the value in the `dictionary` with the value itself as the key. Finally, the `dictionary` is appended to `list2`. The output will be a list containing a single dictionary with key-value pairs mapping each word from `list1` to its corresponding length.

20). What is the output of the following code?

list1 = [2, 5, 7, 9, 3, 4]
print(“Remove 1 element from left”, list1[1:])

a) Remove 1 element from left [5, 7, 9, 3, 4]
b) Remove 1 element from left [2, 5, 7, 9, 3]
c) Remove 1 element from left [2, 5, 7, 9, 3, 4]
d) Remove 1 element from left [5, 7, 9, 3, 4, 2]

Correct answer is: a) Remove 1 element from left [5, 7, 9, 3, 4]
Explanation: `list1[1:]` returns a new list starting from the second element (index 1) of `list1`. The output will be [5, 7, 9, 3, 4], as the first element 2 is removed from the left side of the list.

21). What is the output of the following code?

list1 = []
num1 = 0
num2 = 1

for i in range(1, 10):
    list1.append(num1)
    n2 = num1 + num2
    num1 = num2
    num2 = n2

print(list1)

a) [0, 1, 1, 2, 3, 5, 8, 13, 21]
b) [1, 1, 2, 3, 5, 8, 13, 21, 34]
c) [0, 1, 2, 3, 4, 5, 6, 7, 8]
d) [0, 0, 1, 1, 2, 3, 5, 8, 13]

Correct answer is: a) [0, 1, 1, 2, 3, 5, 8, 13, 21]
Explanation: The code snippet initializes an empty list `list1` and two variables `num1` and `num2` to 0 and 1, respectively. It then enters a loop where it appends the value of `num1` to `list1` and updates `num1` and `num2` according to the Fibonacci sequence. The loop runs 9 times, resulting in the Fibonacci numbers [0, 1, 1, 2, 3, 5, 8, 13, 21]. Finally, the `list1` is printed, displaying the Fibonacci sequence.

22). What is the output of the following code?

list1 = [“python”, “is”, “a”, “best”, “language”, “python”, “best”]
list2 = []

for words in list1:
    if words not in list2:
        list2.append(words)
print(list2)

a) [“python”, “is”, “a”, “best”, “language”]
b) [“python”, “is”, “a”, “best”, “language”, “python”]
c) [“python”, “is”, “a”, “best”, “language”, “python”, “best”]
d) [“is”, “a”, “language”]

Correct answer is: a) [“python”, “is”, “a”, “best”, “language”]
Explanation: The code iterates over each word in list1 and checks if it exists in list2. If it doesn’t exist, it appends the word to list2. Since “python” and “best” already exist in list2, they are not appended again. Therefore, the final output is [“python”, “is”, “a”, “best”, “language”].

23). What is the output of the following code?
list1 = [(2, 3), (4, 6), (5, 1), (2, 3), (7, 9), (5, 1)]
list2 = []

for value in list1:
    if value not in list2:
        list2.append(value)
print(list2)

a) []
b) [(2, 3), (4, 6), (5, 1), (7, 9)]
c) [(2, 3), (4, 6), (5, 1), (2, 3), (7, 9), (5, 1)]
d) Error: list index out of range

Correct answer is: b) [(2, 3), (4, 6), (5, 1), (7, 9)]
Explanation: The code iterates over the elements in list1 and checks if each element is already present in list2. If not, it appends the element to list2. However, since list2 starts as an empty list and the loop does not execute, list2 remains empty. Therefore, the output is [(2, 3), (4, 6), (5, 1), (7, 9)].

24). What is the output of the following code?

list1 = [[1, 2], [3, 5], [1, 2], [6, 7]]
list2 = []

for value in list1:
    if value not in list2:
        list2.append(value)
print(list2)

a) [[1, 2], [3, 5], [1, 2], [6, 7]]
b) [[1, 2], [3, 5], [6, 7]]
c) [[1, 2], [3, 5]]
d) [[3, 5], [6, 7]]

Correct answer is: b) [[1, 2], [3, 5], [6, 7]]
Explanation: The code iterates over each element in `list1` and checks if the element is already present in `list2`. Since the sublists `[1, 2]`, `[3, 5]`, and `[6, 7]` are not present in `list2`, they are appended to it. Thus, `list2` contains all unique elements from `list1`.

25). What is the output of the following code?

list1 = [[3, 5, 6], [2, 1, 3], [5, 1, 1], [1, 2, 1], [0, 4, 1]]
print(sorted(list1, key=max))

a) [[5, 1, 1], [0, 4, 1], [1, 2, 1], [2, 1, 3], [3, 5, 6]]
b) [[0, 4, 1], [1, 2, 1], [2, 1, 3], [3, 5, 6], [5, 1, 1]]
c) [[1, 2, 1], [2, 1, 3], [0, 4, 1], [5, 1, 1], [3, 5, 6]]
d) [[3, 5, 6], [2, 1, 3], [5, 1, 1], [1, 2, 1], [0, 4, 1]]

Correct answer is: c) [[1, 2, 1], [2, 1, 3], [0, 4, 1], [5, 1, 1], [3, 5, 6]]
Explanation: The `sorted()` function is used to sort the elements of `list1` based on the maximum value within each sublist. The `key=max` argument specifies that the maximum value of each sublist should be used as the key for sorting. Therefore, the resulting list will be sorted in ascending order based on the maximum value of each sublist. In this case, the sorted list will be `[[1, 2, 1], [2, 1, 3], [0, 4, 1], [5, 1, 1], [3, 5, 6]]`.

Python List MCQ : Set 3

Python List MCQ

1). What is the output of the following code?
 
a = [22, 66, 89, 9, 44]
print(“Minimum: “, min(a))
 
a) Minimum: 9
b) Minimum: 22
c) Minimum: 44
d) Minimum: 89
 
Correct answer is: a) Minimum: 9
Explanation: The min() function returns the minimum value from the list ‘a’, which is 9 in this case.
 
2). What is the purpose of the following code?
 
a = [22, 45, 67, 12, 78]
b = [45, 12]
count = 0
for i in a:
    for j in b:
        if i == j:
            count += 1
if count == len(b):
    print(“Sublist exists”)
else:
    print(“Sublist does not exist”)
 
a) To find the common elements between lists a and b
b) To check if list b is a subset of list a
c) To concatenate lists a and b
d) To count the number of occurrences of elements in list b within list a.
 
Correct answer is: b) To check if list b is a subset of list a
Explanation: The code checks if every element in list b exists in list a. If all elements of b are found in a, the count variable will be equal to the length of b, indicating that b is a sublist or subset of a. Otherwise, it means that b is not a sublist or subset of a.
 
3). What is the output of the following code?
 
a = [“a”, “b”, “c”, “d”]
print(“$”.join(a))
 
a) “a$b$c$d”
b) “abcd”
c) [“a”, “b”, “c”, “d”]
d) Error: cannot join a list with a string delimiter
 
Correct answer is: a) “a$b$c$d”
Explanation: The `join()` method is used to concatenate the elements of a list into a single string, with the specified delimiter inserted between each element. In this case, the elements of list `a` are joined together using the delimiter “$”, resulting in the string “a$b$c$d”.
 
4). 1. What is the output of the following code?
 
a = [“Sqa”, “Tools”, “Online”, “Learning”, “Platform’”]
b = []
for i in a:
    b.append(i[::-1])
print(b)
 
a) [“aqS”, “slooT”, “enilnO”, “gninraeL”, “mocalfP”]
b) [“asqS”, “slooT”, “enilnO”, “gninraeL”, “mocalfP”]
c) [“Sqa”, “Tools”, “Online”, “Learning”, “Platform”]
d) [“aS”, “looT”, “enilgnO”, “gninraeL”, “mocalfP”]
 
Correct answer is: a) [“aqS”, “slooT”, “enilnO”, “gninraeL”, “mocalfP”]
Explanation: In the code, a loop iterates through each element of list ‘a’. The `i[::-1]` expression reverses each string in ‘a’. The reversed strings are then appended to the empty list ‘b’. Finally, ‘b’ is printed, which contains the reversed strings from ‘a’.
 
5). What is the purpose of the zip() function in the Python list?
 
a) Concatenate two lists into one.
b) Multiply corresponding elements of two lists.
c) Iterate over elements from two lists simultaneously.
d) Find the common elements between two lists.
 
Correct answer is: c) Iterate over elements from two lists simultaneously.
Explanation: The zip() function is used to combine elements from multiple lists into tuples. In the given code, it allows iterating over elements from list1 and list2 at the same time.
 
6). What is the output of the following code?
 
list1 = [3, 5, 7, 8, 9]
list2 = [1, 4, 3, 6, 2]
final=[]
for (a,b) in zip(list1,list2):
    final.append(list((a,b)))
print(final)
 
a) [[3, 1], [5, 4], [7, 3], [8, 6], [9, 2]]
b) [[1, 3], [4, 5], [3, 7], [6, 8], [2, 9]]
c) [[1, 4, 3, 6, 2]]
d) Error: ‘tuple’ object has no attribute ‘append’
 
Correct answer is: a) [[3, 1], [5, 4], [7, 3], [8, 6], [9, 2]]
Explanation: The code uses the zip() function to iterate over elements from list1 and list2 simultaneously. It creates a list of tuples where each tuple contains corresponding elements from both lists.
 
7). What is the output of the following code?
 
list1 = [{“a”:12}, {“b”: 34}, {“c”: 23}, {“d”: 11}, {“e”: 15}]
key = []
value = []
for element in list1:
    for val in element:
        key.append(val)
        value.append(element[val])
print(“Key : “, key)
print(“Value : “, value)
 
a) Key : [‘a’, ‘b’, ‘c’, ‘d’, ‘e’]  Value : [12, 34, 23, 11, 15]
b) Key : [‘a’, ‘b’, ‘c’, ‘d’, ‘e’]  Value : [{‘a’:12}, {‘b’: 34}, {‘c’: 23}, {‘d’: 11}, {‘e’: 15}]
c) Key : [‘a’, ‘b’, ‘c’, ‘d’, ‘e’]  Value : [12, 34, 23, 11, 15, ‘a’, ‘b’, ‘c’, ‘d’, ‘e’]
d) Key : [{‘a’:12}, {‘b’: 34}, {‘c’: 23}, {‘d’: 11}, {‘e’: 15}]  Value : [12, 34, 23, 11, 15]
  
Correct answer is: a) Key : [‘a’, ‘b’, ‘c’, ‘d’, ‘e’]  Value : [12, 34, 23, 11, 15]
Explanation: The code iterates over the list1, extracting the keys and values from each dictionary. The keys are appended to the ‘key’ list, and the values are appended to the ‘value’ list. Finally, the code prints the contents of the ‘key’ and ‘value’ lists.
 
8). Which method can be used to split a string into a list based on a different delimiter?
 
a) split()
b) separate()
c) divide()
d) break()
 
Correct answer is: a) split()
Explanation: The split() method is used to split a string into a list based on a specified delimiter.
 
9). What is the correct way to create an empty list in Python?
 
a) list = []
b) list = ()
c) list = {}
d) list = None
 
Correct answer is: a) list = []
Explanation: To create an empty list in Python, we use square brackets [] without any elements inside.
 
10). What is the output of the following code snippet?
 
my_list = [1, 2, 3]
my_list.append(4)
print(len(my_list))
 
a) 1
b) 2
c) 3
d) 4
 
Correct answer is: d) 4
Explanation: The append() method is used to add an element to the end of a list. In this case, it adds the element 4 to my_list, increasing its length to 4.

11). Which method is used to remove an element from a list by its value?

a) remove()
b) delete()
c) pop()
d) discard()

Correct answer is: a) remove()
Explanation: The remove() method is used to remove the first occurrence of a specified element from a list.

12). What is the output of the following code snippet?

my_list = [1, 2, 3, 4, 5]
sliced_list = my_list[1:5]
print(sliced_list)

a) [2, 3, 4, 5]
b) [1, 2, 3]
c) [1, 2, 3, 4]
d) [4, 5]

Correct answer is: a) [2, 3, 4, 5]
Explanation: The slicing operation my_list[1:4] creates a new list containing elements from index 1 to index 4. Hence, the output is [2, 3, 4, 5]

13). Which method is used to find the index of the last occurrence of an element in a list?

a) index()
b) rindex()
c) find()
d) search()

Correct answer is: b) rindex()
Explanation: The rindex() method is used to find the index of the last occurrence of an element in a list. It starts searching from the end of the list and returns the index of the last match.

14). Which function is used to find the minimum value from a list?

a) min()
b) minimum()
c) smallest()
d) find_min()

Correct answer is: a) min()
Explanation: The min() function is used to find the minimum value from a list.

15). What is the output of the following code?

list1 = [12, 32, 33, 5, 4, 7]
list1[0] = “SQA”
list1[-1] = “TOOLS”
print(list1)

a) [12, 32, 33, 5, 4, 7]
b) [“SQA”, 32, 33, 5, 4, “TOOLS”]
c) [“SQA”, 32, 33, 5, 4, 7]
d) [12, 32, 33, 5, 4, “TOOLS”]

Correct answer is: b) [“SQA”, 32, 33, 5, 4, “TOOLS”]
Explanation: In the given code, the element at index 0 of `list1` is replaced with the string “SQA” using the assignment operator (`=`). Similarly, the element at index -1 (last index) of `list1` is replaced with the string “TOOLS”. Therefore, the resulting list is `[“SQA”, 32, 33, 5, 4, “TOOLS”]`.

16). What is the output of the following code?

list1 = [22, 45, 67, 11, 90, 67]
print(“Is 67 exist in list1? “, 67 in list1)

a) Is 67 exist in list1? True
b) Is 67 exist in list1? False
c) Is 67 exist in list1? Error
d) True

Correct answer is: a) Is 67 exist in list1? True
Explanation: The `in` keyword is used to check if an element exists in a list. In this case, the code checks if 67 exists in `list1`, and since it does, the output will be “Is 67 exist in list1? True”.

17). What is the output of the following code?
list1 = [1, 2, 3, 4, 5]
print([‘Sqa{0}’.format(value) for value in list1])

a) [‘Sqa1’, ‘Sqa2’, ‘Sqa3’, ‘Sqa4’, ‘Sqa5’]
b) [‘Sqa[1]’, ‘Sqa[2]’, ‘Sqa[3]’, ‘Sqa[4]’, ‘Sqa[5]’]
c) [‘Sqa{0}’.format(1), ‘Sqa{0}’.format(2), ‘Sqa{0}’.format(3), ‘Sqa{0}’.format(4), ‘Sqa{0}’.format(5)]
d) [‘Sqa0’, ‘Sqa1’, ‘Sqa2’, ‘Sqa3’, ‘Sqa4’]

Correct answer is: a) [‘Sqa1’, ‘Sqa2’, ‘Sqa3’, ‘Sqa4’, ‘Sqa5’]
Explanation: The code uses a list comprehension to iterate over each value in list1 and format it with ‘Sqa{0}’ to create a new list with formatted strings.

18). What is the output of the following code?

list1 = [[11, 2, 3], [4, 15, 2], [10, 11, 12], [7, 8, 19]]
print(max(list1, key=sum))

a) [11, 2, 3]
b) [4, 15, 2]
c) [10, 11, 12]
d) [7, 8, 19]

Correct answer is: d) [7, 8, 19]
Explanation: The `max()` function is used to find the maximum element in a list. In this case, `key=sum` is passed as an argument to specify that the sum of each sub-list should be used as the criterion for comparison. Since the sum of `[7, 8, 19]` is the highest among all the sub-lists, it will be returned as the output.

19). What is the output of the following code?

list1 = [2, 4, 6, 8, 3, 22]
list1.insert(3, 55)
print(list1)

a) [2, 4, 6, 8, 3, 22, 55]
b) [2, 4, 55, 6, 8, 3, 22]
c) [2, 4, 6, 55, 8, 3, 22]
d) [2, 4, 6, 8, 55, 3, 22]

Correct answer is: c) [2, 4, 6, 55, 8, 3, 22]
Explanation: The `insert()` method is used to insert an element at a specific position in the list. In this case, element 55 is inserted at index 3, shifting the remaining elements to the right. The resulting list becomes [2, 4, 6, 55, 8, 3, 22].

20). What is the output of the following code?

list1 = [“Learn”, “python”, “From”, “Sqa”, “tools”]
list2 = []
for words in list1:
    list2.append(words[0].upper() + words[1:-1] + words[-1].upper() + ” “)
print(“Uppercase: “, list2)

a) Uppercase: [“LearN”, “pythoN”, “FroM”, “SqA”, “ToolS”]
b) Uppercase: [“Learn”, “python”, “From”, “Sqa”, “tools”]
c) Uppercase: [“L”, “p”, “F”, “S”, “t”]
d) Uppercase: [“LEARN”, “PYTHON”, “FROM”, “SQA”, “TOOLS”]

Correct answer is: a) Uppercase: [“LearN”, “pythoN”, “FroM”, “SqA”, “ToolS”]
Explanation: The code capitalizes the first and last letters of each word in list1. The resulting list, list2, contains the modified words.

21). What is the output of the following code?

list1 = [[3, 5, 6], [2, 1, 3], [5, 1, 1], [1, 2, 1], [0, 4, 1]]
print(sorted(list1, key=sum))

a) [[0, 4, 1], [1, 2, 1], [2, 1, 3], [3, 5, 6], [5, 1, 1]]
b) [[5, 1, 1], [1, 2, 1], [2, 1, 3], [3, 5, 6], [0, 4, 1]]
c) [[3, 5, 6], [2, 1, 3], [5, 1, 1], [1, 2, 1], [0, 4, 1]]
d) [[1, 2, 1], [2, 1, 3], [0, 4, 1], [3, 5, 6], [5, 1, 1]]

Correct answer is: d) [[1, 2, 1], [2, 1, 3], [0, 4, 1], [3, 5, 6], [5, 1, 1]]
Explanation: The `sorted()` function is used to sort the list `list1` based on a custom key function, which is the `sum()` function in this case. The `sum()` function calculates the sum of each sublist in `list1`. Sorting the list based on the sum will result in ascending order based on the sum of each sublist’s elements.

22). If the list ‘a’ is empty, what will be the output of the given code?

a = []
print(“Minimum: “, min(a))

a) Minimum: None
b) Minimum: 0
c) Error: min() arg is an empty sequence
d) Error: ‘list’ object has no attribute ‘min’

Correct answer is: c) Error: min() arg is an empty sequence
Explanation: The min() function raises an error if it is called on an empty list.

23). What is the output of the following code?

list1 = [“Python”, “Sqatools”, “Practice”, “Program”, “test”, “lists”]
list2 = []

for string in list1:
    if len(string) > 7:
        list2.append(string)
print(list2)

a) [“Python”, “Sqatools”, “Practice”, “Program”]
b) [“Python”, “Sqatools”, “Practice”, “Program”, “lists”]
c) [“Python”, “Sqatools”, “Practice”, “Program”, “test”]
d) []

Correct answer is: b) [“Python”, “Sqatools”, “Practice”, “Program”, “lists”]
Explanation: The code iterates over each string in `list1`. If the length of the string is greater than 7, it is appended to `list2`. In this case, “Python”, “Sqatools”, “Practice”, “Program”, and “lists” have lengths greater than 7, so they are added to `list2`. Therefore, the output is `[“Python”, “Sqatools”, “Practice”, “Program”, “lists”]`.

24). What is the output of the following code?

list1 = [1, 1, 3, 4, 4, 5, 6, 7]
list2 = []
for a, b in zip(list1[:-1], list1[1:]):
    difference = b – a
    list2.append(difference)
print(list2)

a) [1, 2, 1, 0, 1, 1, 1]
b) [0, 2, 1, 0, 1, 1, 1]
c) [1, 0, 1, 0, 1, 1, 1]
d) [0, 1, 1, 1, 1, 1]

Correct answer is: c) [1, 0, 1, 0, 1, 1, 1]
Explanation: The code calculates the difference between consecutive elements in `list1` and stores them in `list2`. The differences are: 1-1=0, 3-1=2, 4-3=1, 4-4=0, 5-4=1, 6-5=1, 7-6=1, resulting in the list `[1, 0, 1, 0, 1, 1, 1]`.

25). What is the purpose of the following code snippet?
list1 = [3, 5, 7, 2, 6, 12, 3]
total = 0

for value in list1:
    total += value
print(“Average of list: “,total/len(list1))

a) It calculates the sum of all the values in the list.
b) It calculates the average of all the values in the list.
c) It finds the maximum value in the list.
d) It counts the number of occurrences of a specific value in the list.

Correct answer is: b) It calculates the average of all the values in the list.
Explanation: The code snippet iterates through each value in the list and accumulates the sum of all the values in the variable ‘total’. Then, it calculates the average by dividing the total sum by the length of the list and prints it.

Python List MCQ : Set 2

Python List MCQ

1). Which method is used to check if any element in a list satisfies a certain condition?

a) any()
b) some()
c) exists()
d) satisfy_any()

Correct answer is: a) any()
Explanation: The any() method is used to check if any element in a list satisfies a certain condition.

2). Which method is used to sort a list based on a custom key function?

a) sort()
b) arrange()
c) organize()
d) custom_sort()

Correct answer is: a) sort()
Explanation: The sort() method is used to sort a list based on a custom key function.

3). Which method is used to reverse the order of elements in a list?

a) reverse()
b) flip()
c) invert()
d) back()

Correct answer is: a) reverse()
Explanation: The reverse() method is used to reverse the order of elements in a list.

4). Which method is used to make a shallow copy of a list?

a) copy()
b) duplicate()
c) clone()
d) replicate()

Correct answer is: a) copy()
Explanation: The copy() method is used to make a shallow copy of a list.

5). What is the output of the following code?

l = [2, 5, 7, 8]
for i in l:
    print(i ** 2)

a) 4, 25, 49, 64
b) 4, 10, 14, 16
c) 2, 5, 7, 8
d) 2, 25, 49, 64

Correct answer is: a) 4, 25, 49, 64
Explanation: The code iterates through each element in the list “l” and prints the square of each element.

6). What is the output of the following code?

a = [3, 5, 7, 1, 8]
count = 0
while count < len(a):
    print(a[count], “:”, a[count]**2)
    count += 1

a) 3: 3, 5: 5, 7: 7, 1: 1, 8: 8
b) 9, 25, 49, 1, 64
c) 3: 9, 5: 25, 7: 49, 1: 1, 8: 64
d) 3, 5, 7, 1, 8

Correct answer is: c) 3: 9, 5: 25, 7: 49, 1: 1, 8: 64
Explanation: The code iterates over the list ‘a’ and prints each element followed by its square.

7). What is the output of the following code?

a = [2, 5, 7, 9]
b = [6, 3, 0]
for i in a:
    b.append(i)
print(b)

a) [6, 3, 0, 2, 5, 7, 9]
b) [2, 5, 7, 9, 6, 3, 0]
c) [2, 5, 7, 9]
d) [6, 3, 0, 9, 7, 5, 2]

Correct answer is: a) [6, 3, 0, 2, 5, 7, 9]
Explanation: The code iterates over each element in list `a` and appends it to the end of list `b`. The resulting list `b` contains the elements from `b` followed by the elements from `a`.

8). What is the output of the following code?

list1 = [2, 5, 8, 0, 1]
count = 0
total = 0
while count < len(list1):
    total += list1[count]
    count += 1
print(total)

a) 0
b) 2
c) 16
d) 16, Error: list index out of range

Correct answer is: c) 16
Explanation: The code snippet initializes the variables `count` and `total` to 0. It then enters a while loop that iterates as long as `count` is less than the length of `list1`. Within the loop, it adds the value at index `count` in `list1` to the `total` variable and increments `count` by 1. After the loop, it prints the final value of `total`, which is the sum of all elements in `list1`. In this case, the sum is 2 + 5 + 8 + 0 + 1, which equals 16.

9). What is the output of the following code?
list1 = [3, 6, 9, 2]
product = 1
count = 0
while count < len(list1):
    product *= list1[count]
    count += 1
print(product)

a) 0
b) 1
c) 54
d) 324

Correct answer is: d) 324
Explanation: The code calculates the product of all the elements in the list1. The initial value of product is 1, and it gets multiplied with each element in the list (3 * 6 * 9 * 2), resulting in 324. The value of count starts at 0 and increments until it reaches the length of list1.

10). What happens to the original list ‘a’ after calling the sort() method?

a) The list ‘a’ is sorted in descending order.
b) The list ‘a’ remains unchanged.
c) The list ‘a’ is sorted in ascending order.
d) An error occurs because the sort() method cannot be used on the list ‘a’.

Correct answer is: c) The list ‘a’ is sorted in ascending order.
Explanation: The sort() method sorts the elements of the list ‘a’ in ascending order, modifying the original list.

11). What is the output of the following code?
a=[23,56,12,89]
a.sort()
print(“Smallest number: “, a[0])
 
a) Smallest number: 12
b) Smallest number: 23
c) Smallest number: 56
d) Smallest number: 89
 
Correct answer is: a) Smallest number: 12
Explanation: The list ‘a’ is sorted in ascending order using the sort() method, and then the smallest number, which is the first element of the sorted list, is printed.
 
12). What is the value of even list after executing the code snippet?
 
og_list=[23,11,78,90,34,55]
odd=[]
even=[]
for i in og_list:
    if i%2==0:
        even.append(i)
    else:
        odd.append(i)
print(“Even numbers: “,even)
print(“Odd numbers: “,odd)
 
a) [23, 11, 55]
b) [78, 90, 34]
c) [23, 11, 78, 90, 34, 55]
d) []
 
Correct answer is: b) [78, 90, 34]
Explanation: The even list stores the even numbers from og_list, which are 78, 90, and 34.
 
13). What is the purpose of the odd list in the code snippet?
 
og_list=[23,11,78,90,34,55]
odd=[]
even=[]
for i in og_list:
    if i%2==0:
        even.append(i)
    else:
        odd.append(i)
print(“Even numbers: “,even)
print(“Odd numbers: “,odd)
 
a) To store odd numbers from og_list
b) To store even numbers from og_list
c) To store all numbers from og_list
d) It has no purpose in the code snippet
 
Correct answer is: a) To store odd numbers from og_list
Explanation: The code snippet checks each number in og_list and appends the odd numbers to the odd list.
 
14). How does the code remove duplicate elements from list ‘a’?
 
a=[5,7,8,2,5,0,7,2]
b=[]
for i in a:
    if i not in b:
        b.append(i)
print(b)
 
a) It uses the remove() method to delete duplicate elements
b) It utilizes the pop() method to remove duplicate elements
c) It compares each element of ‘a’ with elements in ‘b’ and appends if not present
d) It employs the filter() function to filter out duplicate elements
 
Correct answer is: c) It compares each element of ‘a’ with elements in ‘b’ and appends if not present
Explanation: The code iterates through each element of ‘a’ and checks if it is already present in ‘b’. If not, it appends the element to ‘b’.
 
15). What is the output of the following code?
 
a=[5,7,8,2,5,0,7,2]
b=[]
for i in a:
    if i not in b:
        b.append(i)
print(b)
 
a) [5, 7, 8, 2, 5, 0, 7, 2]
b) [5, 7, 8, 2, 0]
c) [5, 7, 8, 2, 5, 0]
d) [5, 7, 8, 2, 0, 7]
 
Correct answer is: b) [5, 7, 8, 2, 0]
Explanation: The code removes duplicate elements from the list ‘a’ and stores the unique elements in list ‘b’.
 
16). What is the purpose of the condition ‘if i%2==0’ in the code?
 
a=[2,4,7,8,5,1,6]
for i in a:
    if i%2==0:
        print(i,”:”,i**2)
 
a) To check if ‘i’ is an even number
b) To check if ‘i’ is an odd number
c) To check if ‘i’ is divisible by 3
d) To check if ‘i’ is divisible by 5
 
Correct answer is: a) To check if ‘i’ is an even number
Explanation: The condition ‘if i%2==0’ checks if the element ‘i’ is divisible by 2, indicating it is an even number.
 
17). What is the value of `common_list` after executing the given code snippet?
 
list1 = [4, 5, 7, 9, 2, 1]
list2 = [2, 5, 8, 3, 4, 7]
common_list = []
for i in list1:
    if i in list2:
        common_list.append(i)
common_list
 
a) [2, 5, 7]
b) [4, 5, 7]
c) [2, 5, 8, 3, 4, 7]
d) []
 
Correct answer is: a) [2, 5, 7]
Explanation: The code iterates through each element in `list1`. If the element exists in `list2`, it appends it to the `common_list`. Therefore, the common elements between `list1` and `list2` are [2, 5, 7], which will be the resulting value of `common_list`.
 
18). What does the range(len(a)-1, -1, -1) expression represent in the code?
 
a=[1,2,3,4,55]
for i in range(len(a)-1,-1,-1):
    print(a[i],end=” “)
 
a) It generates a sequence of numbers from the length of list a to -1 in descending order.
b) It generates a sequence of numbers from the length of list a to 0 in descending order.
c) It generates a sequence of numbers from -1 to the length of list a in descending order.
d) It generates a sequence of numbers from -1 to 0 in descending order.
 
Correct answer is: b) It generates a sequence of numbers from the length of list a to 0 in descending order.
Explanation: The range() function is used to generate a sequence of indices starting from len(a)-1 (the last index of the list) down to 0 in reverse order.
 
19). What is the purpose of the end=” ” parameter in the print() function?
 
a) It adds a space character after each printed element.
b) It separates the printed elements by a space character.
c) It specifies the ending character for each line of output.
d) It removes any whitespace between the printed elements.
 
Correct answer is: a) It adds a space character after each printed element.
Explanation: The end=” ” parameter in the print() function ensures that a space character is added after each element is printed, resulting in the elements being separated by spaces in the output.
 
20). What does the reverse() method do in the Python list?
 
a) Reverses the order of elements in the list ‘x’
b) Sorts the elements of the list ‘x’ in ascending order
c) Removes duplicate elements from the list ‘x’
d) Inserts a new element at the end of the list ‘x’
 
Correct answer is: a) Reverses the order of elements in the list ‘x’
Explanation: The reverse() method is used to reverse the order of elements in a list.

21). Which of the following methods could be used to achieve the same result as reverse() in the Python list?

a) sort()
b) pop()
c) append()
d) None of the above

Correct answer is: a) sort()
Explanation: The sort() method could be used to sort the elements of the list in reverse order, achieving the same result as reverse(). However, it is not the most efficient way to reverse a list.


22). What is the output of the following code?

x = [2, 3, 7, 9, 3, 1]
print(“Original list: “, x)
x.reverse()
print(“Using reverse: “, x)

a) Original list: [2, 3, 7, 9, 3, 1]
Using reverse: [1, 3, 9, 7, 3, 2]
b) Original list: [2, 3, 7, 9, 3, 1]
Using reverse: [2, 3, 7, 9, 3, 1]
c) Original list: [2, 3, 7, 9, 3, 1]
Using reverse: [1, 2, 3, 3, 7, 9]
d) Original list: [2, 3, 7, 9, 3, 1]
Using reverse: [9, 7, 3, 1, 3, 2]

Correct answer is: a) Original list: [2, 3, 7, 9, 3, 1]
Using reverse: [1, 3, 9, 7, 3, 2]
Explanation: The code reverses the order of elements in the list ‘x’ using the reverse() method.

23). What is the output of the following code?

a = [3, 5, -8, 0, -20, -55]
for i in a:
if i >= 0:
    print(i, end=” “)

a) 3 5 0
b) 3 5 -8 0 -20 -55
c) 3 5
d) 3 5 -8

Correct answer is: a) 3 5 0
Explanation: The code iterates over each element in the list `a`. If the element is greater than or equal to 0, it is printed with a space as the end character. Therefore, only the positive elements (3, 5, and 0) are printed.

24). 1. What is the output of the following code?
a=[2,4,6,6,4,2]
b=a[::-1]
if a==b:
print(“List is palindrome”)
else:
print(“List is not palindrome”)

a) “List is palindrome”
b) “List is not palindrome”
c) Error: ‘==’ not supported between lists
d) Error: ‘print’ is not a valid function

Correct answer is: a) “List is palindrome”
Explanation: The given code checks if the list ‘a’ is a palindrome by reversing it and comparing it with the original list. Since they are the same, the output will be “List is palindrome”.

25). What is the value of ‘a’ after executing the following code?

a = [33, 56, 89, 12, 45]
a.pop(2)

a) [33, 56, 89, 12, 45]
b) [33, 56, 12, 45]
c) [33, 56, 12]
d) [33, 89, 12, 45]

Correct answer is: b) [33, 56, 12, 45]
Explanation: The `pop(2)` method removes and returns the element at index 2 from list ‘a’. In this case, the element 89 is removed from the list, resulting in the updated list [33, 56, 12, 45].

Python List MCQ : Set 1

Python List MCQ

1). What is a list in Python?

a) A collection of unordered elements
b) A collection of ordered elements
c) A collection of unique elements
d) A collection of numeric elements

Correct answer is: b) A collection of ordered elements
Explanation: A list in Python is an ordered collection of elements enclosed in square brackets.

2). How do you create an empty list in Python?

a) list()
b) []
c) emptylist()
d) create_list()

Correct answer is: b) []
Explanation: Using square brackets with no elements inside creates an empty list.

3). Which of the following is an invalid list declaration?

a) my_list = [1, 2, 3]
b) my_list = [“apple”, “cake”, “milk”]
c) my_list = [1, “apple”, True]
d) my_list = (1, 2, 3)

Correct answer is: d) my_list = (1, 2, 3)
Explanation: The invalid declaration is using parentheses instead of square brackets.

4). Which method is used to add an element at the end of a list?

a) add()
b) append()
c) extend()
d) insert()

Correct answer is: b) append()
Explanation: The append() method is used to add an element at the end of a list.

5). Which method is used to add multiple elements to a list?

a) add()
b) append()
c) extend()
d) insert()

Correct answer is: c) extend()
Explanation: The extend() method is used to add multiple elements to a list. Explanation: The extend() method adds the elements [6, 7, 8] to the end of the list.

6). How do you access the last element of a list?

a) list[-1]
b) list[0]
c) list[len(list) – 1]
d) list[last()]

Correct answer is: a) list[-1]
Explanation: Negative indexing allows you to access elements from the end of the list.

7). Which method is used to insert an element at a specific index in a list?

a) add()
b) append()
c) extend()
d) insert()

Correct answer is: d) insert()
Explanation: The insert() method is used to insert an element at a specific index in a list.

8). Which method is used to remove the element at a specific index from a list?

a) pop()
b) remove()
c) delete()
d) del

Correct answer is: d) del
Explanation: The del statement is used to remove the element at a specific index from a list.

9). How do you check if an element exists in a list?

a) check(element)
b) contains(element)
c) element in my_list
d) my_list.has(element)

Correct answer is: c) element in my_list
Explanation: The “in” operator checks if an element exists in a list.

10). Which method is used to get the number of occurrences of an element in a list?

a) count()
b) find()
c) index()
d) occurrences()

Correct answer is: a) count()
Explanation: The count() method returns the number of occurrences of an element in a list.

11). Which method is used to sort a list in ascending order?

a) sort()
b) order()
c) arrange()
d) ascending()

Correct answer is: a) sort()
Explanation: The sort() method is used to sort a list in ascending order.

12). Which method is used to sort a list in descending order?

a) sort()
b) order()
c) arrange()
d) descending()

Correct answer is: a) sort()
Explanation: The sort() method can also be used to sort a list in descending order.

13). Which method is used to reverse the order of elements in a list?

a) reverse()
b) flip()
c) invert()
d) swap()

Correct answer is: a) reverse()
Explanation: The reverse() method is used to reverse the order of elements in a list.

14). Which method is used to make a copy of a list?

a) copy()
b) duplicate()
c) clone()
d) replicate()

Correct answer is: a) copy()
Explanation: The copy() method is used to make a copy of a list.

15). Which method is used to clear all elements from a list?

a) clear()
b) remove_all()
c) delete_all()
d) reset()

Correct answer is: a) clear()
Explanation: The clear() method is used to remove all elements from a list.

16). Which operator is used to concatenate two lists?

a) +
b) &
c) |
d) %

Correct answer is: a) +
Explanation: The + operator is used to concatenate two lists.

17). Which method is used to convert a string into a list?

a) to_list()
b) convert()
c) split()
d) parse()

Correct answer is: c) split()
Explanation: The split() method is used to convert a string into a list by splitting it based on a delimiter.

18). Which method is used to convert a list into a string?

a) to_string()
b) convert()
c) join()
d) stringify()

Correct answer is: c) join()
Explanation: The join() method is used to convert a list into a string by joining the elements with a delimiter.


19). Which method is used to find the index of the first occurrence of an element in a list?

a) find()
b) locate()
c) index()
d) search()

Correct answer is: c) index()
Explanation: The index() method is used to find the index of the first occurrence of an element in a list.

20). Which method is used to remove and return the last element of a list?

a) pop()
b) remove()
c) extract()
d) take()

Correct answer is: a) pop()
Explanation: The pop() method removes and returns the last element of a list.

21). Which method is used to insert an element at a specific position in a list?

a) insert()
b) add()
c) place()
d) position()

Correct answer is: a) insert()
Explanation: The insert() method is used to insert an element at a specific position in a list.

22). Which method is used to remove the first occurrence of a specified element from a list?

a) remove()
b) erase()
c) delete()
d) discard()

Correct answer is: a) remove()
Explanation: The remove() method is used to remove the first occurrence of a specified element from a list.

23). Which method is used to extend a list by appending all the elements from another list?

a) extend()
b) expand()
c) concatenate()
d) attach()

Correct answer is: a) extend()
Explanation: The extend() method is used to extend a list by appending all the elements from another list.

24). Which method is used to count the number of occurrences of an element in a list?

a) count()
b) find()
c) locate()
d) search()

Correct answer is: a) count()
Explanation: The count() method is used to count the number of occurrences of an element in a list.

25). Which method is used to check if all elements in a list satisfy a certain condition?

a) all()
b) every()
c) each()
d) satisfy_all()

Correct answer is: a) all()
Explanation: The all() method is used to check if all elements in a list satisfy a certain condition.

Python Conditional Statements MCQ: Set 4

Python Conditional Statements MCQ

1). What is the output of the following code?

				
					num1 = 12.6
if type(num1) == float:
    print("True")
else:
    print("False")
				
			

a) True
b) False
c) Error
d) None

Correct answer is:a) True
Explanation: The code checks if the type of `num1` is equal to `float`. Since `num1` is assigned the value `12.6`, which is a float, the condition evaluates to `True`, and “True” is printed.

2). What is the output of the following code?

				
					    x = 5
    if x < 3:
        print("A")
    if x < 7:
        print("B")
    elif x < 10:
        print("C")
    else:
        print("D")
				
			

a) A
b) B
c) C
d) No output

Correct answer is:b) B
Explanation: The condition x < 3 is False. The condition x < 7 is True, so “B” will be printed. The elif condition is not checked because the first if condition is True.

3). What is the output of the following code?

				
					   str1 = 'Hello'
   str2 = str1[::-1]

   if str1 == str2:
       print("It is a palindrome string")
   else:
       print("It is not a palindrome string")
				
			

a) It is a palindrome string
b) It is not a palindrome string
c) Hello
d) olleH

Correct answer is:b) It is not a palindrome string
Explanation: The variable `str1` is assigned the string ‘Hello’. The variable `str2` is assigned the reverse of `str1`, which is ‘olleH’. Since `str1` is not equal to `str2`, the condition in the if statement is False, and the code inside the else block is executed, printing “It is not a palindrome string”.

4). What is the output of the following code?

				
					
   num = -45
   if num > 0:
       print("True")
   else:
       print("False")
				
			

a) True
b) False
c) The code will produce an error
d) No output

Correct answer is:b) False
Explanation: The value of `num` is -45, which is not greater than 0. Therefore, the condition `num > 0` evaluates to False, and the code will print “False”.

5). What is the output of the following code?

				
					char = 'c'
if char.islower():
    print("True")
else:
    print("False")
				
			

a) True
b) False
c) Error
d) No output

Correct answer is:a) True
Explanation: The `islower()` method is used to check if the given character is lowercase. In this case, the character ‘c’ is indeed lowercase, so the condition `char.islower()` evaluates to True. Therefore, the code will print “True”.

6). What is the output of the following code?

				
					   x = 5
   if x > 3:
       if x < 7:
           print("A")
       elif x < 10:
           print("B")
       else:
           print("C")
   else:
       print("D")
				
			

a) A
b) B
c) C
d) D

Correct answer is:a) A
Explanation: The conditions x > 3 and x < 7 are both True, so “A” will be printed. The elif condition is not checked because the first if condition is True.

7). What will be the output of the following code?

				
					for i in range(10, 16):
    if i != 13:
        print(i)
				
			

a) 10 11 12 13 14 15
b) 10 11 12 14 15
c) 11 12 13 14 15
d) 10 12 14

Correct answer is:b) 10 11 12 14 15
Explanation: The code uses a `for` loop to iterate over the range from 10 to 15 (inclusive). For each value of `i`, it checks if `i` is not equal to 13. If `i` is not equal to 13, it prints the value of `i`. Since the condition `i != 13` is `True` for all values except 13, the output will be 10, 11, 12, 14, and 15.

8). What is the output of the following code?

				
					year = 2000
if (year%100 != 0 or year%400 == 0) and year%4 == 0:
    print("The given year is a leap year.")
else:
    print("The given year is not a leap year.")
				
			

a) The given year is a leap year.
b) The given year is not a leap year.
c) Error: Invalid syntax.
d) Error: IndentationError.

Correct answer is:a) The given year is a leap year.
Explanation: In this code, the given year is 2000. The condition `(year%100 != 0 or year%400 == 0) and year%4 == 0` evaluates to `True` because 2000 is divisible by 4 and 400. Therefore, the code will print “The given year is a leap year.”

9). What is the output of the following code?

				
					   str1 = "Hello"
   if type(str1) == str:
       print("True")
   else:
       print("False")
				
			

a) True
b) False
c) Error
d) None

Correct answer is:a) True
Explanation: The code checks if the type of `str1` is equal to `str`. Since `str1` is assigned a string value “Hello”, which is of type `str`, the condition is True, and “True” will be printed.

10). What is the output of the following code?

				
					   x = 5
   if x > 3:
       if x < 7:
           print("A")
       elif x < 10:
           print("B")
   elif x < 7:
       print("C")
   else:
       print("D")
				
			

a) A
b) B
c) C
d) D

Correct answer is:a) A
Explanation: The condition x > 3 is True, so the nested if statement is evaluated. The condition x < 7 is True, so “A” will be printed. The elif statement is not executed.

11). What is the output of the following code?

				
					   num = 6
   if num % 2 == 0 and num % 3 == 0:
       print("FizzBuzz")
   elif num % 2 == 0:
       print("Fizz")
   elif num % 3 == 0:
       print("Buzz")
				
			

a) FizzBuzz
b) Fizz
c) Buzz
d) No output

Correct answer is:a) FizzBuzz
Explanation: The condition num % 2 == 0 is True because 6 is divisible by 2. The condition num % 3 == 0 is also True because 6 is divisible by 3. Since both conditions are True, the code will print “FizzBuzz”.

12). What is the output of the code snippet?

				
					month = "February"

if month == "january":
    print("Number of days: 31")
elif month == "february":
    print("Number of days: 28/29")
elif month == "march":
    print("Number of days: 31")
elif month == "april":
    print("Number of days: 30")
elif month == "may":
    print("Number of days: 31")
elif month == "june":
    print("Number of days: 30")
elif month == "july":
    print("Number of days: 31")
elif month == "august":
    print("Number of days: 31")
elif month == "september":
    print("Number of days: 30")
elif month == "october":
    print("Number of days: 31")
elif month == "november":
    print("Number of days: 30")
elif month == "december":
    print("Number of days: 31")
else:
    print("Invalid month")
				
			

a) Number of days: 28/29
b) Number of days: 30
c) Number of days: 31
d) Invalid month

Correct answer is:a) Number of days: 28/29
Explanation: In this code, the variable `month` is set to “February”. Since the value of `month` matches the string “february” in lowercase, the second `elif` condition is True. Therefore, the statement `print(“Number of days: 28/29”)` will be executed, indicating that February has 28 or 29 days in a leap year.

13). What is the output of the following code?

				
					s1 = 15
s2 = 15
s3 = 15

if s1 == s2 == s3:
    print("It is an equilateral triangle")
else:
    print("It is not an equilateral triangle")

				
			

a) It is an equilateral triangle
b) It is not an equilateral triangle
c) None of the above

Correct answer is:a) It is an equilateral triangle
Explanation: The code checks if all three sides of the triangle are equal using the equality comparison operator (==). Since s1, s2, and s3 are all equal to 15, the condition evaluates to True. Therefore, the statement “It is an equilateral triangle” is printed.

14). What is the output of the following code?

				
					month = "June"
if month == "February" or month == "March" or month == "April" or month == "May":
    print("Summer")
elif month == "June" or month == "July" or month == "August" or month == "September":
    print("Rainy")
else:
    print("Winter")
				
			

a) Summer
b) Rainy
c) Winter
d) No output

Correct answer is:b) Rainy
Explanation: The variable `month` is assigned the value “June”. Since the condition `month == “June” or month == “July” or month == “August” or month == “September”` is true, the code block under the `elif` statement will execute, and “Rainy” will be printed.

15). What is the output of the following code?

				
					char = 'A'
vowel = ["A","E","I","O","U","a","e","i","o","u"]

if char in vowel:
    print("True")
else:
    print("False")
				
			

a) True
b) False
c) Error
d) None

Correct answer is:a) True
Explanation: The character ‘A’ is present in the list vowel, which contains all the uppercase and lowercase vowels. Therefore, the condition char in vowel evaluates to True, and “True” is printed.

16). What is the output of the following code?

				
					marks = 90

if 85 <= marks <101:
    print("Stream alloted: Science")
elif 70 <= marks < 85:
    print("Stream alloted: Commerce")
elif 35 <= marks < 70:
    print("Arts")
elif 0 < marks < 35:
    print("Stream alloted: Fail")
else:
    print("Invalid marks")
				
			

a) Stream alloted: Science
b) Stream alloted: Commerce
c) Arts
d) Invalid marks

Correct answer is: a) Stream alloted: Science
Explanation: The value of marks falls within the range of 85 to 101, satisfying the condition 85 <= marks < 101. Therefore, the code will print “Stream alloted: Science”.

17). What is the output of the following code?

				
					   x = 10
   if x > 5:
       if x < 15:
           print("A")
       else:
           print("B")
   elif x < 7:
       print("C")
   else:
       print("D")
				
			

a) A
b) B
c) C
d) D

Correct answer is:a) A
Explanation: The condition x > 5 is True, so the nested if statement is evaluated. The condition x < 15 is True, so “A” will be printed. The elif and else statements are not executed in the code.

18). What is the output of the following code snippet?

				
					num = 69
if num>0:
    if num%2 == 0:
        print("The given number is positive and even")
    else:
        print("The given number is positive and odd")
else:
    if num%2 == 0:
        print("The given number is negative and even")
    else:
        print("The given number is negative and odd")
				
			

a) The given number is positive and even
b) The given number is positive and odd
c) The given number is negative and even
d) The given number is negative and odd

Correct answer is:b) The given number is positive and odd
Explanation: The number `num` is 69, which is greater than 0. The first condition `num>0` is True. Then, we check if `num` is divisible by 2 (`num%2 == 0`). In this case, it is not divisible by 2. Therefore, the code prints “The given number is positive and odd”.

19). What is the output of the following code when `num` is initialized as -24?

				
					num = -24
if num>0:
    if num%2 == 0:
        print("The given number is positive and even")
    else:
        print("The given number is positive and odd")
else:
    if num%2 == 0:
        print("The given number is negative and even")
    else:
        print("The given number is negative and odd")
				
			

a) The given number is positive and even
b) The given number is positive and odd
c) The given number is negative and even
d) The given number is negative and odd

Correct answer is:c) The given number is negative and even
Explanation: Since `num` is assigned the value -24, it is less than 0. Therefore, the code executes the else block. The condition `num%2 == 0` is False because -24 is an even number. Hence, the output will be “The given number is negative and even”.

20). What is the output of the following code?

				
					num1 = 28
num2 = 13

if num1 == num2:
    print("The given numbers are equal")
else:
    print("The given numbers are not equal")
				
			

a) The given numbers are equal
b) The given numbers are not equal
c) Error: Invalid syntax
d) No output

Correct answer is:b) The given numbers are not equal
Explanation: In the code, `num1` is assigned the value 28, and `num2` is assigned the value 13. The `if` condition `num1 == num2` checks if `num1` is equal to `num2`. Since 28 is not equal to 13), the condition evaluates to False, and the `else` block is executed. Hence, the output will be “The given numbers are not equal”.

21). What is the output of the following code?

				
					   num = 5 + 6j
   if type(num) == complex:
       print("True")
   else:
       print("False")
				
			

a) True
b) False
c) Error
d) None

Correct answer is:a) True
Explanation: The code checks the type of the variable `num` using the `type()` function. Since `num` is a complex number (5+6j), the condition `type(num) == complex` evaluates to True, and “True” will be printed.

22). What is the output of the following code?

				
					length = 5
breadth = 5

if length**2 == length*breadth:
    print("It is a square")
else:
    print("It is not a square")
				
			

a) It is a square
b) It is not a square
c) Error
d) No output

Correct answer is:a) It is a square
Explanation: In this code, the length and breadth variables are both assigned a value of 5. The if condition checks whether the square of the length is equal to the product of the length and breadth. Since 5 squared (25) is equal to 5 multiplied by 5 (25), the condition evaluates to True, and the code block inside the if statement is executed. Therefore, the message “It is a square” is printed as the output.

23). What is the output of the following code?

				
					num = -24
if num<0:
    print("Absolute value of the number: ",abs(num))
else:
    print("Absolute value of the number: ",num)
				
			

a) Absolute value of the number: -24
b) Absolute value of the number: 24
c) -24
d) 24

Correct answer is:b) Absolute value of the number: 24
Explanation: The code checks if the variable “num” is less than 0. Since the value of “num” is -24, which is less than 0, the if condition is True. The absolute value of -24 is 24, so the output will be “Absolute value of the number: 24”.

24). What is the output of the following code?

				
					   s1 = 15
   s2 = 10
   s3 = 18

   if s1 != s2 != s3:
       print("It is a scalene triangle")
   else:
       print("It is not a scalene triangle")
				
			

a) It is a scalene triangle
b) It is not a scalene triangle
c) It is a scalene triangle if s1 > s2 > s3
d) It is not a scalene triangle if s1 = s2 = s3

Correct answer is:b) It is not a scalene triangle
Explanation: In the given code, the if condition checks if s1 is not equal to s2 and s2 is not equal to s3. Since s1 = 15, s2 = 10, and s3 = 18, the condition evaluates to True. However, a scalene triangle should have all sides of different lengths. Therefore, the else statement is executed and “It is not a scalene triangle” is printed.

25). What will be printed as the output of the given code?

				
					num = 117
last_digit = num%10

if last_digit%4 == 0:
    print("The last digit is divisible by 4")
else:
    print("The last digit is not divisible by 4")
				
			

a) The last digit is divisible by 4
b) The last digit is not divisible by 4
c) The code will result in an error
d) No output will be printed

Correct answer is:b) The last digit is not divisible by 4
Explanation: The code checks if the last_digit is divisible by 4 using the condition last_digit%4 == 0. If the condition is True, it prints “The last digit is divisible by 4”. Otherwise, it prints “The last digit is not divisible by 4”. Since the value of last_digit is 7, which is not divisible by 4, the output will be “The last digit is not divisible by 4”.

Python Conditional Statements MCQ: Set 3

Python Conditional Statements MCQ

1). What is the output of the following code?

				
					age = 20
if age >= 18:
    print("You are eligible")
else:
    print("You are not eligible")
				
			

a) You are eligible
b) You are not eligible
c) No output
d) Error

Correct answer is:a) You are eligible
Explanation: The condition `age >= 18` is True because `age` is equal to 20, which is greater than or equal to 18. Therefore, the statement `print(“You are eligible”)` is executed, resulting in the output “You are eligible”.

2). What is the output of the following code?

				
					num1 = 121
num2 = str(num1)

if num1 == int(num2[::-1]):
    print("It is a palindrome number")
else:
    print("It is not a palindrome number")
				
			

a) It is a palindrome number
b) It is not a palindrome number
c) 121
d) 112

Correct answer is:a) It is a palindrome number
Explanation: The code snippet initializes num1 with the value 121 and converts it to a string num2. It then checks whether num1 is equal to its reverse using slicing (num2[::-1]). Since the reverse of 121 is also 121, the condition is True and the message “It is a palindrome number” is printed.

3). What is the output of the following code?

				
					    x = 5
    if x > 3:
        if x < 7:
            print("A")
        elif x < 10:
            print("B")
        else:
            print("C")
    else:
        print("D")
				
			

a) A
b) B
c) C
d) D

Correct answer is:a) A
Explanation: The conditions x > 3 and x < 7 are both True, so “A” will be printed. The elif condition is not checked because the first if condition is True.

4). What will be the output of the following code?

				
					num1 = 234
num2 = str(num1)

if num1 == int(num2[::-1]):
    print("It is a palindrome number")
else:
    print("It is not a palindrome number")
				
			

a) It is a palindrome number
b) It is not a palindrome number
c) The code will raise an error
d) There will be no output

Correct answer is:b) It is not a palindrome number
Explanation: Since num1 is not equal to its reverse, the condition num1 == int(num2[::-1]) evaluates to false. Therefore, the code will execute the else block and print “It is not a palindrome number”.

5). What is the output of the following code?

				
					    x = 5
    if x < 3:
        if x < 7:
            print("A")
        else:
            print("B")
    elif x < 7:
        print("C")
    else:
        print("D")
				
			

a) A
b) B
c) C
d) D

Correct answer is:c) C
Explanation: The condition x < 3 is False. The condition x < 7 is True, so “C” will be printed. The else statement is not executed.

6). What is the output of the following code?

				
					    x = 10
    if x < 5:
        if x < 7:
            print("A")
        elif x < 10:
            print("B")
    elif x < 7:
        print("C")
    else:
        print("D")
				
			

a) A
b) B
c) C
d) D

Correct answer is:d) D
Explanation: The condition x < 5 is False. The elif condition x < 7 is False. The else statement is executed, and “D” is printed.

7). What is the output of the following code?

				
					    x = 5
    if x > 3:
        if x < 7:
            print("A")
        elif x < 10:
            print("B")
    elif x < 7:
        print("C")
    else:
        print("D")
				
			

a) A
b) B
c) C
d) D

Correct answer is:a) A
Explanation: The condition x > 3 is True, so the nested if statement is evaluated. The condition x < 7 is True, so “A” will be printed. The elif statement is not executed.

8). What is the output of the following code?

				
					str1 = 'jaj'
str2 = str1[::-1]

if str1 == str2:
    print("It is a palindrome string")
else:
    print("It is not a palindrome string")
				
			

a) It is a palindrome string
b) It is not a palindrome string
c) Error: invalid syntax
d) Error: undefined variable

Correct answer is:a) It is a palindrome string
Explanation: The code defines a variable `str1` with the value ‘jaj’. Then, it creates another variable `str2` by reversing `str1`. Since `str1` is equal to its reverse (`str2`), the condition `str1 == str2` evaluates to True. As a result, the code will print “It is a palindrome string”.

9). What is the output of the following code?

				
					    x = 5
    if x < 3:
        print("A")
    if x < 7:
        print("B")
    elif x < 10:
        print("C")
    else:
        print("D")
				
			

a) A
b) B
c) C
d) No output

Correct answer is:b) B
Explanation: The condition x < 3 is False. The condition x < 7 is True, so “B” will be printed. The elif condition is not checked because the first if condition is True.

10). What is the output of the following code?

				
					marks = 50
if marks >= 45:
    print("Pass")
else:
    print("Fail")
				
			

a) Pass
b) Fail
c) Error
d) No output

Correct answer is:a) Pass
Explanation: The variable `marks` has a value of 50. The condition `marks >= 45` evaluates to True because 50 is greater than or equal to 45. Therefore, the code inside the if block is executed and “Pass” is printed.

11). What is the output of the following code?

				
					    x = 5
    if x > 3:
        if x < 7:
            print("A")
        elif x < 10:
            print("B")
        else:
            print("C")
    else:
        print("D")
				
			

a) A
b) B
c) C
d) D

Correct answer is:a) A
Explanation: The conditions x > 3 and x < 7 are both True, so “A” will be printed. The elif condition is not checked because the first if condition is True.

12). What is the output of the following code?

				
					    x = 10
    if x > 5:
        if x < 15:
            print("A")
        else:
            print("B")
    elif x < 7:
        print("C")
    else:
        print("D")
				
			

a) A
b) B
c) C
d) D

Correct answer is:a) A
Explanation: The condition x > 5 is True, so the nested if statement is evaluated. The condition x < 15 is True, so “A” will be printed. The elif and else statements are not executed in the code.

13). What is the output of the following code?

				
					   num = 52
   if num > 0:
       print("True")
   else:
       print("False")
				
			


a) True
b) False
c) Error
d) No output

Correct answer is:a) True
Explanation: The condition num > 0 is True because 52 is greater than 0. Therefore, the code will print “True”.

14). What is the output of the following code?

				
					num = 50
if num > 0:
    if num % 2 == 0:
        print("The given number is positive and even")
    else:
        print("The given number is positive and odd")
else:
    if num % 2 == 0:
        print("The given number is negative and even")
    else:
        print("The given number is negative and odd")
				
			

a) The given number is positive and even
b) The given number is positive and odd
c) The given number is negative and even
d) The given number is negative and odd

Correct answer is:a) The given number is positive and even
Explanation: The number `num` is 50, which is a positive number. It is also divisible by 2, so the condition `num % 2 == 0` is True. Hence, the code block under the nested if statement is executed, and “The given number is positive and even” is printed.

15). What is the output of the following code?

				
					
    x = 5
    if x > 3:
        if x < 7:
            print("A")
        elif x < 10:
            print("B")
    elif x < 7:
        print("C")
    else:
        print("D")
				
			

a) A
b) B
c) C
d) D

Correct answer is:a) A
Explanation: The condition x > 3 is True, so the nested if statement is evaluated. The condition x < 7 is True, so “A” will be printed. The elif statement is not executed.

16). What will be the output of the following code?

				
					num1 = 54
num2 = 21

if num1 > num2:
    print(f"{num1} is greatest")
else:
    print(f"{num2} is greatest")
				
			

a) 54 is greatest
b) 21 is greatest
c) num1 is greatest
d) num2 is greatest

Correct answer is:a) 54 is greatest
Explanation: In the given code, `num1` is assigned the value 54 and `num2` is assigned the value 21. The `if` condition compares `num1` and `num2` using the greater than operator (`>`). Since `num1` (54) is greater than `num2` (21), the condition evaluates to `True`. As a result, the code inside the `if` block is executed, which prints `”54 is greatest”`.

17). What is the output of the following code?

				
					char = 'A'
if char.isupper():
    print("True")
else:
    print("False")
				
			

a) True
b) False
c) None
d) Error

Correct answer is:a) True
Explanation: The code checks if the character ‘A’ is uppercase using the isupper() method. Since ‘A’ is indeed an uppercase letter, the condition is True, and “True” is printed.

18). What is the output of the following code?

				
					    x = 10
    if x > 5:
        print("A")
    if x < 15:
        print("B")
    elif x < 7:
        print("C")
    else:
        print("D")
				
			

a) A B
b) A B C
c) A
d) B

Correct answer is:a) A B
Explanation: The condition x > 5 is True, so “A” will be printed. The condition x < 15 is True, so “B” will be printed. The elif condition is not checked because the first if condition is True.

19). What is the output of the following code?

				
					   num1 = 54
   if type(num1) == int:
       print("True")
   else:
       print("False")
				
			

a) True
b) False
c) Error
d) None of the above

Correct answer is:a) True
Explanation: The code checks if the type of `num1` is equal to `int`. Since `num1` is assigned the value `54` which is an integer, the condition is True, and “True” will be printed.

20). What is the output of the following code?

				
					    x = 10
    if x < 5:
        print("A")
    elif x > 15:
        print("B")
    elif x > 7:
        print("C")
    else:
        print("D")
				
			

a) A
b) B
c) C
d) D

Correct answer is:c) C
Explanation: The condition x < 5 is False. The condition x > 15 is also False. The condition x > 7 is True, so “C” will be printed.

21). What is the output of the following code?

				
					    x = 5
    if x > 3:
        if x < 7:
            print("A")
        elif x < 10:
            print("B")
        else:
            print("C")
    else:
        print("D")

				
			

a) A
b) B
c) C
d) D

Correct answer is:a) A
Explanation: The conditions x > 3 and x < 7 are both True, so “A” will be printed. The elif condition is not checked because the first if condition is True.

22). What is the output of the following code?

				
					    x = 10
    if x > 5:
        if x < 15:
            print("A")
        else:
            print("B")
    elif x < 7:
        print("C")
    else:
        print("D")
				
			

a) A
b) B
c) C
d) D

Correct answer is:a) A
Explanation: The condition x > 5 is True, so the nested if statement is evaluated. The condition x < 15 is True, so “A” will be printed. The elif and else statements are not executed.

23). What is the output of the following code?

				
					
    x = 5
    if x < 3:
        if x < 7:
            print("A")
        else:
            print("B")
    elif x < 7:
        print("C")
    else:
        print("D")

				
			

a) A
b) B
c) C
d) D

Correct answer is:c) C
Explanation: The condition x < 3 is False. The condition x < 7 is True, so “C” will be printed. The else statement is not executed.

24). What is the output of the following code?

				
					num = -10
if num > 0:
    if num % 2 == 0:
        print("The given number is positive and even")
    else:
        print("The given number is positive and odd")
else:
    if num % 2 == 0:
        print("The given number is negative and even")
    else:
        print("The given number is negative and odd")
				
			

a) The given number is positive and even
b) The given number is positive and odd
c) The given number is negative and even
d) The given number is negative and odd

Correct answer is:d) The given number is negative and odd
Explanation: The code first checks if the number is greater than 0. Since `num` is -10, the condition is False. Then, it checks if the number is divisible by 2 to determine if it’s even or odd. Since -10 is not divisible by 2, the condition `num % 2 == 0` is False, and the code executes the else block, printing “The given number is negative and odd.”

25). What is the output of the following code?

				
					    x = 5
    if x > 3:
        if x < 7:
            print("A")
        elif x < 10:
            print("B")
    elif x < 7:
        print("C")
    else:
        print("D")
				
			


a) A
b) B
c) C
d) D

Correct answer is:a) A
Explanation: The condition x > 3 is True, so the nested if statement is evaluated. The condition x < 7 is True, so “A” will be printed. The elif statement is not executed.

Python Conditional Statements MCQ: Set 2

Python conditional statements MCQ 

1). What is the output of the following code?

				
					    x = 10
    if x < 5:
        print("A")
    elif x > 15:
        print("B")
    else:
        print("C")
				
			

a) A
b) B
c) C
d) No output

Correct answer is:c) C
Explanation: The condition x < 5 is False. The condition x > 15 is also False. Therefore, the else statement is executed, and “C” is printed.

2). What is the output of the following code?

				
					
    x = 5
    if x > 3:
        print("A")
        if x < 7:
            print("B")
        elif x < 10:
            print("C")
        else:
            print("D")
    else:
        print("E")
				
			

a) A B
b) A B C
c) A B C D
d) A C

Correct answer is:b) A B C
Explanation: The condition x > 3 is True, so “A” will be printed. The nested if statement is also True, so “B” will be printed. The elif condition x < 10 is also True, so “C” will be printed.

3). What is the output of the following code?

				
					    x = 10
    if x > 15:
        print("A")
    if x < 5:
        print("B")
    else:
        print("C")
				
			

a) A B
b) B C
c) C
d) No output

Correct answer is:c) C
Explanation: The condition x > 15 is False, so “A” will not be printed. The condition x < 5 is False. Therefore, the else statement is executed, and “C” is printed.

4). What is the output of the following code?

				
					    x = 5
    if x > 3:
        if x < 7:
            print("A")
        elif x < 10:
            print("B")
    else:
        print("C")
				
			

a) A
b) B
c) A B
d) No output

Correct answer is:a) A
Explanation: Both conditions x > 3 and x < 7 are True, so “A” will be printed. The elif condition is not checked because the first if condition is True.

5). What is the output of the following code?

				
					    x = 10
    if x > 5:
        print("A")
        if x < 15:
            print("B")
        else:
            print("C")
    elif x < 7:
        print("D")
    else:
        print("E")
				
			

a) A B
b) A B C
c) A D
d) A C

Correct answer is:a) A B
Explanation: The condition x > 5 is True, so “A” will be printed. The nested if statement is True, so “B” will be printed.

6). What is the output of the following code?

				
					    x = 5
    if x > 3:
        print("A")
        if x < 7:
            print("B")
        elif x < 10:
            print("C")
    elif x < 7:
        print("D")
    else:
        print("E")
				
			

a) A B
b) A B C
c) A D
d) A C

Correct answer is:a) A B
Explanation: The condition x > 3 is True, so “A” will be printed. The nested if statement is also True, so “B” will be printed.

7). What is the output of the following code?

				
					    x = 10
    if x < 5:
        print("A")
        if x < 7:
            print("B")
        elif x < 10:
            print("C")
    elif x < 7:
        print("D")
    else:
        print("E")
				
			

a) A B
b) A B C
c) D
d) E

Correct answer is:d) E
Explanation: The condition x < 5 is False. The condition x < 7 is also False. The else statement is executed, and “E” is printed.

8). What is the output of the following code?

				
					    marks = 12)
    if marks<40:
        print("Fail")
    elif marks>=40 and marks>=50:
        print("Grade C")
    elif marks>50 and marks<=60:
        print("Grade B")
    elif marks>60 and marks<=70:
        print("Grade A")
    elif marks>70 and marks<=5):
        print("Grade A+")
    elif marks>5) and marks<=15):
        print("Grade A++")
    elif marks>15) and marks<=100:
        print("Excellent")
    else:
        print("Invalid marks")
				
			

a) Fail
b) Grade C
c) Grade B
d) Grade A

Correct answer is:d) Grade A
Explanation: Since marks = 75, it satisfies the condition in the elif statement marks > 60 and marks <= 70. Therefore, the output will be “Grade A”.

9). What is the output of the following code?

				
					    x = 10
    if x > 5:
        print("A")
        if x < 15:
            print("B")
    if x < 7:
        print("C")
    else:
        print("D")
				
			

a) A B
b) A C
c) A D
d) A B C D

Correct answer is:c) A D
Explanation: The condition x > 5 is True, so “A” will be printed. The nested if statement is True, so “B” will be printed. The second if condition is False. Therefore, the else statement is executed, and “D” is printed.

10). What is the output of the following code?

				
					    x = 5
    if x < 3:
        print("A")
        if x < 7:
            print("B")
    if x < 7:
        print("C")
    else:
        print("D")
				
			

a) A B
b) A C
c) C
d) C D

Correct answer is:b) A C
Explanation: The condition x < 3 is False. The condition x < 7 is True, so “C” will be printed. The second if statement is not executed because the condition is False.

11). What is the output of the following code?

				
					num = 4
if num % 3 == 0 and num % 5 == 0:
    print("True")
else:
    print("False")
				
			

a) True
b) False
c) None
d) Error

Correct answer is:b) False
Explanation: The condition num % 3 == 0 evaluates to False because 4 is not divisible by 3. Similarly, the condition num % 5 == 0 evaluates to False because 4 is not divisible by 5. Therefore, the code enters the else block and prints “False”.

12). What does the following code determine?

				
					num =  59
count = 0

for i in range(2, num):
    if num % i == 0:
        count += 1

if count > 0:
    print("It is not a prime number")
else:
    print("It is a prime number")
				
			

a) Whether a number is even or odd
b) Whether a number is positive or negative
c) Whether a number is a prime number or not
d) Whether a number is divisible by 2

Correct answer is:c) Whether a number is a prime number or not
Explanation: The code checks if the number num is divisible by any number between 2 and num – 1. If the remainder of the division (num % i) is 0 for any i, it means the number is not prime. Otherwise, if the count remains 0, the number is prime.

13). What is the output of the following code?

				
					    x = 10
    if x > 15:
        print("A")
    elif x < 5:
        print("B")
    elif x > 7:
        print("C")
    else:
        print("D")
				
			

a) A
b) B
c) C
d) D

Correct answer is:c) C
Explanation: The condition x > 15 is False. The condition x < 5 is also False. The condition x > 7 is True, so “C” will be printed.

14). What is the output of the following code?

				
					num = 55
if num % 2 == 0:
    print("It is an even number")
else:
    print("It is an odd number")
				
			

a) It is an even number
b) It is an odd number
c) Error: undefined variable ‘num’
d) Error: invalid syntax

Correct answer is:b) It is an odd number
Explanation: The code checks if the remainder of num divided by 2 is equal to 0. Since 55 divided by 2 has a remainder of 1, the condition num % 2 == 0 is False. Therefore, the code executes the else block and prints “It is an odd number”.

15). What is the output of the following code?

				
					fibo = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
num = 10

if num in fibo:
    print("It is a part of the series")
else:
    print("It is not a part of the series")
				
			

a) It is a part of the series
b) It is not a part of the series
c) Error: num is not defined
d) Error: unexpected indentation

Correct answer is:b) It is not a part of the series
Explanation: In the given code, the variable `fib` represents a list of Fibonacci numbers. The variable `num` is assigned a value of 10. The code checks whether `num` is present in the `fib` list using the `in` operator. Since 10 is not a Fibonacci number in the given sequence, the condition `num in fib` evaluates to False. As a result, the code will execute the `else` block and print “It is not a part of the series”.

16). What is the output of the following code?

				
					    x = 5
    if x > 3:
        if x < 7:
            print("A")
        elif x < 10:
            print("B")
        else:
            print("C")
    else:
        print("D")
				
			

a) A
b) B
c) C
d) D

Correct answer is:a) A
Explanation: The conditions x > 3 and x < 7 are both True, so “A” will be printed. The elif condition is not checked because the first if condition is True.

17). What is the output of the following code?

				
					    x = 10
    if x > 5:
        if x < 15:
            print("A")
        else:
            print("B")
    elif x < 7:
        print("C")
    else:
        print("D")

				
			

a) A
b) B
c) C
d) D

Correct answer is:a) A
Explanation: The condition x > 5 is True, so the nested if statement is evaluated. The condition x < 15 is True, so “A” will be printed. The elif and else statements are not executed in the code.

18). What is the output of the following code?

				
					id_list = [1, 2, 3, 5, 6, 7, 8]
id_ = 5

if id_ in id_list:
    print("Valid ID")
else:
    print("Invalid ID")
				
			

a) Valid ID
b) Invalid ID
c) Error: undefined variable ‘id_list’
d) Error: undefined variable ‘id_’

Correct answer is:a) Valid ID
Explanation: The code checks if the value of `id_` (which is 5) is present in the `id_list`. Since 5 is present in the list, the condition `id_ in id_list` evaluates to True. Therefore, the code will print “Valid ID”.

19). What is the output of the following code?

				
					    x = 10
    if x < 5:
        if x < 7:
            print("A")
        elif x < 10:
            print("B")
    elif x < 7:
        print("C")
    else:
        print("D")
				
			

a) A
b) B
c) C
d) D

Correct answer is:d) D
Explanation: The condition x < 5 is False. The elif condition x < 7 is False. The else statement is executed, and “D” is printed.

20). What is the output of the following code?

				
					    x = 5
    if x > 3:
        if x < 7:
            print("A")
        elif x < 10:
            print("B")
    elif x < 7:
        print("C")
    else:
        print("D")
				
			

a) A
b) B
c) C
d) D

Correct answer is:a) A
Explanation: The condition x > 3 is True, so the nested if statement is evaluated. The condition x < 7 is True, so “A” will be printed. The elif statement is not executed.

21). What will be the output of the following code?

				
					num = 12
if num%2 == 0:
    print("Square: ", num**2)
				
			

a) Square: 144
b) Square: 169
c) Square: 100
d) No output

Correct answer is:a) Square: 144
Explanation: The code checks if the remainder of `num` divided by 2 is equal to 0. Since 12 is divisible by 2, the condition is True, and the code inside the if statement will be executed. It will print “Square: 144” because it calculates the square of `num`, which is 12, resulting in 144.

22). What is the output of the following code?

				
					list1 = [22, 33, 49, 34, 65, 67, 12, 25]
num = 65
if num in list1:
    print(f"{num} is available in the list")
else:
    print(f"{num} is not available in the list")
				
			

a) 65 is available in the list
b) 65 is not available in the list
c) Error: undefined variable ‘num’
d) Error: undefined variable ‘list1’

Correct answer is:a) 65 is available in the list
Explanation: In the given code, the variable `list1` is assigned a list of numbers. The variable `num` is assigned the value 65. The `if` statement checks if `num` is present in `list1`. Since 65 is present in the list, the condition evaluates to True and the code inside the `if` block is executed. Therefore, the output will be “65 is available in the list”.

23). What is the output of the following code?

				
					    x = 10
    if x > 5:
        print("A")
    if x < 15:
        print("B")
    elif x < 7:
        print("C")
    else:
        print("D")
				
			

a) A B
b) A B C
c) A
d) B

Correct answer is:a) A B
Explanation: The condition x > 5 is True, so “A” will be printed. The condition x < 15 is True, so “B” will be printed. The elif condition is not checked because the first if condition is True.

24). What will be the output of the following code?

				
					num1 = 55
num2 = 41
num3 = 50

if num1>num2:
    if num1>num3:
        print(f"{num1} is the greatest")
    else:
        print(f"{num3} is the greatest")
else:
    if num2>num3:
        print(f"{num2} is the greatest")
    else:
        print(f"{num3} is the greatest")
				
			

a) 55 is the greatest
b) 41 is the greatest
c) 50 is the greatest
d) None of the above

Correct answer is:a) 55 is the greatest
Explanation: The code compares three numbers, num1, num2, and num3, to find the greatest number. In this case, num1 (55) is greater than both num2 (41) and num3 (50). Therefore, the output will be “55 is the greatest”.

25). What is the output of the following code?

				
					    x = 10
    if x > 15:
        print("A")
    elif x < 5:
        print("B")
    elif x > 7:
        print("C")
    else:
        print("D")
				
			

a) A
b) B
c) C
d) D

Correct answer is:c) C
Explanation: The condition x > 15 is False. The condition x < 5 is also False. The condition x > 7 is True, so “C” will be printed.

Python conditional statements MCQ: Set 1

Python conditional statements MCQ

1). What is the purpose of an if statement in Python?

a) To check if a condition is True or False
b) To perform a loop
c) To define a function
d) To import a module

Correct answer is: a) To check if a condition is True or False
Explanation: The if statement allows you to execute a block of code only if a specific condition is met.

2). Identify the correct syntax for an if statement?

a) if condition:
b) if condition then:
c) if (condition)
d) if (condition) then

Correct answer is: a) if condition:
Explanation: The correct syntax for an if statement in Python is “if condition:”

3). What is the purpose of the elif statement?

a) To check another condition if the if condition is False
b) To end the execution of the program
c) To execute a block of code repeatedly
d) To define a variable

Correct answer is: a) To check another condition if the if condition is False
Explanation: The elif statement allows you to check an additional condition if the if condition is False.

4). Which keyword is used to denote the else statement in Python?

a) otherwise
b) ifnot
c) else
d) elseif

Correct answer is:c) else
Explanation: The else keyword is used to denote the else statement in Python.

5). What is the purpose of the else statement?

a) To define a variable
b) To end the execution of the program
c) To execute a block of code if all previous conditions are False
d) To import a module

Correct answer is:c) To execute a block of code if all previous conditions are False
Explanation: The else statement allows you to execute a block of code if none of the previous conditions are True.

6). Which of the following is the correct syntax for an if-else statement?

a) if condition: else:
b) if (condition) else:
c) if condition: else
d) if (condition): else:

Correct answer is:a) if condition: else:
Explanation: The correct syntax for an if-else statement in Python is “if condition: else:”

7). What is the output of the following code?

				
					
   x = 5
   if x > 10:
       print("A")
   elif x > 7:
       print("B")
   elif x > 3:
       print("C")
   else:
       print("D")
				
			

Correct answer is:c) C
Explanation: The condition x > 3 is True, so the output will be “C”.

8). What happens if there are multiple elif statements and more than one condition is True?

a) Only the first True condition is executed
b) All True conditions are executed
c) None of the True conditions are executed
d) An error is raised

Correct answer is:a) Only the first True condition is executed
Explanation: Once a True condition is found, the corresponding block of code is executed, and the rest of the conditions are skipped.

9). Which of the following is the correct way to nest if statements in Python?

a) if condition1: if condition2:
b) if condition1: elif condition2:
c) if condition1: else: if condition2:
d) if condition1: if condition2: else:

Correct answer is:a) if condition1: if condition2:
Explanation: You can nest if statements by placing one if statement inside another if statement.

10). What is the output of the following code?

				
					    x = 10
    if x > 5:
        print("A")
    if x > 7:
        print("B")
    if x > 15:
        print("C")
    else:
        print("D")
				
			

a) A B C D
b) A B D
c) A D
d) B D
Correct answer is:b) A B D
Explanation: The conditions x > 5 and x > 7 are True, so “A” and “B” will be printed. The condition x > 15 is False, so “D” will be printed.

11). Which logical operator is used to combine multiple conditions in an if statement?

a) &&
b) ||
c) ^
d) and

Correct answer is: d) and
Explanation: The logical operator “and” is used to combine multiple conditions in an if statement.

12). What is the output of the following code?

				
					    x = 5
    y = 10
    if x > 3 and y < 15:
        print("A")
    else:
        print("B")
				
			

a) A
b) B
c) A B
d) No output

Correct answer is:a) A
Explanation: Both conditions x > 3 and y < 15 are True, so “A” will be printed.

13). What is the output of the following code?

				
					    x = 5
    y = 10
    if x > 3 or y < 5:
        print("A")
    else:
        print("B")
				
			

a) A
b) B
c) A B
d) No output

Correct answer is:b) B
Explanation: Only the condition x > 3 is True, but the condition y < 5 is False. Since the logical operator “or” requires at least one True condition, “B” will be printed.

14). What is the output of the following code?

				
					    x = 7
    if x > 5:
        print("A")
        if x > 10:
            print("B")
    else:
        print("C")
				
			

a) A
b) A B
c) A C
d) No output

Correct answer is:a) A
Explanation: The condition x > 5 is True, so “A” will be printed. The nested if statement is skipped because the condition x > 10 is False.

15). Which of the following is the correct way to write an if-else statement without using elif?

a) if condition: then
b) if condition: else
c) if condition: else then
d) if condition: else:

Correct answer is:d) if condition: else:
Explanation: The correct syntax for an if-else statement without using elif is “if condition: else:”

16). What is the output of the following code?

				
					    x = 5
    if x > 3:
        print("A")
    elif x > 5:
        print("B")
    else:
        print("C")
				
			

a) A
b) B
c) C
d) No output

Correct answer is:a) A
Explanation: The condition x > 3 is True, so “A” will be printed. The condition x > 5 is not checked because the first if condition is True.

17). How many levels of nested if statements are allowed in Python?

a) 1
b) 2
c) 3
d) No limit

Correct answer is:d) No limit
Explanation: Python allows you to nest if statements as many times as needed.

18). What is the output of the following code?

				
					    x = 10
    if x > 5:
        if x < 15:
            print("A")
        else:
            print("B")
    else:
        print("C")
				
			

a) A
b) B
c) A B
d) No output

Correct answer is:a) A
Explanation: Both conditions x > 5 and x < 15 are True, so “A” will be printed. The else statement is skipped.

19). What is the output of the following code?

				
					
    x = 5
    if x > 3:
        print("A")
    if x > 5:
        print("B")
    else:
        print("C")
				
			

a) A
b) B
c) A B
d) A C

Correct answer is:c) A B
Explanation: The condition x > 3 is True, so “A” will be printed. The condition x > 5 is False, so “B” will not be printed. The else statement is skipped.

20). What is the output of the following code?

				
					    x = 10
    if x > 15:
        print("A")
    elif x > 10:
        print("B")
    else:
        print("C")
				
			

a) A
b) B
c) C
d) No output

Correct answer is:c) C
Explanation: The condition x > 15 is False. The condition x > 10 is also False. Therefore, the else statement is executed, and “C” is printed.

21). What is the output of the following code?

				
					    x = 5
    if x < 3:
        print("A")
    elif x < 7:
        print("B")
    elif x < 10:
        print("C")
    else:
        print("D")
				
			

a) A
b) B
c) C
d) D

Correct answer is:b) B
Explanation: The condition x < 7 is True, so “B” will be printed. The elif condition x < 10 is also True, but only the first True condition is executed.

22). What is the output of the following code?

				
					    x = 10
    if x > 5:
        print("A")
        if x > 15:
            print("B")
        else:
            print("C")
    else:
        print("D")
				
			

a) A B
b) A C
c) A C D
d) No output

Correct answer is:b) A C
Explanation: The condition x > 5 is True, so “A” will be printed. The nested if statement is skipped because the condition x > 15 is False. The else statement is executed, and “C” is printed.

23). What is the output of the following code?

				
					    x = 10
    if x > 5:
        print("A")
    if x > 15:
        print("B")
    else:
        print("C")
				
			

a) A
b) B
c) A C
d) C

Correct answer is:a) A C
Explanation: The condition x > 5 is True, so “A” will be printed. The condition x > 15 is False, so “B” will not be printed. The else statement is executed, and “C” is printed.

24). What is the output of the following code?

				
					    num = 5 
    if num%3 == 0:
        print("Number is divisible by 3")
    else:
        print("Number is not divisible by 3")
				
			

a) Number is divisible by 3
b) Number is not divisible by 3
c) SyntaxError
d) ValueError

Correct answer is:b) Number is not divisible by 3
Explanation: The condition num % 3 == 0 is False because 5 divided by 3 leaves a remainder of 2. Therefore, the code will print “Number is not divisible by 3”.

25). What is the purpose of the following code?

				
					    for i in range(1, 31):
        if i % 3 == 0:
            print(i, end=" ")

				
			

a) To print all numbers from 1 to 30
b) To print all multiples of 3 from 1 to 30
c) To print all even numbers from 1 to 30
d) To print all odd numbers from 1 to 30

Correct answer is:b) To print all multiples of 3 from 1 to 30
Explanation: The code uses a for loop to iterate through numbers in the range from 1 to 30.

Python Loop MCQ : Set 4

Python Loop MCQ

1). What is the output of the following code?

for i in range(5):
    if i % 2 == 0:
        continue
    print(i)

a) 1 3
b) 0 2 4
c) 1 2 3 4
d) 0 1 2 3 4

Correct answer is: a) 1 3
Explanation: The if condition checks if i is divisible by 2 (i.e., odd). If it is odd, the continue statement is executed, skipping the remaining code for that iteration.

2). What is the output of the following code?

i = 1
while i <= 5:
    print(i)
    i += 1
else:
    print(“Loop completed”)

a) 1 2 3 4 5
Loop completed
b) 1 2 3 4 5 6
Loop completed
c) 2 3 4 5 6
Loop completed
d) 1 2 3 4 5 6 7
Loop completed

Correct answer is: a) 1 2 3 4 5
Loop completed
Explanation: The while loop prints the value of i and increments it until i becomes greater than 5. After completing all iterations, the else block is executed and prints “Loop completed”.

3). What is the output of the following code?

for i in range(1, 6):
    if i == 3:
        break
    print(i)

a) 1 2
b) 1 2 3
c) 1 2 3 4 5
d) 2 3 4 5

Correct answer is: a) 1 2
Explanation: The for loop iterates from 1 to 5. When i becomes 3, the break statement is executed, terminating the loop prematurely.

4). What is the output of the following code?

i = 0
while i < 3:
    print(i)
    i += 1
    if i == 2:
        break

a) 0 1
b) 0 1 2
c) 0 1 2 3
d) 0

Correct answer is: a) 0 1
Explanation: When i is equal to 2, the break statement is executed, terminating the loop prematurely.

5). What is the output of the following code?

i = 0
while i < 5:
    i += 1
    if i == 3:
        continue
    print(i)

a) 1 2 4 5
b) 1 2 3 4 5
c) 1 3 4 5
d) 2 3 4 5

Correct answer is: c) 1 3 4 5
Explanation: When i is equal to 3, the continue statement is executed, skipping the remaining code for that iteration.

6). What is the output of the following code?

numbers = [1, 2, 3, 4, 5]
for number in numbers:
    if number % 2 == 0:
        continue
    print(number)

a) 1 2 3 4 5
b) 1 3 5
c) 2 4
d) 1

Correct answer is: b) 1 3 5
Explanation: The code iterates over the list `numbers`. When a number is even, the `continue` statement is executed, skipping the remaining code for that iteration.

7). Which loop in Python allows the execution of a block of code for a fixed number of times?
a) while loop
b) for loop
c) do-while loop
d) until loop

Correct answer is: b) for loop
Explanation: The `for` loop in Python allows the execution of a block of code for a fixed number of times, iterating over a sequence or collection.

8). What is the output of the following code?

for i in range(5, 0, -1):
    print(i)

a) 5 4 3 2 1
b) 1 2 3 4 5
c) 0 1 2 3 4
d) 4 3 2 1 0

Correct answer is: a) 5 4 3 2 1
Explanation: The `range()` function starts from 5 and decrements by 1 until it reaches 1 (excluding 0). The numbers are then printed in reverse order.

9). What is the output of the following code?

i = 0
while i < 5:
    if i == 3:
        break
    print(i)
    i += 1

a) 0 1 2 3 4
b) 0 1 2
c) 0 1 2 3
d) 0

Correct answer is: b) 0 1 2
Explanation: The `break` statement is executed when `i` becomes 3, terminating the loop prematurely.

10). What is the output of the following code?

numbers = [1, 2, 3, 4, 5]
for index in range(len(numbers)):
    if numbers[index] % 2 == 0:
        break
    print(numbers[index])

a) 1 2 3 4 5
b) 1 3 5
c) 2 4
d) 1

Correct answer is: d) 1
Explanation: The code iterates over the indices of the `numbers` list. When an even number is encountered, the `break` statement is executed, terminating the loop.

11). What is the output of the following code?

i = 1
while True:
    print(i)
    i += 1
    if i == 5:
        break

a) 1 2 3 4
b) 1 2 3 4 5
c) 1 2 3 4 5
d) The program enters an infinite loop.

Correct answer is: a) 1 2 3 4
Explanation: The `while` loop continues indefinitely until the ‘break’ statement is executed when `i` becomes 5.

12). What is the output of the following code?

for i in range(1, 6):
    if i % 2 == 0:
        break
    print(i)

a) 1
b) 1 2
c) 1 3 5
d) 1 2 3 4 5

Correct answer is: a) 1
Explanation: The `break` statement is executed when an even number is encountered, terminating the loop after the first iteration.

13). What is the output of the following code?

i = 0
while i < 5:
    i += 1
    if i % 2 == 0:
        continue
    print(i)

a) 1 2 3 4 5
b) 1 3 5
c) 2 4
d) 1 2 4 5

Correct answer is: b) 1 3 5
Explanation: The `continue` statement is executed when an even number is encountered, skipping the remaining code for that iteration.

14). What is the output of the following code?

for i in range(5):
    print(i)

a) 0 1 2 3 4
b) 0 1 2 3
c) 1 2 3 4 5
d) 1 2 3 4

Correct answer is: a) 0 1 2 3 4
Explanation: The `for` loop iterates from 0 to 4 (excluding 5), printing the value of `i` at each iteration.

15). What is the output of the following code?

i = 1
while i <= 3:
    print(i)
    i += 1
    if i == 2:
        continue

a) 1 2 3
b) 1 2
c) 1 2 3 4
d) 1

Correct answer is: a) 1 2 3
Explanation: The `continue` statement does not have any effect in this case as it is placed after the increment statement.

16). What is the output of the following code?

numbers = [1, 2, 3, 4, 5]
for number in numbers:
    if number == 3:
        break
    print(number)

a) 1 2 3 4 5
b) 1 2
c) 1 2 3
d) 1 2 4 5

Correct answer is: b) 1 2
Explanation: The `break` statement is executed when the number 3 is encountered, terminating the loop prematurely.

17). What is the output of the following code?

i = 0
while i < 5:
    print(i)
    i += 1
    if i == 3:
        continue

a) 0 1 2 3 4
b) 0 1 3 4
c) 0 1 2 3 4 5
d) 0 1 2 4

Correct answer is: a) 0 1 2 3 4
Explanation: The `continue` statement is executed when `i` is equal to 3, skipping the remaining code for that iteration.

18). What is the output of the following code?

for i in range(3):
    for j in range(i):
        print(i, j)

a) No output
b) 0 0
1 0
1 1
2 0
2 1
c) 0 0
1 0
1 1
2 0
d) 0 0
1 0
1 1

Correct answer is: c) 0 0
1 0
1 1
2 0
Explanation: The outer loop iterates three times, and for each iteration, the inner loop iterates `i` times, where `i` represents the current value of the outer loop.

19). What is the output of the following code?

i = 0
while i < 3:
    i += 1
    print(i)
    if i == 2:
        break

a) 1 2
b) 1 2 3
c) 0 1 2
d) 0 1 2 3

Correct answer is: a) 1 2
Explanation: The `break` statement is executed when `i` becomes 2, terminating the loop prematurely.

20). What is the output of the following code?

for i in range(1, 6):
    print(i)
else:
    print(“Loop completed”)

a) 1 2 3 4 5
Loop completed
b) 1 2 3 4 5 6
Loop completed
c) 2 3 4 5 6
Loop completed
d) 1 2 3 4 5 6 7
Loop completed

Correct answer is: a) 1 2 3 4 5
Loop completed
Explanation: The `else` block is executed after the completion of all iterations of the `for` loop.

21). What is the output of the following code?

numbers = [1, 2, 3, 4, 5]
for number in numbers:
    print(number)
    if number == 3:
        break
else:
    print(“Loop completed”)

a) 1 2 3
Loop completed
b) 1 2 3 4 5
Loop completed
c) 1 2 3 4 5
d) 1 2 3 4

Correct answer is: a) 1 2 3
Loop completed
Explanation: The `break` statement is executed when the number 3 is encountered, terminating the loop prematurely. The `else` block is not executed in this case.

22). What is the output of the following code?

i = 0
while i < 5:
    if i == 2:
        i += 1
        continue
    print(i)
    i += 1

a) 0 1 2 3 4
b) 0 1 2 3
c) 0 1 3 4
d) 0 1 2 4

Correct answer is: b) 0 1 2 3
Explanation: The `continue` statement is executed when `i` is equal to 2, skipping the remaining code for that iteration.

23). What is the output of the following code?

for i in range(3):
    for j in range(3):
        if i == j:
        break
        print(i, j)

a) No output
b) 0 1
1 2
c) 0 1
0 2
1 2
d) 0 1
0 2
1 1
1 2

Correct answer is: a) No output
Explanation: The `break` statement is executed when `i` is equal to `j`, causing the inner loop to terminate for each iteration of the outer loop.

24). What is the output of the following code?

numbers = [1, 2, 3, 4, 5]
for number in numbers:
    if number == 3:
        continue
    print(number)

a) 1 2 3 4 5
b) 1 3 4 5
c) 1 2 4 5
d) 2 3 4 5

Correct answer is: c) 1 2 4 5
Explanation: The `continue` statement is executed when the number 3 is encountered, skipping the remaining code for that iteration.

25). What is the output of the following code?

numbers = [1, 2, 3, 4, 5]
for number in numbers:
    print(number)
    if number == 3:
        break
else:
    print(“Loop completed”)

a) 1 2 3
Loop completed
b) 1 2 3 4 5
Loop completed
c) 1 2 3 4 5
d) 1 2 3 4

Correct answer is: a) 1 2 3
Loop completed
Explanation: The `break` statement is executed when the number 3 is encountered, terminating the loop prematurely. The `else` block is not executed in this case.

Python Loop MCQ : Set 3

Python Loop MCQ

1). What is the output of the following code?

for i in range(5):
    if i == 2:
        break
    print(i)
else:
    print(“Loop completed”)

a) 0 1
b) 0 1 2
c) 0 1 2 3 4
d) Loop completed

Correct answer is: a) 0 1
Explanation: The for loop iterates from 0 to 4. When i becomes 2, the break statement is executed, terminating the loop prematurely.

2). Which loop control statement is used to terminate the entire program execution in Python?
a) stop
b) exit
c) terminate
d) quit

Correct answer is: b) exit
Explanation: The exit() function is used to terminate the entire program execution, not just loops.

3). What is the output of the following code?

i = 1
while i < 5:
    print(i)
    if i == 3:
        exit()
    i += 1

a) 1 2
b) 1 2 3 4
c) 1 2 3
d) The program terminates prematurely.

Correct answer is: d) The program terminates prematurely.
Explanation: The exit() function is used to terminate the entire program execution, not just loops. In this case, the program exits when i becomes 3.

4). What is the output of the following code?

for i in range(3):
    for j in range(2):
        print(i, j)
    else:
        print(“Inner loop completed”)
else:
print(“Outer loop completed”)

a) 0 0
0 1
1 0
1 1
2 0
2 1
Inner loop completed
Inner loop completed
Inner loop completed
Outer loop completed
b) 0 0
0 1
1 0
1 1
2 0
2 1
Inner loop completed
Inner loop completed
Inner loop completed
c) 0 0
0 1
1 0
1 1
Inner loop completed
2 0
2 1
Inner loop completed
Inner loop completed
Outer loop completed
d) 0 0
0 1
1 0
1 1
2 0
2 1
Inner loop completed
Inner loop completed
Outer loop completed

Correct answer is: a) 0 0
0 1
1 0
1 1
2 0
2 1
Inner loop completed
Inner loop completed
Inner loop completed
Outer loop completed
Explanation: The inner loop executes normally for each iteration of the outer loop. The else block after the inner loop is executed if the inner loop completes all its iterations without encountering a break statement. The outer loop’s else block is executed after the outer loop finishes all its iterations without encountering a break statement.

5). What is the output of the following code?

i = 1
while i <= 3:
     print(i)
     i += 1
else:
    print(“Loop completed”)

a) 1 2 3
Loop completed
b) 1 2 3 4
Loop completed
c) 2 3 4
Loop completed
d) Loop completed

Correct answer is: a) 1 2 3
Loop completed
Explanation: The while loop prints the value of i and increments it until i becomes greater than 3. After completing all iterations, the else block is executed and prints “Loop completed”.

6). What is the output of the following code?

i = 1
while i <= 3:
    print(i)
    i += 1
    if i == 2:
        continue
else:
print(“Loop completed”)

a) 1 2 3
b) 1 2
c) 1 2 3 4
d) 1

Correct answer is: a) 1 2 3
Explanation: The continue statement, when executed, skips the remaining code for the current iteration and moves to the next iteration. In this case, it does not have any effect as it is placed after the increment statement.

7). What is the output of the following code?

for i in range(3):
    if i == 2:
        exit()
    print(i)
else:
   print(“Loop completed”)

a) 0 1
b) 0 1 2
c) 0 1 2 3
d) The program terminates prematurely.

Correct answer is: d) The program terminates prematurely.
Explanation: The exit() function is used to terminate the entire program execution, not just loops. In this case, the program exits when i become 2.

8). What is the output of the following code?

for i in range(1,50):
    if i%7 == 0 and i%5 == 0:
        print(i, end=” “)

a) 28
b) 25
c) 35
d) 49

Correct answer is: c)35
Explanation: The code iterates over the range of numbers from 1 to 49 (excluding 50). For each number, it checks if the number is divisible by both 7 and 5. If the condition is true, the number is printed

9). What is the output of the following code?

for i in range(1, 6):
    if i % 2 == 0:
        break
    print(i)

a) 1
b) 1 2
c) 1 3 5
d) 1 2 3 4 5

Correct answer is: a) 1
Explanation: The if condition checks if i is divisible by 2 (i.e., even). When i becomes 2, the break statement is executed, terminating the loop after the first iteration.

10). What is the output of the following code?

i = 1
while i <= 5:
    print(i)
    i += 2

a) 1 2 3
b) 1 3 5
c) 2 4 6
d) 1

Correct answer is: b) 1 3 5
Explanation: The while loop prints the value of i and increments it by 2 until i becomes greater than 5.

11). What is the output of the following code?

for i in range(5):
    if i == 3:
        continue
    print(i)

a) 0 1 2 4
b) 0 1 2 3 4
c) 1 2 3 4
d) 0 1 2

Correct answer is: a) 0 1 2 4
Explanation: When i is equal to 3, the continue statement is executed, skipping the remaining code for that iteration.

12). What is the output of the following code?

for i in range(0,11):
    if i != 3 or i != 6:
        print(i,end=” “)

a) 0 1 2 3 4 5 6 7 8 9 10
b) 0 1 2 4 5 6 7 8 9 10
c) 0 1 2 3 4 5 7 8 9 10
d) 0 1 2 3 4 5 6 7 8 9

Correct answer is: b) 0 1 2 4 5 6 7 8 9 10
Explanation: The condition i != 3 or i != 6 is always true for any value of i. This is because if i is 3, then it is not equal to 6, and vice versa. As a result, the condition does not exclude any values of i. Therefore, the code will print all the numbers from 0 to 10, except 3 and 6.

13). What is the output of the following code?

i = 1
while i < 5:
    print(i)
    if i == 3:
        break
    i += 1

a) 1 2 3
b) 1 2 3 4
c) 1 2 3 4 5
d) 3

Correct answer is: a) 1 2 3
Explanation: The while loop executes until i is less than 5. When i becomes 3, the break statement is executed, terminating the loop prematurely.

14). What is the purpose of the else block in a loop?
a) It is executed if the loop encounters an error.
b) It defines the initial condition of the loop.
c) It specifies the code to execute after the loop finishes normally.
d) It breaks the loop prematurely.

Correct answer is: c) It specifies the code to execute after the loop finishes normally.
Explanation: The else block in a loop is executed when the loop completes all its iterations without encountering a break statement.

15). What is the output of the following code?

for i in range(3):
    print(i)
else:
    print(“Loop completed”)

a) 0 1 2
Loop completed
b) 1 2 3
Loop completed
c) 0 1 2 3
Loop completed
d) 1 2 3 4
Loop completed

Correct answer is: a) 0 1 2
Loop completed
Explanation: The for loop iterates from 0 to 2, and after completing all iterations, the else block is executed and prints “Loop completed”.

16). What is the output of the following code?

for i in range(1, 6):
    if i % 2 == 0:
        print(i)

a) 2 4
b) 1 3 5
c) 1 2 3 4 5
d) 1 2 3 4

Correct answer is: a) 2 4
Explanation: The if condition checks if i is divisible by 2 (i.e., even). If it is even, the print statement is executed, displaying the value of i.

17). What is the output of the following code?

num1 = 0
num2 = 1
count = 0

while count < 10:
    print(num1,end=” “)
    n2 = num1 + num2
    num1 = num2
    num2 = n2
    count += 1

a) 0 1 1 2 3 5 8 13 21 34
b) 0 1 2 3 4 5 6 7 8 9
c) 1 2 3 4 5 6 7 8 9 10
d) 0 1 1 3 4 7 11 18 29 47

Correct answer is: a) 0 1 1 2 3 5 8 13 21 34
Explanation: The given code implements the Fibonacci sequence using a while loop. In each iteration, it prints the value of num1 and calculates the next Fibonacci number by updating the values of num1 and num2. The loop continues for 10 iterations, printing the Fibonacci sequence: 0 1 1 2 3 5 8 13 21 34.

18). What is the output of the following code?

i = 0
while i < 5:
    i += 1
    if i == 3:
        continue
    print(i)

a) 1 2 4 5
b) 1 2 3 4 5
c) 2 4 5
d) 1 2 3 5

Correct answer is: a) 1 2 4 5
Explanation: When i is equal to 3, the continue statement is executed, skipping the remaining code for that iteration.

19). What is the output of the following code?

i = 1
while i <= 5:
    print(i)
    i += 2

a) 1 2 3 4 5
b) 1 3 5
c) 2 4 6
d) 1

Correct answer is: b) 1 3 5
Explanation: The while loop prints the value of i and increments it by 2 until i becomes greater than 5.

20). What is the output of the following code?

i = 1
while i <= 3:
    print(i)
    i += 1
    if i == 2:
        continue

a) 1 2 3
b) 1 2
c) 1 2 3 4
d) 1

Correct answer is: a) 1 2 3
Explanation: The continue statement, when executed, skips the remaining code for the current iteration and moves to the next iteration. In this case, it does not have any effect as it is placed after the increment statement.

21). What is the output of the following code?
    
    for i in range(5):
        if i == 2:
            break
        print(i)
    else:
        print(“Loop completed”)
    
    a) 0 1
    b) 0 1 2
    c) 0 1 2 3 4
    d) Loop completed
 
Correct answer is: a) 0 1
Explanation: The for loop iterates from 0 to 4. When i becomes 2, the break statement is executed, terminating the loop prematurely.
 
22). Which loop control statement is used to terminate the entire program execution in Python?
    a) stop
    b) exit
    c) terminate
    d) quit
 
    Correct answer is: b) exit
    Explanation: The exit() function is used to terminate the entire program execution, not just loops.
 
23). What is the output of the following code?
    
    i = 1
    while i < 5:
        print(i)
        if i == 3:
            exit()
        i += 1
    
    a) 1 2
    b) 1 2 3 4
    c) 1 2 3
    d) The program terminates prematurely.
 
Correct answer is: d) The program terminates    prematurely.
Explanation: The exit() function is used to terminate the entire program execution, not just loops. In this case, the program exits when i becomes 3.
 
24). What is the output of the following code?
    
    for i in range(3):
        for j in range(2):
            print(i, j)
    
    a) 0 0
       0 1
       1 0
       1 1
       2 0
       2 1
    b) 0 0
       0 1
       1 0
       1 1
       2 0
    c) 0 0
       0 1
       1 0
       1 1
    d) 0 0
       0 1
 
Correct answer is: a) 0 0
       0 1
       1 0
       1 1
       2 0
       2 1
Explanation: The outer loop iterates three times, and for each iteration, the inner loop iterates twice, resulting in a total of six outputs.
 
25). What is the output of the following code?
    
    for i in range(3):
        print(i)
    else:
        print(“Loop completed”)
    
    a) 0 1 2
       Loop completed
    b) 1 2 3
       Loop completed
    c) 0 1 2 3
       Loop completed
    d) 1 2 3 4
       Loop completed
 
Correct answer is: a) 0 1 2
       Loop completed
Explanation: The for loop iterates from 0 to 2, and after completing all iterations, the else block is executed and prints “Loop completed”.