Python OOPS MCQ : Set 1

Python OOPS MCQ

1). Which of the following assertions most accurately sums up Python’s encapsulation?

a) It is a process of hiding the implementation details of a class.
b) It is a process of creating multiple instances of a class.
c) It is a process of defining attributes and methods in a class.
d) It is a process of converting data types in Python.

Correct answer is: a) It is a process of hiding the implementation details of a class.
Explanation: Encapsulation in Python refers to the bundling of data and methods within a class, allowing the implementation details to be hidden from the outside world.

2). Which of the following is an example of inheritance in Python?

a) A class inheriting properties from another class.
b) A class implementing an interface.
c) A class containing multiple methods.
d) A class accessing variables from a module.

Correct answer is: a) A class inheriting properties from another class.
Explanation: A fundamental aspect of object-oriented programming is inheritance. It allows a class to inherit attributes and methods from another class, known as the superclass or base class.

3). What is the purpose of the `super()` function in Python?

a) It is used to invoke a superclass’s method.
b) It is used to define class attributes.
c) It is used to create an instance of a class.
d) It is used to encapsulate class methods.

Correct answer is: a) It is used to invoke a superclass’s method.
Explanation: The `super()` function is used to call a method or access an attribute from the superclass within a subclass.

4). Which of the following is true about multiple inheritance in Python?

a) A class may descended from various superclasses.
b) Multiple classes can inherit from a single superclass.
c) A class can inherit from only one superclass.
d) Multiple classes cannot be used together in Python.

Correct answer is: a) A class may descended from various superclasses.
Explanation: Python supports multiple inheritance, which means a class can inherit attributes and methods from multiple parent classes.

5). What is the purpose of the `__init__` method in Python classes?

a) It is a special method used to create a new instance of a class.
b) It is used to define class attributes.
c) It is a built-in method that Python automatically calls.
d) It is used to delete an instance of a class.

Correct answer is: a) It is a special method used to create a new instance of a class.
Explanation: The `__init__` method, also known as the constructor, is called when a new instance of a class is created. The characteristics of the object are initialised using it.

6). What is the purpose of the `self` parameter in Python class methods?

a) It represents the superclass of a class.
b) It represents the current instance of a class.
c) It is a keyword used to define class attributes.
d) It is a built-in function in Python.

Correct answer is: b) It represents the current instance of a class.
Explanation: The `self` parameter is a reference to the current instance of a class. It is used to access and modify the object’s attributes and methods.

7). Which of the following best describes polymorphism in Python?
a) It allows a class to inherit from multiple superclasses.

b) It allows a class to hide its implementation details.
c) It allows different classes to implement the same method name.
d) It allows a class to access variables from a module.

Correct answer is: c) It allows different classes to implement the same method name.
Explanation: Polymorphism in Python refers to the ability of different classes to define the same method name but with different implementations.

8). What is method overriding in Python?

a) It allows a subclass to inherit attributes from a superclass.
b) It allows a subclass to implement its own version of a method inherited from a superclass.
c) It allows a subclass to access the private attributes of a superclass.
d) It allows a subclass to hide its implementation details.

Correct answer is: b) It allows a subclass to implement its own version of a method inherited from a superclass.
Explanation: The act of a subclass providing its own implementation of a method that is already defined in its superclass is known as method overriding.

9). What is the difference between class variables and instance variables in Python?

a) Class variables are defined within methods, while instance variables are defined outside methods.
b) Class variables are accessible only within the class, while instance variables are accessible outside the class.
c) Class variables have a different value for each instance of a class, while instance variables have the same value for all instances.
d) Class variables are used to define attributes, while instance variables are used to define methods.

Correct answer is: c) Class variables have a different value for each instance of a class, while instance variables have the same value for all instances.
Explanation: Class variables are shared among all instances of a class and have the same value, whereas instance variables have distinct values for each instance of a class.

10). Which of the following is an example of a composition relationship in Python?

a) A class inheriting properties from another class.
b) A class having an instance of another class as its attribute.
c) A class implementing an interface.
d) A class accessing variables from a module.

Correct answer is: b) A class having an instance of another class as its attribute.
Explanation: Composition is a relationship where a class contains an instance of another class as one of its attributes.

11). What is the difference between a class method and an instance method in Python?

a) Class methods can access instance attributes, while instance methods cannot.
b) Instance methods can access class attributes, while class methods cannot.
c) Class methods are defined using the `@classmethod` decorator, while instance methods are not.
d) Instance methods are called using the class name, while class methods are called using an instance of the class.

Correct answer is: b) Instance methods can access class attributes, while class methods cannot.
Explanation: Instance methods have access to both instance and class attributes, while class methods can only access class attributes.

12). What is the purpose of the `@staticmethod` decorator in Python?

a) It allows a method to be called without creating an instance of the class.
b) It converts a class method into an instance method.
c) It enables inheritance between classes.
d) It defines a method within a class.

Correct answer is: a) It allows a method to be called without creating an instance of the class.
Explanation: The `@staticmethod` decorator is used to define a static method in a class. Without creating an instance, static methods can be called on the class itself.

13). What is the role of an abstract base class (ABC) in Python?

a) It allows multiple inheritance.
b) It defines a base class that cannot be instantiated and provides a common interface for its subclasses.
c) It allows private access to class attributes.
d) It provides a mechanism for encapsulation.

Correct answer is: b) It defines a base class that cannot be instantiated and provides a common interface for its subclasses.
Explanation: An abstract base class in Python provides a common interface for its subclasses. It acts as a model for its subclasses but cannot be instantiated.

14). Which keyword is used to access the superclass from within a subclass in Python?

a) super
b) self
c) parent
d) base

Correct answer is: a) super
Explanation: The `super` keyword is used to access the superclass from within a subclass. It allows the subclass to invoke methods or access attributes of the superclass.

15). What is the purpose of the `__str__` method in Python classes?

a) It converts a class to a string representation.
b) It initializes the attributes of a class.
c) It defines the equality between two instances of a class.
d) It creates a deep copy of an instance.

Correct answer is: a) It converts a class to a string representation.
Explanation: The `__str__` method is used to define the string representation of a class. It is automatically called when the `str()` function is used on an instance of the class.

16). What is the difference between shallow copy and deep copy in Python?

a) Shallow copy copies only the references, while deep copy copies the actual values.
b) Shallow copy creates a new object, while deep copy creates a reference to the original object.
c) Shallow copy creates an independent copy of an object, while deep copy creates a nested copy.
d) Shallow copy only works for immutable objects, while deep copy works for both mutable and immutable objects.

Correct answer is: a) Shallow copy copies only the references, while deep copy copies the actual values.
Explanation: Deep copy generates a completely independent copy with its own values, whereas shallow copy creates a new object that references the values of the original object.

17). Which of the following is true about the `__del__` method in Python?

a) It is used to define class attributes.
b) It is automatically invoked whenever a class instance is generated.
c) It is a destructor method that is called when an instance is about to be destroyed.
d) It is used to initialize the attributes of a class.

Correct answer is: c) It is a destructor method that is called when an instance is about to be destroyed.
Explanation: The `__del__` method is a destructor method in Python. It is automatically called when an instance of a class is about to be destroyed.

18). What is the purpose of method overloading in Python?

a) It allows a method to have different implementations based on the number and types of arguments.
b) It allows a method to override another method from a superclass.
c) It allows a method to be called without passing any arguments.
d) It allows a method to be called from within another method.

Correct answer is: a) It allows a method to have different implementations based on the number and types of arguments.
Explanation: Method overloading in Python allows a method to have multiple implementations with different numbers and types of arguments.

19). Which of the following statements is true about method overriding in Python?

a) A subclass can override a method in its superclass.
b) A subclass can only override a private method in its superclass.
c) A subclass can override a method in any other class.
d) A subclass cannot override a method in its superclass.

Correct answer is: a) A subclass can override a method in its superclass.
Explanation: A subclass can offer its own implementation of a method that is already defined in its superclass by using method overriding.

20). What is the purpose of the `@property` decorator in Python?

a) It is used to define a class attribute.
b) It is used to define a static method.
c) It is used to create a read-only property with a getter method.
d) It is used to create a write-only property with a setter method.

Correct answer is: c) It is used to create a read-only property with a getter method.
Explanation: The `@property` decorator is used to define a getter method for creating a read-only property in a class.

21). What is abstraction?

a) The ability of an object to take on different forms
b) The process of one class inheriting the properties and methods of another class
c) The process of hiding the implementation details of an object from the user
d) The process of representing abstract concepts

Correct answer is: d) The process of representing abstract concepts
Explanation: Abstraction is one of the most important features of object-oriented programming. It allows for the creation of objects that represent things that do not have a physical representation in the real world. For example, a class can be used to represent the concept of a “person”, even though there is no such thing as a “person” in the real world.

22). What distinguishes a constructor from a method?

a) A constructor is a method that is called when an object of that class is created, while a method is a function that is associated with a class
b) A constructor is a method that is used to initialize the data members of an object, while a method is a function that is used to perform operations on an object
c) A constructor is a method that is called when an object of that class is deleted, while a method is a function that is called when an object of that class is modified
d) None of the above

Correct answer is: b) A constructor is a method that is used to initialize the data members of an object, while a method is a function that is used to perform operations on an object

Python File Handling MCQ : Set 4

Python File Handling MCQ

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

				
					file = open('file.txt')
data = file.read().split()
m_num = []
for val in data:
    if val.isnumeric():
        if len(val) == 10:
            m_num.append(val)
print("Mobile numbers in the file: ", m_num)
				
			

a) Read the contents of the file and split them into a list
b) Extract all the numeric values from the file
c) Filter and collect 10-digit mobile numbers from the file
d) Print the content of the file

Correct answer is: c) Filter and collect 10-digit mobile numbers from the file
Explanation: The given code opens a file named ‘file.txt’ and reads its contents using the `read()` method. The content is then split into a list of individual words using the `split()` method. Next, an empty list `m_num` is created to store the mobile numbers. The code then iterates through each value in the list `data` and checks if it is a numeric value using the `isnumeric()` method. If the value is numeric, it further checks if its length is equal to 10 digits. If both conditions are met, the value is considered a 10-digit mobile number and is appended to the `m_num` list. Finally, the code prints the collected mobile numbers using the `print()` function. The purpose of this code snippet is to filter and extract 10-digit mobile numbers from the given file.

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

				
					file = open("file name", "r")
lines = file.readlines()
count = 0
for line in lines:
    count += 1
print("Total number of lines in the file: ", count)
				
			

a) To read the contents of a file and store them in a list
b) To count the number of characters in a file
c) To count the number of words in a file
d) To count the number of lines in a file

Correct answer is: d) To count the number of lines in a file
Explanation: The given code opens a file named “file name” in read mode using the `open()` function and assigns it to the `file` variable. Then, it uses the `readlines()` method to read all the lines from the file and stores them in a list called `lines`. Next, a variable `count` is initialized to 0. The code then iterates over each line in the `lines` list using a `for` loop. For each line, the `count` variable is incremented by 1, effectively counting the number of lines in the file. Finally, the total number of lines in the file is printed as output using the `print()` function.

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

				
					import os
info = os.stat('file.txt')
print("Size of the file: ", info.st_size)
				
			

a) To check if the file ‘file.txt’ exists in the current directory
b) To get the size of the file ‘file.txt’
c) To delete the file ‘file.txt’
d) To rename the file ‘file.txt’

Correct answer is: b) To get the size of the file ‘file.txt’
Explanation: The code uses the `os.stat()` function from the `os` module to retrieve the file information for the file named ‘file.txt’. The `os.stat()` function returns a named tuple with several attributes representing file information. In this case, the code accesses the `st_size` attribute of the `info` named tuple, which corresponds to the size of the file in bytes. The code then prints the size of the file to the console using the `print()` function. Therefore, the purpose of this code snippet is to obtain and display the size of the file ‘file.txt’.

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

				
					tup = ('1', '2', '3')
f = open('file.txt', 'w')
f.write(" ".join(tup))
f.close()
				
			

a) It creates a tuple containing three elements: ‘1’, ‘2’, and ‘3’.
b) It opens a file named ‘file.txt’ in write mode.
c) It writes the string representation of the tuple elements separated by a space to the file.
d) It closes the file after writing the data.

Correct answer is: c) It writes the string representation of the tuple elements separated by a space to the file.
Explanation: It creates a tuple named `tup` containing three elements: ‘1’, ‘2’, and ‘3’. It opens a file named ‘file.txt’ in write mode using the `open()` function with the mode parameter set to ‘w’. It writes the string representation of the elements in the tuple `tup` to the file by using the `write()` method. The elements are joined together using the `join()` method with a space as the separator. Finally, it closes the file using the `close()` method to ensure that all the changes are saved.

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

				
					f = open('file.txt','r')
print(f.closed)
f.close()
print(f.closed)
				
			

a) To open a file in read mode, check if the file is closed, and then close the file
b) To open a file in write mode, check if the file is closed, and then close the file
c) To open a file in append mode, check if the file is closed, and then close the file
d) To open a file in read mode and check if the file is closed, without closing the file

Correct answer is: a) To open a file in read mode, check if the file is closed, and then close the file
Explanation: The code opens a file named ‘file.txt’ in read mode using the `open()` function with the mode parameter set to ‘r’. The `print(f.closed)` statement is used to check the status of the file object’s `closed` attribute, which indicates whether the file is closed or not. Since the file is just opened, the output will be `False`. The `f.close()` statement is used to explicitly close the file. The `print(f.closed)` statement is called again to check the status of the file object’s `closed` attribute after closing the file. Since the file is closed, the output will be `True`.

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

				
					file = open('file.txt')
words = file.read().split()
list1 = []
for word in words:
    for char in word:
        list1.append(char)
print("Characters in the file in the list: ", list1)
				
			

a) To count the number of characters in a file.
b) To extract all the words from a file.
c) To create a list of characters from a file.
d) To concatenate all the words in a file.

Correct answer is: c) To create a list of characters from a file.
Explanation: The given code opens a file named ‘file.txt’ using the `open()` function without specifying a mode, which defaults to read mode (‘r’). It then reads the content of the file using the `read()` method and splits the content into a list of words using the `split()` method. The code initializes an empty list `list1` to store the characters from the file. It then iterates over each word in the `words` list and, for each word, iterates over each character using a nested loop. It appends each character to the `list1` using the `append()` method. Finally, it prints the message “Characters in the file in the list: ” followed by the `list1` containing all the characters from the file.

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

				
					data = data2 = ""
with open('file1.txt') as f:
    data = f.read()
with open('file2.txt') as f:
    data2 = f.read()
data += "\n"
data += data2

with open ('file3.txt', 'w') as f:
    f.write(data)
				
			

a) It reads the contents of two files and concatenates them.
b) It copies the contents of one file to another file.
c) It appends the contents of one file to another file.
d) It deletes the contents of two files and saves the result in another file.

Correct answer is: a) It reads the contents of two files and concatenates them.
Explanation: The given code snippet opens two files, ‘file1.txt’ and ‘file2.txt’, and reads their contents using the `read()` method. The contents of the two files are stored in the variables `data` and `data2` respectively. The code then appends a newline character (`”\n”`) to the `data` variable and concatenates the contents of `data2` to `data`. Finally, the code opens a file named ‘file3.txt’ in write mode using the `open()` function with the `’w’` argument. It writes the concatenated data to ‘file3.txt’ using the `write()` method, effectively saving the combined contents of ‘file1.txt’ and ‘file2.txt’ in ‘file3.txt’.

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

				
					file = open('file name')
words = file.read().split()
count = 0
for word in words:
    for char in word:
        if char.isalpha():
            count += 1
print("Total number of characters in the file: ", count)
				
			

a) Count the number of lines in the file.
b) Count the number of words in the file.
c) Count the number of alphabetic characters in the file.
d) Count the number of non-alphabetic characters in the file.

Correct answer is: c) Count the number of alphabetic characters in the file.
Explanation: The given code opens a file and reads its contents. It then splits the contents into words and initializes a counter, `count`, to zero. The code then iterates over each word and checks each character in the word. If the character is alphabetic (a letter), it increments the `count` by 1. Finally, it prints the total number of alphabetic characters in the file. Therefore, the purpose of this code is to count the number of alphabetic characters in the file.

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

				
					file = open('file.txt')
words = file.read().split()
count = 0
for word in words:
    for char in word:
        if char.isupper():
            count += 1
print("Total number of uppercase characters in the file: ", count)
				
			

a) Count the total number of words in the file.
b) Count the total number of lines in the file.
c) Count the total number of lowercase characters in the file.
d) Count the total number of uppercase characters in the file.

Correct answer is:
d) Count the total number of uppercase characters in the file.
Explanation: `file = open(‘file.txt’)`: This line opens the file named “file.txt” in the default mode (‘r’), creating a file object called `file`. `words = file.read().split()`: The `read()` method is used to read the content of the file, and `split()` is called to split the content into a list of words. The list of words is stored in the variable `words`. `count = 0`: A variable `count` is initialized to 0 to keep track of the number of uppercase characters. `for word in words:`: This starts a loop to iterate over each word in the `words` list. `for char in word:`: This nested loop iterates over each character in the current word. `if char.isupper():`: The `isupper()` method is called on each character to check if it is an uppercase character. If the condition in step 6 is `True`, the code increments the `count` variable by 1. After both loops complete, the code prints the total number of uppercase characters found in the file.

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

				
					file = open('file.txt')
words = file.read().split()
count = 0
for word in words:
    for char in word:
        if char.islower():
            count += 1
print("Total number of lowercase characters in the file: ", count)
				
			

a) Count the total number of characters in the file
b) Count the total number of words in the file
c) Count the total number of uppercase characters in the file
d) Count the total number of lowercase characters in the file

Correct answer is: d) Count the total number of lowercase characters in the file
Explanation: The given code opens a file named ‘file.txt’ and reads its content. The content is then split into individual words. The variable `count` is initialized to 0. Next, a nested loop iterates over each word and each character within the word. The `if` statement checks if the character is lowercase using the `islower()` method. If it is lowercase, the `count` variable is incremented. Finally, the code prints the total number of lowercase characters in the file using the `print()` statement.

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

				
					file = open('file name')
words = file.read().split()
count = 0
for word in words:
    for char in word:
        if char.isnumeric():
            count += 1
print("Total number of digits in the file: ", count)
				
			

a) Count the total number of words in the file.
b) Calculate the average word length in the file.
c) Determine the frequency of each digit in the file.
d) Count the total number of digits in the file.

Correct answer is: d) Count the total number of digits in the file.
Explanation: The given code opens a file using the ‘file name’ and reads its contents. It then splits the content into individual words and initializes a counter variable, `count`, to keep track of the number of digits found in the file. The code then iterates over each word in the file. For each word, it iterates over each character and checks if the character is numeric using the `isnumeric()` method. If a character is numeric, the counter `count` is incremented. Finally, the code prints the total number of digits found in the file. Therefore, the purpose of the code is to count the total number of digits in the file and display the result.

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

				
					file = open('file.txt')
file.readline()
print("Position of a cursor in the file: ", file.tell())
				
			

a) To open the file ‘file.txt’ in read mode
b) To open the file ‘file.txt’ in write mode
c) To read a line from the file ‘file.txt’
d) To print the current position of the file cursor

Correct answer is: d) To print the current position of the file cursor
Explanation: The given code opens a file named ‘file.txt’ using the `open()` function without specifying the mode, which defaults to read mode. The `file.readline()` method is then called to read a single line from the file. Finally, the `file.tell()` method is used to retrieve the current position of the file cursor, and it is printed using the `print()` function. The purpose of this code snippet is to determine and display the position of the file cursor within the file after reading a line.

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

				
					file = open('file.txt')
file.readline()
print("Position of a cursor in the file: ",file.tell())
file.seek(10)
print("Position of a cursor in the file: ",file.tell())
				
			

a) To open a file and read its contents line by line.
b) To retrieve the current position of the file cursor.
c) To move the file cursor to a specific position.
d) To print the contents of the file starting from a specific position.

Correct answer is: c) To move the file cursor to a specific position.
Explanation: The code opens a file named “file.txt” using the `open()` function. It then reads a single line from the file using the `readline()` method, although this line is not utilized further. The `tell()` method is used to retrieve the current position of the file cursor, which represents the byte offset from the beginning of the file. The code then uses the `seek()` method to move the file cursor to a specific position, in this case, position 10. Finally, the `tell()` method is called again to print the updated position of the file cursor. Therefore, the purpose of this code snippet is to demonstrate the movement of the file cursor to a specific position within the file.

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

				
					file = open('file.txt')
data = list(file.readlines())
for line in reversed(data):
    print(line)
				
			

a) To open a file and print its contents in reverse order.
b) To open a file and store its contents in a list.
c) To open a file and print its contents line by line.
d) To open a file and append its contents to an existing list.

Correct answer is: a) To open a file and print its contents in reverse order.
Explanation: The given code snippet opens a file named ‘file.txt’ using the `open()` function and assigns it to the variable `file`. It then reads the contents of the file using the `readlines()` method and converts it into a list by using the `list()` function. The list of lines is stored in the variable `data`. The subsequent for loop iterates over the `data` list in reverse order using the `reversed()` function. Inside the loop, each line is printed using the `print()` function. As a result, the code prints the contents of the ‘file.txt’ file in reverse order, displaying each line on a separate line of the output.

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

				
					file = open('file name')
words = file.read().split()
vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
count = 0
for word in words:
    for char in word:
        if char in vowels:
            count += 1
print("Total number of vowels in the file: ", count)
				
			

a) Count the total number of words in a file
b) Count the total number of lines in a file
c) Count the total number of vowels in a file
d) Count the total number of consonants in a file

Correct answer is: c) Count the total number of vowels in a file
Explanation: The code begins by opening a file using the `open()` function and assigning it to the `file` variable. The file name is specified as `’file name’` (please note that the actual file name would be provided in place of `’file name’`). The `file.read()` method is used to read the entire contents of the file as a single string. The `split()` method is then called on the string obtained from `file.read()` to split it into a list of words. By default, it splits the string at whitespace characters. The code initializes a list called `vowels` containing all the vowels in both lowercase and uppercase.A variable called `count` is initialized to 0. This variable will be used to keep track of the number of vowels encountered.The code then iterates over each word in the `words` list using a nested loop. Within the nested loop, each character in the current word is checked to see if it is present in the `vowels` list. If a character is found in the `vowels` list, it means it is a vowel, and the `count` variable is incremented by 1.Finally, the total number of vowels found in the file is printed using the `print()` function.

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

				
					file = open('file.txt')
words = file.read().split()
for word in words:
    if len(word) < 5:
        print(word, end=" ")
				
			

a) Open a file named ‘file.txt’ and read its content.
b) Open a file named ‘file.txt’ and write to it.
c) Count the number of words in a file named ‘file.txt’.
d) Print all words from a file named ‘file.txt’ that have a length less than 5.

Correct answer is: d) Print all words from a file named ‘file.txt’ that have a length less than 5.
Explanation: The code opens a file named ‘file.txt’ using the `open()` function and reads its content. The content is then split into a list of words using the `split()` method. The code then iterates over each word in the list and checks if its length is less than 5 characters. If a word satisfies the condition, it is printed using the `print()` function with the `end` parameter set to a space character. Therefore, the code’s purpose is to print all words from the file ‘file.txt’ that have a length less than 5.

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

				
					f1 = open("file.txt", "r")
data = f1.read()
data = data.replace(" ", "_")
f2 = open("file1.txt", "w")
f2.write(data)
				
			

a) Count the number of spaces in a text file and replace them with underscores.
b) Open a file named “file.txt” in read mode, replace all spaces with underscores, and save the modified content in a new file named “file1.txt”.
c) Open a file named “file.txt” in write mode, replace all underscores with spaces, and save the modified content in the same file.
d) Read the content of a file named “file.txt” and write it to a new file named “file1.txt” without any modifications.

Correct answer is: b) Open a file named “file.txt” in read mode, replace all spaces with underscores, and save the modified content in a new file named “file1.txt”.
Explanation: Opens a file named “file.txt” in read mode using the `open()` function and assigns it to the variable `f1`. Reads the entire content of the file using the `read()` method and stores it in the variable `data`. Replaces all occurrences of spaces with underscores in the `data` string using the `replace()` method. Opens a new file named “file1.txt” in write mode using the `open()` function and assigns it to the variable `f2`. Writes the modified `data` string to the “file1.txt” file using the `write()` method.

Python File Handling MCQ : Set 3

Python FIle Handling MCQ

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

				
					f = open("file1", "a")
f.write("\nlearning python is fun")
f.close()
				
			

a) The code appends the string “learning python is fun” to the file named “file1” and then closes the file.
b) The code opens the file named “file1” for reading, writes the string “learning python is fun” to the file, and then closes the file.
c) The code creates a new file named “file1” and writes the string “learning python is fun” to the file, and then closes the file.
d) The code raises an error because the file “file1” does not exist.

Correct answer is: a) The code appends the string “learning python is fun” to the file named “file1” and then closes the file.
Explanation: In the given code, the file “file1” is opened in “append” mode by using the second argument “a” in the `open()` function. This allows the code to append content to the existing file rather than overwriting it. The `write()` method is then used to write the string “\nlearning python is fun” to the file, which adds a new line followed by the specified text. Finally, the `close()` method is called to close the file and ensure that any changes are saved.

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

				
					f = open("file1", "a")
f.write("\nlearning python is fun")
f.close()
				
			

a) The code appends the string “learning python is fun” to the file named “file1” and then closes the file.
b) The code opens the file named “file1” for reading, writes the string “learning python is fun” to the file, and then closes the file.
c) The code creates a new file named “file1” and writes the string “learning python is fun” to the file, and then closes the file.
d) The code raises an error because the file “file1” does not exist.

Correct answer is: a) The code appends the string “learning python is fun” to the file named “file1” and then closes the file.
Explanation: In the given code, the file “file1” is opened in “append” mode by using the second argument “a” in the `open()` function. This allows the code to append content to the existing file rather than overwriting it. The `write()` method is then used to write the string “\nlearning python is fun” to the file, which adds a new line followed by the specified text. Finally, the `close()` method is called to close the file and ensure that any changes are saved.

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

				
					file = open("file1", "r")
linesList = file.readlines()
for i in linesList[:3]:
    print(i)
				
			

a) It prints the first three lines of the file “file1”.
b) It prints the first three characters of each line in the file “file1”.
c) It prints the entire contents of the file “file1”.
d) It raises an error due to an incorrect file name.

Correct answer is: a) It prints the first three lines of the file “file1”.
Explanation: The code opens a file named “file1” in read mode using the `open()` function. It then reads all the lines from the file using the `readlines()` method and stores them in the `linesList` variable. The subsequent for loop iterates over the first three lines of the `linesList` and prints each line using the `print()` function. As a result, the code will output the first three lines of the file “file1”.

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

				
					import re
file = open("file name", "r") 
for line in file:
    s = line.strip()
    result = re.findall(r"[A-Za-z0-9._%+-]+"
                     r"@[A-Za-z0-9.-]+"
                     r"\.[A-Za-z]{2,4}", s)
    print(result)
				
			

a) Prints all the lines from the file.
b) Prints the email addresses found in each line of the file.
c) Prints the number of email addresses found in the file.
d) Raises an error due to an invalid regular expression.

Correct answer is: b) Prints the email addresses found in each line of the file.
Explanation: The given code reads a file line by line using a loop. For each line, it removes leading and trailing whitespaces using `line.strip()` and assigns the result to the variable `s`. Then, the regular expression `r”[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}”` is used to find email addresses within the line. The `re.findall()` function is used to find all non-overlapping matches of the regular expression pattern in the given string (`s`). The `re.findall()` function returns a list of all the email addresses found in the line. Each email address is a string matching the regular expression pattern. Finally, the code prints the `result`, which is the list of email addresses found in each line of the file.

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

				
					file = open('file name')
data = file.readlines()
print("1st line")
print(data[0])
				
			

a) It will raise a FileNotFoundError.
b) It will print “1st line” and then raise an IndexError.
c) It will print “1st line” and then print the first line of the file.
d) It will print “1st line” and then print an empty line.

Correct answer is: c) It will print “1st line” and then print the first line of the file.
Explanation: The given code opens a file named “file name” using the `open()` function and assigns the file object to the variable `file`. Then, it reads all the lines from the file using the `readlines()` method and stores them in the variable `data`. The next two lines of code print “1st line” and the first line of the file, respectively. Since the `readlines()` method reads all the lines of the file and stores them in a list, `data[0]` represents the first line of the file. Therefore, when `print(data[0])` is executed, it will print the content of the first line of the file. Hence, the output of the code will be “1st line” followed by the first line of the file.

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

				
					f1 = open('file1.txt', 'r')
f2 = open('file.txt', 'w')
  
cont = f1.readlines()
for i in range(0, len(cont)):
    if(i % 2 != 0):
        f2.write(cont[i])
    else:
        pass
  
f2.close()
				
			

a) The code reads the contents of the file named ‘file name’ and writes the odd-indexed lines to a new file named ‘file.txt’.
b) The code reads the contents of the file named ‘file.txt’ and writes the odd-indexed lines to a new file named ‘file name’.
c) The code reads the contents of the file named ‘file name’ and writes the even-indexed lines to a new file named ‘file.txt’.
d) The code reads the contents of the file named ‘file.txt’ and writes the even-indexed lines to a new file named ‘file name’.

Correct answer is: a) The code reads the contents of the file named ‘file1.txt’ and writes the odd-indexed lines to a new file named ‘file.txt’.
Explanation: The code opens two files: ‘file1.txt’ in read mode (`’r’`) and ‘file.txt’ in write mode (`’w’`). The `f1.readlines()` method reads all the lines from the file named ‘file name’ and stores them in the `count` variable as a list of strings. The `for` loop iterates over the indices of the `count` list using the `range()` function. For each iteration, the code checks if the index `i` is odd (`i % 2 != 0`). If the index is odd, it means the line is odd-indexed, and the code writes that line to the file named ‘file.txt’ using `f2.write(cont[i])`. If the index is even, the `else` block is executed, which does nothing (`pass` statement). Finally, the code closes the file named ‘file.txt’ using `f2.close()`. Therefore, the code reads the contents of the file named ‘file1.txt’ and writes only the odd-indexed lines to a new file named ‘file.txt’.

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

				
					with open('file.txt') as f:
    data_list = f.readlines()
    print(data_list)
				
			

a) `file.txt`
b) `data_list`
c) `[‘file.txt’]`
d) The contents of the ‘file.txt’ file as a list of strings

Correct answer is: d) The contents of the ‘file.txt’ file as a list of strings
Explanation: The code opens the file named ‘file.txt’ using the `open()` function and assigns it to the file object `f`. Then, the `readlines()` method is called on `f` to read the contents of the file and store them in the `data_list` variable as a list of strings. Finally, the `print()` function is used to display the contents of `data_list`. Therefore, the output will be the contents of the ‘file.txt’ file, each line represented as a string element in the `data_list` list.

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

				
					file = open('file.txt')
words = file.read().split()
max_len = len(max(words, key=len))
for word in words:
    if len(word) == max_len:
        print(word)
				
			

a) The code will result in an error.
b) The code will print all the words in the file.
c) The code will print the longest word in the file.
d) The code will print the number of words in the file.

Correct answer is: c) The code will print the longest word in the file.
Explanation: The code opens a file named ‘file.txt’ and reads its content. It splits the content into individual words and stores them in the `words` list. The variable `max_len` is assigned the length of the longest word in the list `words`, using the `max()` function and the `key=len` argument to compare the words based on their lengths. The subsequent `for` loop iterates over each word in the `words` list. It checks if the length of the word matches the `max_len` value. If the lengths match, the word is printed. Therefore, the code will print the longest word in the file.

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

				
					file = open('file.txt')
words = file.read().split()
count = 0
for word in words:
    if word == 'python':
        count += 1
print("Count of python in the file: ", count)
				
			

a) To open a file and read its contents into a list of words
b) To count the occurrences of the word ‘python’ in a file
c) To write the count of the word ‘python’ to a new file
d) To replace all occurrences of the word ‘python’ in a file

Correct answer is: b) To count the occurrences of the word ‘python’ in a file
Explanation: The given code opens a file named ‘file.txt’ using the `open()` function without specifying the mode, which defaults to read mode. It then reads the contents of the file using the `read()` method and splits the contents into a list of words using the `split()` method. Next, a variable `count` is initialized to 0. The code then iterates over each word in the `words` list using a `for` loop. Within the loop, it checks if the current word is equal to ‘python’. If it is, the `count` variable is incremented by 1. After iterating through all the words, the code prints the final count of the word ‘python’ using the `print()` function. Therefore, the purpose of this code is to count the occurrences of the word ‘python’ in the contents of the file ‘file.txt’ and display the count to the user.

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

				
					import random
lines = open('file.txt').read().splitlines()
data = random.choice(lines)
print(data)
				
			

a) To open a file and read its contents
b) To randomly select a line from a file and store it in the variable ‘data’
c) To shuffle the lines of a file and print the shuffled data
d) To generate random data and store it in a file named ‘file.txt’

Correct answer is: b) To randomly select a line from a file and store it in the variable ‘data’
Explanation: The code opens a file named ‘file.txt’ using the `open()` function and reads its contents using the `read()` method. It then splits the contents into separate lines using the `splitlines()` method and stores them in the `lines` variable. The `random.choice()` function is used to randomly select a line from the `lines` list and assign it to the `data` variable. Finally, the selected line is printed using the `print()` function. Therefore, the purpose of this code is to randomly choose a line from the file and store it in the variable ‘data’.

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

				
					with open('file1.txt', 'r') as data_file:
    with open('file2.txt', 'a') as output_file:
        for line in data_file:
            output_file.write(line.upper())

				
			

a) Copy the contents of ‘file1.txt’ to ‘file2.txt’.
b) Append the contents of ‘file1.txt’ to ‘file2.txt’, converting all text to uppercase.
c) Append the contents of ‘file2.txt’ to ‘file1.txt’, converting all text to uppercase.
d) Create a new file named ‘file2.txt’ and write the uppercase version of ‘file1.txt’ into it.

Correct answer is: b) Append the contents of ‘file1.txt’ to ‘file2.txt’, converting all text to uppercase.
Explanation: The code opens two files: ‘file1.txt’ in read mode (`’r’`) and ‘file2.txt’ in append mode (`’a’`). When the block is exited the `with` statement ensures that the files are automatically closed. The code then enters a loop where it iterates over each line in ‘file1.txt’. For each line, the `upper()` method is called to convert the text to uppercase. The converted line is then written to ‘file2.txt’ using the `write()` method. Therefore, the purpose of the code is to read the contents of ‘file1.txt’, convert the text to uppercase, and append the converted text to ‘file2.txt’.

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

				
					with open('file1.txt', 'r') as data_file:
        with open('file2.txt', 'a') as output_file:
            for line in data_file:
                output_file.write(line.lower())

				
			

a) It reads the content of ‘file1.txt’ and writes it to ‘file2.txt’ in lowercase.
b) It reads the content of ‘file1.txt’ and appends it to ‘file2.txt’ in lowercase.
c) It reads the content of ‘file1.txt’ and writes it to ‘file2.txt’ in uppercase.
d) It reads the content of ‘file1.txt’ and appends it to ‘file2.txt’ in uppercase.

Correct answer is: a) It reads the content of ‘file1.txt’ and writes it to ‘file2.txt’ in lowercase.
Explanation: The given code snippet opens two files, ‘file1.txt’ and ‘file2.txt’, using the `open()` function and file mode arguments (‘r’ for reading and ‘a’ for appending). The code then uses a nested context manager to read each line from ‘file1.txt’ and write it to ‘file2.txt’ in lowercase. The `for` loop iterates over the lines of ‘file1.txt’, and the `write()` method of the output_file object writes each line in lowercase to ‘file2.txt’. The code utilizes the `with` statement to ensure that the files are automatically closed after the code block is executed. Therefore, the purpose of the code is to convert the content of ‘file1.txt’ to lowercase and store it in ‘file2.txt’.

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

				
					file = open('file.txt')
words = file.read().split()
count = 0
for word in words:
    count += 1
print("Count of words in the file: ", count)
				
			

a) To open a file and read its content as a string
b) To count the number of lines in a file
c) To count the number of characters in a file
d) To count the number of words in a file

Correct answer is: d) To count the number of words in a file
Explanation: The code opens a file named ‘file.txt’ using the `open()` function without specifying a mode, which defaults to read mode (`’r’`). It then reads the content of the file using the `read()` method, which returns the content as a string. The `split()` method is then used to split the string into a list of words based on whitespace. A count variable is initialized to 0, and a `for` loop iterates over each word in the `words` list. For each word encountered, the count variable is incremented by 1. Finally, the total count of words is printed using the `print()` function. Therefore, the purpose of this code is to open a file, read its content, split the content into words, and count the number of words in the file.

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

				
					import string, os
if not os.path.exists("letters"):
    os.makedirs("letters")
for letter in string.ascii_uppercase:
    with open(letter + ".txt", "w") as f:
        f.writelines(letter)
				
			

a) To create a directory named “letters” and write a separate file for each uppercase letter in the English alphabet, where each file contains only the corresponding letter.
b) To read existing files in the “letters” directory and write the uppercase letters of the English alphabet into them.
c) To create a directory named “letters” and write all uppercase letters of the English alphabet into a single file named “letters.txt”.
d) To check if the “letters” directory exists and write all uppercase letters of the English alphabet into a single file named “letters.txt”.

Correct answer is: a) To create a directory named “letters” and write a separate file for each uppercase letter in the English alphabet, where each file contains only the corresponding letter.
Explanation: The code first checks if the directory named “letters” exists using `os.path.exists()`. If the directory doesn’t exist, it is created it using `os.makedirs()`. Then, it iterates through each uppercase letter of the English alphabet using `string.ascii_uppercase`. Within the loop, it opens a file with the name of the current letter concatenated with “.txt” in write mode using `open()` with the “w” argument. It uses a `with` statement to ensure proper file handling, automatically closing the file after writing. It writes the current letter to the file using `f.writelines()`. As a result, the code creates a separate file for each uppercase letter in the “letters” directory, where each file contains only the corresponding letter.

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

				
					file = open('file.txt')
words = file.read().split()
even = []
odd = []
for word in words:
    if len(word) % 2 == 0:
        even.append(word)
    else:
        odd.append(word)
print("Words having even length: ", even)
print("Words having odd length: ", odd)
				
			

a) Count the total number of words in the ‘file.txt’ file.
b) Split the contents of the ‘file.txt’ file into a list of words.
c) Separate the words with even and odd lengths from the ‘file.txt’ file.
d) Print the contents of the ‘file.txt’ file as a single string.

Correct answer is: c) Separate the words with even and odd lengths from the ‘file.txt’ file.
Explanation: The given code opens a file named ‘file.txt’ using the `open()` function and assigns the file object to the variable `file`. It then reads the contents of the file using the `read()` method and splits the contents into a list of words using the `split()` method. The empty lists `even` and `odd` are initialized to store words with even and odd lengths, respectively.

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

				
					file = open('file.txt')
words = file.read().split()
vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
count = 0
for word in words:
    for char in word:
        if char not in vowels:
            count += 1
print("Total number of consonants in the file: ", count)
				
			

a) Count the total number of vowels in the given file
b) Count the total number of characters in the given file
c) Count the total number of consonants in the given file
d) Check if the file contains any vowels

Correct answer is: c) Count the total number of consonants in the given file
Explanation: The given code opens a file named “file.txt” and reads its contents. It splits the content into individual words and assigns them to the `words` list. It then initializes a variable `count` to keep track of the number of consonants. Next, the code defines a list of vowels containing both lowercase and uppercase vowels. It then enters a nested loop structure where it iterates over each word in the `words` list and, for each word, iterates over each character in the word. Within the nested loop, it checks if the current character (`char`) is not present in the `vowels` list. If the character is not a vowel, it increments the `count` variable by 1. This process repeats for each character in each word. Finally, the code prints the value of `count`, which represents the total number of consonants present in the file.

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

				
					f1 = open('file.txt', 'r')
f2 = open('file2.txt', 'a')
lines = f1.readlines()
for line in lines:
    if 't' in line:
        f2.write(line)
f1.close()
f2.close()

				
			

a) It reads the contents of ‘file.txt’ and writes lines containing the letter ‘t’ to ‘file2.txt’.
b) It appends the contents of ‘file.txt’ to ‘file2.txt’.
c) It reads the contents of ‘file.txt’ and prints lines containing the letter ‘t’.
d) It creates a new file ‘file2.txt’ and writes lines containing the letter ‘t’ from ‘file.txt’.

Correct answer is: a) It reads the contents of ‘file.txt’ and writes lines containing the letter ‘t’ to ‘file2.txt’.
Explanation: The code opens two files, ‘file.txt’ in read mode (`’r’`) and ‘file2.txt’ in append mode (`’a’`). It then reads all the lines from ‘file.txt’ using `f1.readlines()`. The code then iterates over each line and checks if the letter ‘t’ is present in the line using the condition `if ‘t’ in line`. If the condition is true, the line is written to ‘file2.txt’ using `f2.write(line)`. Finally, the code closes both file objects using `f1.close()` and `f2.close()`.

Python File Handling MCQ : Set 2

Python File Handling MCQ

1). Which method is used to truncate a file to a specified size in Python?

a) truncate()
b) resize()
c) reduce()
d) shrink()

Correct answer is: a) truncate()
Explanation: The `truncate()` method is used to truncate a file to a specified size in Python. If the specified size is smaller than the current size, the file will be truncated. If it is larger, the file size will be increased, and null bytes will be added.

2). Which of the following methods is used to read a specific number of bytes from a file in Python?

a) read()
b) readlines()
c) readline()
d) read(size)

Correct answer is: d) read(size)
Explanation: The `read(size)` method is used to read a specific number of bytes from a file in Python. It takes an integer `size` as an argument and returns the specified number of bytes from the file.

3). How can you create a new file and write data to it in Python?

a) create(file, ‘w’)
b) write(file, ‘w’)
c) open(file, ‘w’)
d) make(file, ‘w’)

Correct answer is: c) open(file, ‘w’)
Explanation: To create a new file and write data to it in Python, you need to use the `open()` function with the file name as the first argument and `’w’` as the second argument. This opens the file in write mode and creates a new file if it does not exist.

4). Which method is used to iterate over the lines of a file object in Python?

a) iterate()
b) lines()
c) readlines()
d) readline()

Correct answer is: c) readlines()
Explanation: The `readlines()` method is used to iterate over the lines of a file object in Python. It returns a list of lines, which can be iterated over using a loop or other iteration methods.

5). What happens if you try to open a file in write mode that already exists?

a) The existing file will be overwritten with the new content
b) An error is raised
c) The existing file will be truncated
d) The program waits until the file is deleted

Correct answer is: a) The existing file will be overwritten with the new content
Explanation: If you open a file in write mode using the `open()` function and the file already exists, the existing file will be overwritten with the new content. Any previous content in the file will be lost.

6). Which method is used to copy a file in Python?

a) copyfile()
b) move()
c) duplicate()
d) os.copy()

Correct answer is: a) copyfile()
Explanation: The `copyfile()` function from the `shutil` module is used to copy a file in Python. It takes the source file path and the destination file path as arguments and copies the contents of the source file to the destination file.

7). How can you read the contents of a file as a single string in Python?

a) read()
b) readlines()
c) readline()
d) readall()

Correct answer is: a) read()
Explanation: The `read()` method is used to read the contents of a file as a single string in Python. It reads the entire content of the file and returns it as a string.

8). Which of the following is NOT a valid method to close a file in Python?

a) close()
b) flush()
c) exit()
d) using the `with` statement

Correct answer is: c) exit()
Explanation: The `exit()` method is not used to close a file in Python. It is a built-in method used to exit the Python interpreter. The correct method to close a file is by calling the `close()` method or using the `with` statement.

9). Which method is used to read a file line by line and process each line individually in Python?

a) read()
b) readlines()
c) readline()
d) iterating over the file object

Correct answer is: d) iterating over the file object
Explanation: You can read a file line by line and process each line individually in Python by iterating over the file object. When you iterate over a file object, each iteration returns a line from the file.

10). Which method is used to read a specific number of characters from a file in Python?

a) read()
b) readlines()
c) readline()
d) read(size)

Correct answer is: a) read()
Explanation: The `read()` method is used to read a specific number of characters from a file in Python. If no size is specified, it reads the entire content of the file.

11). Which method is used to write multiple lines of data to a file in Python?

a) writeline()
b) writelines()
c) write()
d) writelines()

Correct answer is: d) writelines()
Explanation: The `writelines()` method is used to write multiple lines of data to a file in Python. It takes a list of strings as an argument and writes each string as a separate line in the file.

12). Which method is used to write binary data to a file in Python?

a) write()
b) writebytes()
c) writebin()
d) writebinary()

Correct answer is: b) writebytes()
Explanation: The `writebytes()` method is used to write binary data to a file in Python. It takes a bytes-like object as an argument and writes the binary data to the file.

13). How can you read a file in chunks in Python?

a) read(size)
b) readlines()
c) readline()
d) using a loop and read(size) method

Correct answer is: d) using a loop and read(size) method
Explanation: You can read a file in chunks in Python by using a loop and the `read(size)` method. In each iteration, you can read a specified number of bytes from the file.

14). Which method is used to move a file from one location to another in Python?

a) move()
b) rename()
c) copyfile()
d) os.move()

Correct answer is: a) move()
Explanation: The `move()` method from the `shutil` module is used to move a file from one location to another in Python. It takes the source file path and the destination file path as arguments and moves the file to the specified destination.

15). What is the mode used to open a file for both reading and writing?

a) r
b) w
c) a
d) r+

Correct answer is: d
Explanation: The mode r+ is used to open a file for both reading and writing. It will allow you to read and write to the file.

16). What is the difference between the modes r and r+?

a) The mode r can only read the contents of the file, while the mode r+ can read and write to the file.
b) The mode r will only read the contents of the file if it already exists, while the mode r+ will create a new file if it does not exist.
c) The mode r will not allow you to change the contents of the file, while the mode r+ will allow you to change the contents of the file.
d) Both modes are the same.

Correct answer is: a
Explanation: The mode r can only read the contents of the file, while the mode r+ can read and write to the file.

17). What is the difference between the modes w and w+?

a) The mode w will overwrite the contents of the file if it already exists, while the mode w+ will create a new file if it does not exist.
b) The mode w will not allow you to change the contents of the file, while the mode w+ will allow you to change the contents of the file.
c) Both modes are the same.
d) None of the above.

Correct answer is: a
Explanation: The mode w will overwrite the contents of the file if it already exists, while the mode w+ will create a new file if it does not exist.

18). What is the difference between the modes a and a+?

a) The mode a will append the contents of the file to the end of the file, while the mode a+ will allow you to read and append to the file.
b) The mode a will not allow you to change the contents of the file, while the mode a+ will allow you to change the contents of the file.
c) Both modes are the same.
d) None of the above.

Correct answer is: a
Explanation: The mode a will append the contents of the file to the end of the file, while the mode a+ will allow you to read and append to the file.

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

				
					file = open("file1", "r")
print(file.read())
file.close()
				
			

a) It will print the content of the file named “file1” to the console.
b) It will raise a FileNotFoundError because the file named “file1” does not exist.
c) It will raise a PermissionError because the file “file1” is opened in read-only mode.
d) It will print an empty string to the console because the file named “file1” is empty.

Correct answer is: a) It will print the content of the file named “file1” to the console.
Explanation: The code opens a file named “file1” in read mode using the `open()` function. Then, the `read()` method is called on the file object to read the entire content of the file. Finally, the content is printed to the console using the `print()` function.

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

				
					file = open("file1", "w")
file.write("This line writes into file")
file.close()
				
			

a) The code will raise a `FileNotFoundError` because the file “file1” does not exist.
b) The code will create a new file named “file1” and write the text “This line writes into file” into it.
c) The code will open an existing file named “file1” and append the text “This line writes into file” to its contents.
d) The code will raise a `PermissionError` because the file “file1” is read-only.

Correct answer is: b) The code will create a new file named “file1” and write the text “This line writes into file” into it.
Explanation: The code opens a file named “file1” in write mode using the `”w”` parameter. If the file already exists, its contents will be truncated. Since the file does not exist initially, a new file named “file1” will be created. The code then writes the string “This line writes into file” to the file using the `write()` method. Finally, the file is closed.

Python File Handling MCQ : Set 1

Python File Handling MCQ

1). What is file handling in Python?

a) A mechanism to handle errors in file operations
b) A way to create new files in Python
c) A process of working with files, such as reading from or writing to them
d) A method to encrypt files in Python

Correct answer is: c) A process of working with files, such as reading from or writing to them
Explanation: File handling in Python refers to the process of performing various operations on files, including reading data from files or writing data to files.

2). Which function is used to open a file in Python?

a) read()
b) open()
c) write()
d) close()

Correct answer is: b) open()
Explanation: The `open()` function in Python is used to open a file. It takes the filename as an argument and returns a file object that can be used to perform file operations.

3). How can you read the contents of a file in Python?

a) read(file)
b) open(file, ‘r’)
c) write(file)
d) close(file)

Correct answer is: b) open(file, ‘r’)
Explanation: To read the contents of a file in Python, you need to use the `open()` function with the file name as the first argument and `’r’` as the second argument. This opens file in the read mode.

4). Which of the following modes is used to open a file for the writing in Python?

a) ‘r’
b) ‘w’
c) ‘a’
d) ‘x’

Correct answer is: b) ‘w’
Explanation: The mode `’w’` in Python is used to open a file for the writing. If file already exists, it will be truncated. If file does not exists, a new file will be created.

5). By which method can you write data to a file in Python?

a) open(file, ‘w’)
b) write(file)
c) read(file)
d) close(file)

Correct answer is: a) open(file, ‘w’)
Explanation: To write data to a file in Python, you need to open the file in write mode using the `open()` function with the file name as the first argument and `’w’` as the second argument. This opens the file for writing.

6). What is the purpose of the `close()` function in file handling?

a) To delete a file
b) To rename a file
c) To close the file after performing file operations
d) To check if a file exists

Correct answer is: c) To close the file after performing file operations
Explanation: The `close()` function is used to close the file after performing file operations. It releases the resources associated with the file and ensures that any changes made to the file are saved.

7). Which of the following methods is used to read a single line from a file in Python?

a) read()
b) readlines()
c) readline()
d) readall()

Correct answer is: c) readline()
Explanation: The `readline()` method is used to read a single line from a file in Python. It reads characters from the current position in the file until it encounters a newline character.

8). What does the `with` statement do in file handling?

a) Opens a file for reading
b) Closes a file after performing file operations
c) Deletes a file from the system
d) Renames a file

Correct answer is: b) Closes a file after performing file operations
Explanation: The `with` statement is used in file handling to ensure that the file is properly closed after performing file operations. It automatically closes the file.

9). Which of the following modes is used to open a file for both reading and writing in Python?

a) ‘r’
b) ‘w’
c) ‘a’
d) ‘r+’

Correct answer is: d) ‘r+’
Explanation: The mode `’r+’` is used to open a file for both reading and writing in Python. It allows you to read from and write to the file at any position.

10). Which method is used to write data to a file in Python?

a) read()
b) write()
c) append()
d) open()

Correct answer is: b) write()
Explanation: The `write()` method is used to write data to a file in Python. It takes a string as an argument and writes it in the file.

11). Which mode is used to open a file for appending data in Python?

a) ‘a’
b) ‘w’
c) ‘r’
d) ‘x’

Correct answer is: a) ‘a’
Explanation: The mode `’a’` in Python is used to open a file for appending data. If file does not exist, it will be created. If file exists, data will be appended to the end of the file.

12). How can you read the contents of a file as a list of lines in Python?

a) read()
b) readlines()
c) readline()
d) openlines()

Correct answer is: b) readlines()
Explanation: The `readlines()` method is used to read the contents of a file as a list of lines in Python. Each line is stored as an element in the list.

13). Which method is used to move the file pointer to a specific position in a file?

a) seek()
b) move()
c) position()
d) setpos()

Correct answer is: a) seek()
Explanation: The `seek()` method is used to move the file pointer to a specific position in a file. It takes two arguments: the offset (number of bytes to move) and the optional `from_` argument, which specifies the reference position.

14). What is the purpose of the `tell()` method in file handling?

a) To check if a file exists
b) To rename a file
c) To return the current position of the file pointer
d) To check the size of a file

Correct answer is: c) To return the current position of the file pointer
Explanation: The `tell()` method is used to return the current position of the file pointer in a file. It returns an integer representing the offset in bytes from the beginning of the file.

15). Which method is used to check if the end of a file has been reached?

a) seek()
b) endoffile()
c) eof()
d) atend()

Correct answer is: c) eof()
Explanation: There is no built-in method to directly check if the end of a file has been reached. However, the `eof()` function is commonly used in file handling to determine if the end of the file has been reached based on the return value of other file reading methods.

16). How can you delete a file using Python?

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

Correct answer is: b) remove(file)
Explanation: The `remove()` function from the `os` module is used to delete a file in Python. It takes the filename as an argument and deletes the file from the file system.

17). Which method is used to check if a file is closed in Python?

a) is_closed()
b) isclosed()
c) closed()
d) close()

Correct answer is: b) isclosed()
Explanation: The `isclosed()` method is used to check if a file is closed in Python. It returns `True` if the file is closed and `False` otherwise.

18). What is the purpose of the `flush()` method in file handling?

a) To close the file after performing file operations
b) To clear the contents of a file
c) To ensure that any pending writes are immediately written to the file
d) To check if a file exists

Correct answer is: c) To ensure that any pending writes are immediately written to the file
Explanation: The `flush()` method is used to ensure that any pending writes are immediately written to the file. It is useful in situations where you want to make sure that all data is written to the file before proceeding.

19). Which of the following is NOT a valid file mode in Python?

a) ‘x’
b) ‘t’
c) ‘b’
d) ‘a+’

Correct answer is: b) ‘t’
Explanation: The mode `’t’` is not a valid file mode in Python. The available modes are `’r’` (read), `’w’` (write), `’a’` (append), and their combinations with `’+’` (read and write).

20). What happens if you try to open a non-existing file in read mode in Python?

a) A new file with the same name is created
b) An error is raised
c) The program waits until the file is created
d) The program continues without any issues

Correct answer is: b) An error is raised
Explanation: If you try to open a non-existing file in read mode using the `open()` function, Python will raise a `FileNotFoundError` indicating that the file does not exist.

Python Function MCQ : Set 4

Python Function MCQ

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

def square(d):
    a = {}
    for key,value in d.items():
        a[key] = value**2
    return a
square({‘a’:4,’b’:3,’c’:12,’d’:6})

a) {‘a’: 16, ‘b’: 9, ‘c’: 144, ‘d’: 36}
b) {‘a’: 8, ‘b’: 6, ‘c’: 24, ‘d’: 12}
c) {‘a’: 2, ‘b’: 3, ‘c’: 4, ‘d’: 6}
d) {‘a’: 4, ‘b’: 3, ‘c’: 12, ‘d’: 6}

Correct answer is: a) {‘a’: 16, ‘b’: 9, ‘c’: 144, ‘d’: 36}
Explanation: The code defines a function `square` that takes a dictionary `d` as an argument. Inside the function, it initializes an empty dictionary `a`. Then, it iterates over the key-value pairs of the input dictionary using the `items()` method. For each key-value pair, it calculates the square of the value and assigns it as a value in the new dictionary `a`, with the same key as the original dictionary.

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

def prime(lower, upper):
    print(“Prime numbers between”, lower, “and”, upper, “are:”)

    for num in range(lower, upper + 1):
        count = 0
        for i in range(1, num + 1):
            if num % i == 0:
                count += 1
        if count == 2:
            print(i, end=” “)

prime(1, 100)

a) Prime numbers between 1 and 100 are: 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
b) Prime numbers between 1 and 100 are: 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50
c) Prime numbers between 1 and 100 are: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
d) Prime numbers between 1 and 100 are: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26

Correct answer is: a) Prime numbers between 1 and 100 are: 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
Explanation: The function `prime()` takes two parameters, `lower` and `upper`, which represent the range of numbers to check for prime numbers. The function then iterates over each number in the range using a for loop, starting from `lower` and ending at `upper + 1`. Inside the loop, a variable `count` is initialized to 0. Another for loop iterates from 1 to the current number (`num`). Within this inner loop, the program checks if the current number (`num`) is divisible evenly by the current value of `i`. If it is, the `count` is incremented by 1. After the inner loop finishes, the program checks if the `count` is equal to 2. If it is, it means the number is only divisible by 1 and itself, indicating it is a prime number. In this code snippet, the function `prime(1, 100)` is called, which finds and prints all the prime numbers between 1 and 100.

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

def odd(lower, upper):
    print(“Odd numbers between”, lower, “and”, upper, “are:”)

    for num in range(lower, upper + 1):
        if num % 2 != 0:
            print(num, end=” “)

odd(1, 50)

a) Odd numbers between 1 and 50 are: 1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49
b) Odd numbers between 1 and 50 are: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
c) Odd numbers between 1 and 50 are: 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50
d) Odd numbers between 1 and 50 are: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50

Correct answer is: a) Odd numbers between 1 and 50 are: 1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49
Explanation: The function `odd` takes in two parameters, `lower` and `upper`, and prints the odd numbers between `lower` and `upper`. In this case, the function is called with `lower` equal to 1 and `upper` equal to 50. The for loop iterates over the range from 1 to 51 (upper + 1). For each number in the range, if the number is not divisible by 2 (i.e., it is an odd number), it is printed with a space at the end. Therefore, the output will be “Odd numbers between 1 and 50 are: 1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49”.

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

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

add(5, 15)

a) 5
b) 15
c) 20
d) None

Correct answer is: c) 20
Explanation: The function `add()` takes two parameters, `a` and `b`, and adds them together. In this case, `a` is 5 and `b` is 15. The function returns the sum of `a` and `b`, which is 20. When the `add(5, 15)` function call is executed, it returns the value 20.

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

def fruit(fname, fprice, quantity):
    print(“Fruit name: “, fname)
    print(“Fruit price: “, price)
    print(“Fruit quantity in kg: “, quantity)
    print(“Bill: “, fprice * quantity)

fruit(“Apple”, 100, 2)

a) Fruit name: Apple, Fruit price: 100, Fruit quantity in kg: 2, Bill: 200
b) Fruit name: Apple, Fruit price: 100, Fruit quantity in kg: 2, Bill: 100
c) Fruit name: Apple, Fruit price: 200, Fruit quantity in kg: 2, Bill: 400
d) Fruit name: Apple, Fruit price: 200, Fruit quantity in kg: 4, Bill: 800

Correct answer is: a) Fruit name: Apple, Fruit price: 100, Fruit quantity in kg: 2, Bill: 200
Explanation: The function `fruit` takes three parameters: `fname` (fruit name), `fprice` (fruit price), and `quantity` (fruit quantity in kg). It then prints the values of these parameters along with the calculated bill, which is the product of `fprice` and `quantity`.

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

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

leap(2005)

a) The given year is leap year.
b) The given year is not leap year.
c) The code raises an error.
d) None of the above.

Correct answer is: b) The given year is not a leap year.
Explanation: In the code, the function `leap()` takes a year as input and checks if it is a leap year or not. The condition `(a % 100 != 0 or a % 400 == 0) and a % 4 == 0` is used to determine the leap year. For the given input of `2005`, the condition `(a % 100 != 0 or a % 400 == 0) and a % 4 == 0` evaluates to `(True or False) and False`, which simplifies to `True and False`. Since the logical AND operator requires both conditions to be True for the entire expression to be True, the code execution enters the `else` block and prints “The given year is not a leap year.”

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

def reverse():
    num = n = 123
    rev = 0
    while n > 0:
        r = n % 10
        rev = (rev * 10) + r
        n = n // 10
    print(“Reverse number: “, rev)

reverse()

a) Reverse number: 123
b) Reverse number: 321
c) Reverse number: 312
d) Reverse number: 132

Correct answer is: b) Reverse number: 321
Explanation: The code defines a function `reverse()` that calculates the reverse of a given number. In this case, the initial value of `num` and `n` is 123. Inside the `while` loop, the remainder of `n` divided by 10 (`r`) is calculated. It is then added to the `rev` variable after multiplying it by 10 (shifting the existing digits to the left) to make space for the new digit. The updated `rev` becomes the new reversed number. The variable `n` is then divided by 10 to remove the rightmost digit. This process continues until `n` becomes 0, at which point the loop terminates. Finally, the reversed number is printed using the `print()` function, resulting in “Reverse number: 321” as the output.

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

def library(bname, came):
    print(“Book name: “, bname)
    print(“Borrowed by:”, cname)

library(“Harry Potter”, “Yash”)

a) Book name: Harry Potter
b) Harry Potter Yash
c) Book name: Harry potter Borrowed by: Yash
d) Book name: Harry Potter Borrowed by: Yash

Correct answer is: d) Book name: Harry Potter Borrowed by: Yash
Explanation: The function `library` takes two parameters `bname` and `cname`. When the function is called with the arguments “Harry Potter” and “Yash”, it prints “Book name: Harry Potter” and “Borrowed by: Yash” using the `print` function. Therefore, the output will be “Book name: Harry Potter Borrowed by: Yash”.

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

def binary(n1, n2):
    result = bin(int(n1, 2) + int(n2, 2))
    print(f”Addition of binary numbers {n1}, {n2}: “, result[2:]) binary(‘100010’, ‘101001’)

a) 1001011
b) 1000111
c) 10101011
d) 111011

Correct answer is: a) 1001011
Explanation: The given code defines a function binary(n1, n2) that takes two binary numbers represented as strings n1 and n2. It then performs binary addition on these two numbers.

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

def search():
    str1 = “python programming”
    str2 = “python”
    count = 0
    for word in str1.split(” “):
        if word == str2:
            count += 1
    if count > 0:
        print(f”{str2} is in {str1}”)
    else:
        print(f”{str2} is not in {str1}”)

search()

a) python is in python programming
b) python programming is in python
c) python is not in python programming
d) python programming is not in python

Correct answer is: a) python is in python programming
Explanation: The code defines a function named `search()`. Inside the function, the variable `str1` is assigned the value “python programming” and `str2` is assigned the value “python”. The variable `count` is initialized to 0. The code then splits `str1` into a list of words using the space character as the separator. It iterates over each word in the list and checks if it is equal to `str2`. If a match is found, `count` is incremented by 1. After the loop, the code checks if `count` is greater than 0. If it is, it means that `str2` was found in `str1`, and it prints “{str2} is in {str1}”. Otherwise, it prints “{str2} is not in {str1}”.

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

def length():
    str1 = “sqatools in best for learning python”
    l = str1.split(” “)
    print(f”Length of the last word {l[-1]} in the string: “, len(l[-1]))

length()

a) Length of the last word “python” in the string: 6
b) Length of the last word “sqatools” in the string: 8
c) Length of the last word “learning” in the string: 8
d) Length of the last word “in” in the string: 2

Correct answer is: a) Length of the last word “python” in the string: 6
Explanation: The code defines a function `length()` that splits the string `str1` into a list of words using the space as the delimiter. The last word of the string, accessed using `l[-1]`, is “python”. The `len()` function is then used to calculate the length of this last word, which is 6 characters. Finally, the function prints the message “Length of the last word python in the string: ” followed by the length of the word. Thus, the output of the code is “Length of the last word python in the string: 6”.

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

def mobile_number():
    num = 24568526
    if len(str(num)) == 10:
        print(“It is a valid phone number”)
    else:
        print(“It is not a valid phone number”)

mobile_number()

a) It is a valid phone number
b) It is not a valid phone number
c) Error: Invalid input format
d) None of the above

Correct answer is: b) It is not a valid phone number
Explanation: The code defines a function `mobile_number()` that assigns the value `24568526` to the variable `num`. The code then checks if the length of the string representation of `num` is equal to 10. In this case, the length of the string `”24568526″` is 8, which is not equal to 10. Therefore, the code prints “It is not a valid phone number”.

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

def to_number():
    num = 2563
    str1 = “”

    for i in str(num):
        if i == “1”:
            str1 += “One”
        elif i == “2”:
            str1 += “Two”
        elif i == “3”:
            str1 += “Three”
        elif i == “4”:
            str1 += “Four”
        elif i == “5”:
            str1 += “Five”
        elif i == “6”:
            str1 += “Six”
        elif i == “7”:
            str1 += “Seven”
        elif i == “8”:
            str1 += “Eight”
        elif i == “9”:
            str1 += “Nine”

    print(str1)

to_number()

a) “TwoFiveSixThree”
b) “TwoFiveSixThree”
c) “Two Five Six Three”
d) “2563”

Correct answer is: c) “Two Five Six Three”
Explanation: The function `to_number` converts the number 2563 into its string representation with words. It iterates over each digit in the string representation of the number using a for loop. Inside the loop, it checks each digit and appends the corresponding word to the variable `str1`.

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

import itertools
def permutations():
    string = “ABC”
    list1 = list(string)
    permutations = list(itertools.permutations(list1))
    return permutations

permutations()

a) [(‘A’, ‘B’, ‘C’), (‘A’, ‘C’, ‘B’), (‘B’, ‘A’, ‘C’), (‘B’, ‘C’, ‘A’), (‘C’, ‘A’, ‘B’), (‘C’, ‘B’, ‘A’)]
b) [‘ABC’, ‘ACB’, ‘BAC’, ‘BCA’, ‘CAB’, ‘CBA’]
c) [(‘A’, ‘A’, ‘A’), (‘B’, ‘B’, ‘B’), (‘C’, ‘C’, ‘C’)]
d) [‘A’, ‘B’, ‘C’]

Correct answer is: a) [(‘A’, ‘B’, ‘C’), (‘A’, ‘C’, ‘B’), (‘B’, ‘A’, ‘C’), (‘B’, ‘C’, ‘A’), (‘C’, ‘A’, ‘B’), (‘C’, ‘B’, ‘A’)]
Explanation: The code uses the `itertools.permutations()` function to generate all possible permutations of the characters in the string “ABC”. The function returns a list of tuples, where each tuple represents a different permutation. In this case, the output will be `[(‘A’, ‘B’, ‘C’), (‘A’, ‘C’, ‘B’), (‘B’, ‘A’, ‘C’), (‘B’, ‘C’, ‘A’), (‘C’, ‘A’, ‘B’), (‘C’, ‘B’, ‘A’)]`, representing all the possible permutations of the characters ‘A’, ‘B’, and ‘C’.

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

def login():
    name = “Ketan”
    password = “password1234”
    print(“Credential accepted”)

login()

a) Credential accepted
b) Ketan
c) password1234
d) None

Correct answer is: a) Credential accepted
Explanation: When the function `login()` is called, it assigns the string “Ketan” to the variable `name` and the string “password1234” to the variable `password`. The `print()` function is then used to output the message “Credential accepted” to the console. Therefore, the output of the code snippet will be “Credential accepted”.

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

def fun(string):
    a = {}
    l = string.split(” “)
    for word in l:
        a[word[0] + word[-1]] = word
    return a

result = fun(“Python is easy li Learn”)
print(result)

a) {‘Pi’: ‘Python’, ‘is’: ‘is’, ‘ey’: ‘easy’, ‘Li’: ‘Learn’}
b) {‘Pn’: ‘Python’, ‘is’: ‘is’, ‘ey’: ‘easy’, ‘li’: ‘li’, ‘Ln’: ‘Learn’}
c) {‘Ph’: ‘Python’, ‘is’: ‘is’, ‘ey’: ‘easy’, ‘Le’: ‘Learn’}
d) {‘Py’: ‘Python’, ‘is’: ‘is’, ‘ea’: ‘easy’, ‘Le’: ‘Learn’}

Correct answer is: b) {‘Pn’: ‘Python’, ‘is’: ‘is’, ‘ey’: ‘easy’, ‘li’: ‘li’, ‘Ln’: ‘Learn’}
Explanation: The function fun takes a string as input and splits it into a list of words using the space as a delimiter. It then iterates over each word in the list. For each word, it creates a dictionary entry where the key is the concatenation of the first character and the last character of the word, and the value is the word itself. Finally, it returns the resulting dictionary.

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

def hcf(num1,num2):
    if num1 > num2:
        smaller = num2
    else:
        smaller = num1

    for i in range(1, smaller+1):
        if((num1 % i == 0) and (num2 % i == 0)):
            hcf = i

    print(f”H.C.F of {num1} and {num2}: {hcf}”)

num1 = 24
num2 = 54
hcf(num1,num2)

a) H.C.F of 24 and 54: 6
b) H.C.F of 24 and 54: 12
c) H.C.F of 24 and 54: 24
d) H.C.F of 24 and 54: 54

Correct answer is: a) H.C.F of 24 and 54: 6
Explanation: The given code calculates the highest common factor (H.C.F) of `num1` and `num2` using the Euclidean algorithm. In this case, `num1` is 24 and `num2` is 54. The code starts by assigning the smaller value (`num1` or `num2`) to the variable `smaller`. Then, it iterates from 1 to `smaller` using a for loop. For each iteration, it checks if both `num1` and `num2` are divisible by the current number `i`. If they are, the current number `i` is assigned to the variable `hcf`. Finally, it prints the calculated H.C.F using the f-string format. In this scenario, the H.C.F of 24 and 54 is 6. Therefore, the output of the code will be “H.C.F of 24 and 54: 6”.

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

def average(numbers):
    total = sum(numbers)
    average = total / len(numbers)
    return average

scores = [90, 85, 92, 88, 95]
result = average(scores)
print(result)

a) 88
b) 90
c) 92
d) 95

Correct answer is: a) 88
Explanation: The code defines a function find_average that calculates the average of a list of numbers. It calculates the sum of the numbers using the sum() function and divides it by the length of the list. In this case, the average of the scores list [90, 85, 92, 88, 95] is 88. Therefore, the output will be 88.

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

def product(a, b=2):
    return a * b

result1 = product(5)
result2 = product(5, 3)
print(result1, result2)

a) 10 15
b) 5 15
c) 10 6
d) 5 6

Correct answer is: a) 10 15
Explanation: The function calculate_product takes two parameters, a and b, with a default value of 2 for b. If the b argument is not provided, it uses the default value. In this case, result1 is calculated as 5 * 2, which is 10, and result2 is calculated as 5 * 3, which is 15. Therefore, the output will be “10 15”.

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

def power(base, exponent):
    return base ** exponent

result = power(2, 3)
print(result)

a) 6
b) 8
c) 16
d) 23

Correct answer is: c) 16
Explanation: The function calculate_power calculates the result of raising the base to the exponent using the exponentiation operator **. In this case, 2 raised to the power of 3 is 8. Therefore, the output will be 8.

Python Function MCQ : Set 3

Python Function MCQ

1). What is the purpose of the given Python function?

def add(a,b):
    total = a+b
    print(“Total: “,total)

num1 = int(input(“Enter number 1: “))
num2 = int(input(“Enter number 2: “))

add(num1,num2)

a) It multiplies two numbers and prints the result.
b) It divides two numbers and prints the result.
c) It subtracts two numbers and prints the result.
d) It adds two numbers and prints the result.

Correct answer is: d) It adds two numbers and prints the result.
Explanation: The function add(a, b) takes two parameters a and b, adds them together, and stores the result in the variable total. Then it prints the result using the print statement. In the provided code, num1 is set to 10 and num2 is set to 20. When add(num1, num2) is called, it adds 10 and 20, resulting in a total of 30, which is printed as “Total: 30”.

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

def String(str1):
    print(str1*10)

string = “Python”
String(string)

a) PythonPythonPythonPythonPythonPythonPythonPythonPythonPython
b) 10Python
c) 10
d) Python10

Correct answer is: a) PythonPythonPythonPythonPythonPythonPythonPythonPythonPython
Explanation: The given code defines a function called `String(str1)` that takes a string as input and prints it ten times. It then creates a variable `string` with the value “Python” and calls the `String()` function, passing the `string` variable as an argument. When the function is called with `String(string)`, the function takes the input string “Python” and multiplies it by 10.

3). What is the purpose of the following code snippet?

def table(num):
    a = 0
    for i in range(1, 11):
        a = i * num
    print(i, “*”, num, “=”, a)

n = 5
table(n)

a) It calculates the factorial of a given number.
b) It generates a multiplication table for a given number.
c) It prints the squares of numbers from 1 to 10.
d) It calculates the sum of a given number and its multiples.

Correct answer is: b) It generates a multiplication table for a given number.
Explanation: The code defines a function named `table` that takes a parameter `num`. Within the function, a for loop iterates over the range from 1 to 11 (exclusive). In each iteration, the variable `a` is assigned the result of multiplying `i` by `num`. Then, it prints the equation `i * num = a`. The variable `n` is set to 5, and the `table` function is called with `n` as the argument, generating a multiplication table for 5.

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

def largest(a,b,c):
    if a>b:
        if a>c:
            print(f”{a} is the greatest number”)
    elif b>a:
        if b>c:
             print(f”{b} is the greatest number”)
    else:
        print(f”{c} is the greatest number”)

num1 = 50
num2 = 60
num3 = 44

largest(num1,num2,num3)

a) 50 is the greatest number
b) 60 is the greatest number
c) 44 is the greatest number
d) No output is printed

Correct answer is: b) 60 is the greatest number
Explanation: The function largest is called with three numbers: 50, 60, and 44. Among these numbers, 60 is the greatest. Therefore, the output of the function call is “60 is the greatest number”, which will be printed to the console.

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

def total(list1):
    t = 0
    for val in list1:
        t += val
    print(“Sum of given list: “, t)

l = [6, 9, 4, 5, 3]
total(l)

a) Sum of given list: 27
b) Sum of given list: 27 [6, 9, 4, 5, 3]
c) 27
d) None

Correct answer is: a) Sum of given list: 27
Explanation: The function `total` takes a list as input and iterates through each element, adding them to the variable `t`. In this case, the list `l` contains the elements [6, 9, 4, 5, 3], and their sum is 27. The function prints “Sum of given list: 27” as the output. The print statement is inside the function, and it displays the sum directly to the console.

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

def mul(list1):
    t = 1
    for val in list1:
        t *= val
    print(“Product of elements in the given list: “,t)

l = [-8, 6, 1, 9, 2]
mul(l)

a) 0
b) 1
c) 864
d) -864

Correct answer is: d) -864
Explanation: The function “mul(l)” is called with the list “[-8, 6, 1, 9, 2]”. The function calculates the product of all elements in the list: (-8) * 6 * 1 * 9 * 2 = -864. The product (-864) is then printed as the output.

7). What is the purpose of the following code snippet?

def rev(str1):
    a = str1[::-1]
    print(“Reverse of the given string: “, a)

string = “Python1234”
rev(string)

a) It reverses the order of characters in a given string.
b) It checks if the given string is a palindrome.
c) It prints the given string without any modifications.
d) It generates an error due to an undefined function.

Correct answer is: a) It reverses the order of characters in a given string.
Explanation: The function `rev` takes a string `str1` as input and assigns the reverse of the string to the variable `a` using slicing with a step of -1. The `[::-1]` notation is used to reverse the order of characters in the string. Finally, the function prints the reversed string as “Reverse of the given string: ” followed by the value of `a`. In the given code, the string “Python1234” is passed as an argument to the function `rev`, so the output will be “Reverse of the given string: 4321nohtyP”.

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

def check(num):
    if num in range(2, 20):
        print(“True”)
    else:
        print(“False”)
num1 = 15
check(num1)

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

Correct answer is: a) True
Explanation: The given code defines a function `check(num)` that takes a parameter `num`. Inside the function, it checks if the value of `num` is in the range from 2 (inclusive) to 20 (exclusive) using the `in` keyword with the `range()` function. If `num` is within this range, it prints “True”, otherwise, it prints “False”.

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

def unique(list1):
    print(list(set(list1)))

l = [2, 2, 3, 1, 4, 4, 4, 4, 4, 6]
unique(l)

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

Correct answer is: a) [2, 3, 1, 4, 6]
Explanation: The function `unique` takes a list as an argument and uses the `set()` function to remove duplicate elements from the list. The `set()` function creates an unordered collection of unique elements. When the `set()` is converted back to a list using the `list()` function, the order of elements may differ.

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

def prime(num):
    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”)

num1 = 7
prime(num1)

a) It is not a prime number
b) It is a prime number
c) Error
d) None

Correct answer is: b) It is a prime number
Explanation: The function `prime` takes an input number `num` and checks if it is a prime number. It iterates over the numbers from 2 to `num-1` (exclusive) and checks if `num` is divisible by any of these numbers. If it is divisible by any number, the count is incremented. If the count is greater than 0, it means the number has divisors other than 1 and itself, and thus, it is not a prime number. Otherwise, if the count remains 0, it means the number has no divisors other than 1 and itself, making it a prime number.

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

def even(list1):
    even_list = []
    for val in list1:
        if val % 2 == 0:
    even_list.append(val)
    print(even_list)

l = [1, 2, 3, 4, 5, 6, 7, 8, 9]
even(l)

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

Correct answer is: b) [2, 4, 6, 8]
Explanation: The function `even()` takes a list as input and creates an empty list called `even_list`. It then iterates through each value in the input list. If the value is divisible by 2 (i.e., it is even), it appends it to `even_list`. Finally, it prints `even_list`. In this case, the input list `l` contains numbers from 1 to 9. The even numbers in this list are 2, 4, 6, and 8. Therefore, the output is `[2, 4, 6, 8]`.

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

def square():
    for i in range(1, 11):
        print(i, “:”, i ** 2)

square()

a) 1 : 1, 2 : 4, 3 : 9, 4 : 16, 5 : 25, 6 : 36, 7 : 49, 8 : 64, 9 : 81, 10 : 100
b) 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
c) 1 : 1, 4 : 16, 9 : 81
d) None of the above

Correct answer is: a) 1 : 1, 2 : 4, 3 : 9, 4 : 16, 5 : 25, 6 : 36, 7 : 49, 8 : 64, 9 : 81, 10 : 100
Explanation: The function `square()` uses a for loop to iterate over the numbers from 1 to 10 (inclusive) using the `range(1, 11)` expression. Inside the loop, it prints the current number (`i`) followed by a colon (`:`) and the square of `i` (`i ** 2`).

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

mycode = ‘print(“Python”)’
code = “””
def multiply(x, y):
    return x * y

print(‘sqatools’)
“””
exec(mycode)
exec(code)

a) Python
b) sqatools
c) Python\nsqatools
d) sqatools\nPython

Correct answer is: c) Python\nsqatools
Explanation: The `exec()` function in Python is used to execute dynamically generated Python code. In this code, `mycode` variable contains the string `’print(“Python”)’`, which is executed using `exec(mycode)`. This will print the string “Python” to the console. The `code` variable contains a multi-line string that defines a function called `multiply(x, y)` and prints the string “sqatools” to the console. When `exec(code)` is executed, it will execute the code within the string.

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

def lcm(num1, num2):
    if num1 > num2:
        greater = num1
    else:
        greater = num2

    while True:
        if (greater % num1 == 0) and (greater % num2 == 0):
            lcm = greater
            break
        greater += 1

    print(f”L.C.M of {num1} and {num2}: {lcm}”)

num1 = 12
num2 = 20
lcm(num1, num2)

a) L.C.M of 12 and 20: 60
b) L.C.M of 12 and 20: 12
c) L.C.M of 12 and 20: 20
d) L.C.M of 12 and 20: 240

Correct answer is: a) L.C.M of 12 and 20: 60
Explanation: The function `lcm()` calculates the least common multiple (LCM) of two numbers, `num1` and `num2`. In this case, `num1` is 12 and `num2` is 20. The code first compares the values of `num1` and `num2` and assigns the larger value to the variable `greater`. Next, a `while` loop is initiated. It continues until the condition `True` is met. Within the loop, it checks if the `greater` number is divisible by both `num1` and `num2` using the modulo operator `%`. If it is, it means that `greater` is the LCM, and the value is stored in the variable `lcm`. The loop is then terminated using the `break` statement. Finally, the function prints the result using an f-string, displaying the LCM of `num1` and `num2`.

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

def total():
    t = 0
    for i in range(1, 11):
        t += i
    print(“Total: “, t)

total()

a) Total: 55
b) Total: 45
c) Total: 10
d) Total: 15

Correct answer is: a) Total: 55
Explanation: The code defines a function named `total()`. Inside the function, a variable `t` is initialized to 0. Then, a loop is executed using the `range()` function from 1 to 10 (excluding 11). In each iteration, the loop variable `i` is added to `t`. After the loop finishes, the total value of `t` is printed with the message “Total: “. The loop iterates over the numbers 1 to 10, and each number is added to the total `t`. Therefore, the final value of `t` is the sum of all numbers from 1 to 10, which is 55. Thus, the output of the code is “Total: 55”.

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

def func(*args):
    for num in args:
        print(num**3, end=” “)

func(5, 6, 8, 7)

a) 125 216 512 343
b) 5 6 8 7
c) 15 18 24 21
d) 125 216 512 343 5 6 8 7

Correct answer is: a) 125 216 512 343
Explanation: The function `func` accepts a variable number of arguments using the `*args` syntax, which allows it to receive multiple arguments as a tuple. Inside the function, a loop iterates over each element in `args` and prints the cube of each number.

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

def fact(n):
    fact = 1
    while n > 0:
        fact *= n
        n -= 1
    print(f”Factorial of {num}: {fact}”)

num = 5
fact(num)

a) Factorial of 5: 5
b) Factorial of 5: 120
c) Factorial of 5: 25
d) Factorial of 5: 1

Correct answer is: b) Factorial of 5: 120
Explanation: The code defines a function `fact(n)` to calculate the factorial of a given number. It initializes the variable `fact` to 1 and enters a while loop that iterates while `n` is greater than 0. In each iteration, it multiplies `fact` by `n` and decreases `n` by 1.

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

def fibo():
    num1 = 0
    num2 = 1
    count = 0

    while count < 10:
        print(num1, end=” “)
        n2 = num1 + num2
        num1 = num2
        num2 = n2
        count += 1

fibo()

a) 0 1 1 2 3 5 8 13 21 34
b) 1 1 2 3 5 8 13 21 34 55
c) 0 1 2 3 4 5 6 7 8 9
d) 0 1 1 3 5 8 13 21 34 55

Correct answer is: a) 0 1 1 2 3 5 8 13 21 34
Explanation: The code defines a function `fibo()` that prints the Fibonacci sequence up to the 10th term. The initial values `num1` and `num2` are set to 0 and 1, respectively. The `count` variable keeps track of the number of terms printed. Inside the while loop, `num1` is printed, and then `num1` is updated to the value of `num2`, and `num2` is updated to the sum of the previous `num1` and `num2`. This process continues until the count reaches 10.

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

def unique(l):
    distinct = set(l)
    print(list(distinct))

unique([4, 6, 1, 7, 6, 1, 5])

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

Correct answer is: b) [4, 6, 1, 7, 5]
Explanation: The function `unique` takes a list `l` as input. It creates a set `distinct` from the elements of the list, which removes duplicate values. Then, the set is converted back to a list using the `list()` function. The `print()` statement displays the resulting list.

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

def dupli(string):
    list1 = []
    for char in string:
        if string.count(char) > 1:
            list1.append(char)
    print(set(list1))

dupli(‘Programming’)

a) {‘r’, ‘g’}
b) {‘o’, ‘m’}
c) {‘r’, ‘m’, ‘g’}
d) {‘r’, ‘o’, ‘m’, ‘g’}

Correct answer is: c) {‘r’, ‘m’, ‘g’}
Explanation: The function `dupli` takes a string as input and checks each character in the string. If the count of the character in the string is greater than 1, it is considered a duplicate and added to the `list1` list. In this case, the string is ‘Programming’, and the characters ‘r’, ‘o’, and ‘g’ occur more than once. The `list1` list will contain these duplicate characters. Finally, the `set()` function is used to convert the `list1` list into a set, which removes duplicate elements. The set containing the duplicate characters is then printed, resulting in {‘r’, ‘m’, ‘g’}.

Python Function MCQ : Set 2

Python Function MCQ

1). What is the purpose of the “return” statement in Python?

a) It defines a loop.
b) It handles exceptions.
c) It terminates the execution of a loop.
d) It specifies the value to be returned by a function.

Correct answer is: d) It specifies the value to be returned by a function.
Explanation: The “return” statement is used to specify the value that a function should return when it is called.

2). Which of the following is a valid way to define a default argument in a function?

a) def my_func(x = 0):
b) def my_func(x, default=0):
c) def my_func(default=0, x):
d) def my_func(x = 0, default):

Correct answer is: a) def my_func(x = 0):
Explanation: Option a) is a valid way to define a default argument in a function. The default value is specified after the “=” sign.

3). What is the purpose of the “reduce()” function in Python?

a) It applies a function to every item in an iterable.
b) It removes duplicates from an iterable.
c) It filters out elements from an iterable based on a condition.
d) It performs a cumulative computation on an iterable.

Correct answer is: d) It performs a cumulative computation on an iterable.
Explanation: The “reduce()” function is used to perform a cumulative computation on an iterable by applying a specified function to the elements.

4). What is the function header?

a) The name of the function and the list of parameters that the function takes.
b) The list of parameters that the function takes.
c) The body of the function.
d) The return value of the function.

Correct answer is: a) The name of the function and the list of parameters that the function takes.

5). What is the body of a function?

a) The code that is executed when the function is called.
b) The list of parameters that the function takes.
c) The return value of the function.
d) The name of the function.

Correct answer is: a) The code that is executed when the function is called.

6). What is a parameter?

a) A variable that is defined inside a function.
b) A variable that is used to store the return value of a function.
c) A variable that is passed to a function.
d) A variable that is used to control the flow of execution of a function.

Correct answer is: c) A variable that is passed to a function.

7). What is the difference between a global variable and local variable?

a) A local variable is defined inside a function, while a global variable is defined outside of a function.
b) A local variable can only be accessed inside the function that defines it, while a global variable can be accessed anywhere in the program.
c) A local variable is created when the function is called, and it is destroyed when the function returns. A global variable is created when the program starts, and it exists until the program ends.
d) All of the above.

Correct answer is: d) All of the above.

8). What is the difference between a built-in function and a user-defined function?

a) A built-in function is a function that is provided by the Python language, while a user-defined function is a function that is defined by the user.
b) A built-in function cannot be modified, while a user-defined function can be modified.
c) A built-in function can only be called from within a function, while a user-defined function can be called from anywhere in the program.
d) All of the above.

Correct answer is: d) All of the above.

9). What is the advantage of using functions?

a) Functions make code more readable and maintainable.
b) Functions can be reused in different parts of the program.
c) Functions can help to improve performance.
d) All of the above.

Correct answer is: d) All of the above.

10). What is the disadvantage of using functions?

a) Functions can make code more complex.
b) Functions can make code less efficient.
c) Functions can make code more difficult to debug.
d) None of the above.

Correct answer is: d) None of the above.

11). What is the purpose of the “zip()” function in Python?

a) It combines two or more iterables element-wise.
b) It compresses data into a ZIP file.
c) It returns the size of an iterable.
d) It reverses the order of elements in an iterable.

Correct answer is: a) It combines two or more iterables element-wise.
Explanation: The “zip()” function is used to combine two or more iterables element-wise, creating an iterator of tuples.

12). Which of the following is a valid way to access the documentation string of a function in Python?

a) help(my_function)
b) my_function.__doc__
c) my_function.document
d) All of the above

Correct answer is: d) All of the above
Explanation: All the given options are valid ways to access the documentation string (docstring) of a function in Python.

13). Which of the following is a valid way to define a recursive function in Python?

a) def my_func():
b) def my_func(x):
c) def my_func():
d) def my_func(x = 0):

Correct answer is: b) def my_func(x):
Explanation: Option b) is a valid way to define a recursive function in Python. The function should have at least one parameter to enable recursive calls with different arguments.

14). Which of the following is a valid way to define a lambda function in Python?

a) lambda x: x + 1
b) def lambda(x): return x + 1
c) def my_func(x): return x + 1
d) lambda: return x + 1

Correct answer is: a) lambda x: x + 1
Explanation: Option a) is a valid way to define a lambda function in Python. It takes a parameter `x` and returns `x + 1`.

15). What is the purpose of the “filter()” function in Python?

a) It applies a function to every item in an iterable.
b) It removes duplicates from an iterable.
c) It filters out elements from an iterable based on a condition.
d) It counts the number of occurrences of an element in an iterable.

Correct answer is: c) It filters out elements from an iterable based on a condition.
Explanation: The “filter()” function is used to filter out elements from an iterable based on a specified condition.

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

def func(x):
    return x * 3

result = func(“abc”)
print(result)

a) a
b) abc
c) abcabcabc
d) None

Correct answer is: c) abcabcabc
Explanation: The function func multiplies the input string x by 3. In this case, “abc” multiplied by 3 results in “abcabcabc”.

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

def func(x):
    return x * 2

value = 4
result = func(value)
print(result)

a) 3
b) 8
c) 9
d) None

Correct answer is: b) 8
Explanation: The variable value is passed to the function func, and the function returns the value of x multiplied by 2. In this case, value is 4, so the function returns 4 * 2 = 8.

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

def func(x):
    if x == “”:
        return “Empty”
    else:
        return “Not empty”

result = func(“”)
print(result)

a) Empty
b) Not empty
c) Error
d) None

Correct answer is: a) Empty
Explanation: The function func checks if the input string x is empty. In this case, since x is an empty string, it returns “Empty”.

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

def func(x):
    return len(x)

result = func([1, 2, 3, 4])
print(result)

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

Correct answer is: d) 4
Explanation: The function func returns the length of the input list x using the “len()” function. In this case, the list has 4 elements, so the output is 4.

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

def func(x):
    return x[::-1]

result = func(“Python”)
print(result)

a) nohtyP
b) P
c) Python
d) None

Correct answer is: a) nohtyP
Explanation: The function func returns the reverse of the input string x using slicing with a step of -1. In this case, “Python” reversed becomes “nohtyP”.

Python Function MCQ : Set 1

Python Function MCQ

1). Which keyword is used to define a function in Python?

a) def
b) func
c) define
d) function

Correct answer is: a) def
Explanation: The keyword “def” is used to define a function in Python.

2). In a function what is the purpose of a return statement?

a) It defines the function name.
b) It calls another function.
c) It specifies the input parameters.
d) It returns a value from the function.

Correct answer is: d) It returns a value from the function.
Explanation: The return statement is used to specify the value that should be returned from the function when it is called.

3). Which of the following is a valid way to call a function in Python?

a) function_name()
b) functionName()
c) FunctionName()
d) All of the above.

Correct answer is: d) All of the above.
Explanation: All of the given options are valid ways to call a function in Python.

4). What is the purpose of the “pass” statement in Python?

a) It is used to define an empty function.
b) It is used to skip the execution of a function.
c) It is used to indicate the end of a function.
d) It is used to define a placeholder in a function.

Correct answer is: d) It is used to define a placeholder in a function.
Explanation: The “pass” statement is used as a placeholder when you want to define a function without any implementation.

5). Which scope in Python can access variables defined inside a function?

a) Global scope
b) Local scope
c) Built-in scope
d) None of the above

Correct answer is: a) Global scope
Explanation: Variables defined inside a function have local scope and can only be accessed within that function, unless they are explicitly marked as global.

6). What happens if a function is called with fewer arguments than specified in the function definition?

a) An error is raised.
b) The function will run without any issues.
c) The missing arguments will be assigned default values.
d) The function will return None.

Correct answer is: a) An error is raised.
Explanation: If a function is called with fewer arguments than specified in the function definition, a TypeError will be raised.

7). What is the purpose of the “lambda” keyword in Python?

a) It defines a lambda expression.
b) It is used to create a new function.
c) It is used to define the main function.
d) It is used to import external modules.

Correct answer is: a) It defines a lambda expression.
Explanation: The “lambda” keyword is used to define anonymous functions, also known as lambda expressions.

8). Which of the following is a valid way to pass arguments to a function?

a) Positional arguments
b) Keyword arguments
c) Default arguments
d) All of the above

Correct answer is: d) All of the above
Explanation: All the options (positional, keyword, and default arguments) are valid ways to pass arguments to a function.

9). What is the maximum number of return statements allowed in a function?

a) 1
b) 2
c) 3
d) There is no limit.

Correct answer is: d) There is no limit.
Explanation: There is no limit to the number of return statements in a function. However, only one return statement is executed during the function call.

10). What is the purpose of the “map” function in Python?

a) It applies a function to every item in an iterable.
b) It returns the maximum value from an iterable.
c) It converts an iterable to a list.
d) It sorts the items in an iterable.

Correct answer is: a) It applies a function to every item in an iterable.
Explanation: The “map” function is used to apply a given function to each item of an iterable and returns an iterator with the results.

11). Which of the following is a recursive function?

a) A function that calls itself.
b) A function that uses a loop.
c) A function that imports another module.
d) A function that returns multiple values.

Correct answer is: a) A function that calls itself.
Explanation: It is a function that calls itself either directly or indirectly.

12). Which built-in function is used to find the length of an object?

a) count()
b) length()
c) size()
d) len()

Correct answer is: d) len()
Explanation: The `len()` function is used to find the length of an object, such as a string, list, or tuple.

13). What is the purpose of the “global” keyword in Python?

a) It defines a global variable.
b) It imports a module.
c) It creates a new function.
d) It raises an error.

Correct answer is: a) It defines a global variable.
Explanation: The “global” keyword is used to indicate that a variable is defined in the global scope, allowing it to be accessed from any part of the program.

14). Which of the following is NOT a valid way to define a function in Python?

a) def my_function():
b) define my_function():
c) my_function = def():
d) lambda x: x + 1

Correct answer is: c) my_function = def():
Explanation: The option c) is not a valid way to define a function in Python. The correct syntax is `def function_name():`.

15). Which of the following is NOT a valid function call in Python?

a) my_function(1, 2)
b) my_function(x=1, y=2)
c) my_function(1, y=2)
d) my_function(x=1, 2)

Correct answer is: d) my_function(x=1, 2)
Explanation: In a function call, keyword arguments must follow positional arguments. In option d), a positional argument is followed by a keyword argument, which is not valid.

16). What is the purpose of the “__init__” method in a Python class?

a) It defines the class name.
b) It initializes the object’s state.
c) It imports external modules.
d) It defines class methods.

Correct answer is: b) It initializes the object’s state.
Explanation: The method “__init__” is a method in Python classes that is called when an object is created. It initializes the object’s state.

17). Which of the following is a built-in function in Python for sorting?

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

Correct answer is: b) sorted()
Explanation: The `sorted()` function is a built-in function in Python that is used to sort iterables, such as lists or tuples.

18). What is the purpose of the “isinstance()” function in Python?

a) It checks if two objects are equal.
b) It checks if an object is an instance of a class.
c) It converts an object to a different type.
d) It finds the index of an element in a list.

Correct answer is: b) It checks if an object is an instance of a class.
Explanation: The function `isinstance()` is used to check if an object is an instance of a specified class or its subclasses.

19). Which of the following is a valid way to define a default argument in a function?

a) def my_func(x = 0):
b) def my_func(x, default=0):
c) def my_func(default=0, x):
d) def my_func(x = 0, default):

Correct answer is: a) def my_func(x = 0):
Explanation: Option a) is a valid way to define a default argument in a function. The default value is specified after the “=” sign.

20). What is the purpose of the “enumerate()” function in Python?

a) It counts the number of occurrences of an element in an iterable.
b) It returns a reversed version of an iterable.
c) It assigns indices to items in an iterable.
d) It removes duplicates from an iterable.

Correct answer is: c) It assigns indices to items in an iterable.
Explanation: The “enumerate()” function is used to assign indices to items in an iterable, creating tuples of the form (index, item).

Python Set MCQ : Set 4

Python Set MCQ

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

a = {1, 2, 4, 5, 7, 8, 9}
print(“Original set1: “, a)
print(type(a))

a) Original set1: {1, 2, 4, 5, 7, 8, 9}
\<class ‘set’>
b) Original set1: {1, 2, 4, 5, 7, 8, 9}
\<class ‘list’>
c) Original set1: {1, 2, 4, 5, 7, 8, 9}
\<class ‘tuple’>
d) Original set1: {1, 2, 4, 5, 7, 8, 9}
\<class ‘dict’>

Correct answer is: a) Original set1: {1, 2, 4, 5, 7, 8, 9} \<class ‘set’>
Explanation: The code initializes a set named ‘a’ with the elements 1, 2, 4, 5, 7, 8, and 9. The print() function is then used to display the original set, which outputs {1, 2, 4, 5, 7, 8, 9}. The type() function is used to determine the data type of the set ‘a’, which is a set (class ‘set’).

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

a = {1, 2, 4, 5, 7, 8, 9}
print(“Original set1: “, a)
b = frozenset(a)
print(b)

a) Original set1: {1, 2, 4, 5, 7, 8, 9}
frozenset({1, 2, 4, 5, 7, 8, 9})
b) Original set1: {1, 2, 4, 5, 7, 8, 9}
frozenset([1, 2, 4, 5, 7, 8, 9])
c) Original set1: {1, 2, 4, 5, 7, 8, 9}
frozenset((1, 2, 4, 5, 7, 8, 9))
d) Original set1: {1, 2, 4, 5, 7, 8, 9}
frozenset({1: None, 2: None, 4: None, 5: None, 7: None, 8: None, 9: None})

Correct answer is: c) Original set1: {1, 2, 4, 5, 7, 8, 9}
frozenset({1, 2, 4, 5, 7, 8, 9})
Explanation: The code initializes a set `a` with elements 1, 2, 4, 5, 7, 8, and 9. The line `b = frozenset(a)` creates a frozen set `b` from `a`. The `frozenset()` function returns an immutable frozenset object. The output will be “Original set1: {1, 2, 4, 5, 7, 8, 9}” followed by “frozenset({1, 2, 4, 5, 7, 8, 9})”.

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

a = {1,2,4,6}
b = {7,8,9,6}
c = {5,8,9}
print(“Original set1: “,a)
print(“Original set2: “,b)
print(“Original set3: “,c)
print(“Difference between above sets: “)
print(a.difference(b.difference(c)))

a) Original set1: {1, 2, 4, 6}
Original set2: {7, 8, 9, 6}
Original set3: {5, 8, 9}
Difference between above sets: {1, 2, 4}
b) Original set1: {1, 2, 4, 6}
Original set2: {7, 8, 9, 6}
Original set3: {5, 8, 9}
Difference between above sets: {1, 2, 4, 6, 7, 8, 9}
c) Original set1: {1, 2, 4, 6}
Original set2: {7, 8, 9, 6}
Original set3: {5, 8, 9}
Difference between above sets: {1, 2, 4, 5, 6, 7, 8, 9}
d) Original set1: {1, 2, 4, 6}
Original set2: {7, 8, 9, 6}
Original set3: {5, 8, 9}
Difference between above sets: {5, 7}

Correct answer is: a) Original set1: {1, 2, 4, 6}
Original set2: {7, 8, 9, 6}
Original set3: {5, 8, 9}
Difference between above sets: {1, 2, 4}
Explanation: The code demonstrates the difference between sets using the difference() method. The difference() method is applied to the set ‘a’ with the argument ‘b.difference(c)’, which computes the difference between set ‘b’ and set ‘c’. Then, this difference is subtracted from set ‘a’ using the difference() method. The resulting set contains the elements that are present in ‘a’ but not in ‘b’ or ‘c’, which in this case is {1, 2, 4}.

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

a = {1,2,4,6}
b = {7,8,9,6}
c = {5,8,9,6}
print(“Original set1: “,a)
print(“Original set2: “,b)
print(“Original set3: “,c)
print(“Intersection between above sets: “)
print(a.intersection(b.intersection(c)))

a) {6}
b) {1, 2, 4, 6}
c) {6, 8, 9}
d) {6, 8, 9, 5}

Correct answer is: a) {6}
Explanation: The code calculates the intersection between sets a, b, and c using the intersection() method. First, b.intersection(c) finds the common elements between sets b and c, which results in {6, 8, 9}. Then, a.intersection(b.intersection(c)) finds the common elements between set a and the result of the previous intersection, which is {6}.

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

a = {1,2,4,6}
b = {7,8,9,6}
c = {5,8,9,6}
print(“Original set1: “,a)
print(“Original set2: “,b)
print(“Original set3: “,c)
print(“Difference between above sets: “)
print(a.union(b.union(c)))

a) {1, 2, 4, 5, 6, 7, 8, 9}
b) {1, 2, 4, 6, 7, 8, 9}
c) {1, 2, 4, 5, 6, 7}
d) {1, 2, 4, 6}

Correct answer is: a) {1, 2, 4, 5, 6, 7, 8, 9}
Explanation: The union() method is used to find the union of multiple sets. In this case, we are finding the union of set a, set b, and set c. The resulting set contains all the unique elements from all the sets involved. Therefore, the output will be {1, 2, 4, 5, 6, 7, 8, 9}.

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

String = “Learning python is fun”
Set = {“fun”,”python”}
count = 0
for word in Set:
    if word in String:
        count += 1
if count > 0:
print(“An element in a set is a substring of a given string”)
else:
print(“An element in a set is not a substring of a given string”)

a) An element in a set is a substring of a given string
b) An element in a set is not a substring of a given string
c) String: Learning python is fun
Set: {‘fun’, ‘python’}
d) String: “Learning python is fun”
Set: {“fun”,”python”}

Correct answer is: a) An element in a set is a substring of a given string
Explanation: The code checks if any element in the set is a substring of the given string. In this case, both “fun” and “python” are substrings of the string “Learning python is fun”. Therefore, the count variable is incremented, and the condition count > 0 is satisfied. As a result, the output will be “An element in a set is a substring of a given string”.

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

Set = {1, 2, 4, 6}
print(“Set: “, Set)
List = list(Set)
print(“The index of 4: “, List.index(4))

a) Set: {1, 2, 4, 6} | The index of 4: 2
b) Set: {1, 2, 4, 6} | The index of 4: 3
c) Set: [1, 2, 4, 6] | The index of 4: 2
d) Set: [1, 2, 4, 6] | The index of 4: 3

Correct answer is: a) Set: {1, 2, 4, 6} | The index of 4: 2
Explanation: The code initializes a set named “Set” with the elements 1, 2, 4, and 6. The set is then converted to a list using the list() function and stored in the variable “List”. When using the index() method on the list “List” and passing the argument 4, it returns the index position of the element 4, which is 2.

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

a = {1, 2, 4, 6}
print(“Original set:”, a)
Dict = {}
for ele in a:
    Dict[ele] = {}
print(“Dictionary:”, Dict)

a) Original set: {1, 2, 4, 6} Dictionary: {1: {}, 2: {}, 4: {}, 6: {}}
b) Original set: {1, 2, 4, 6} Dictionary: {1: {}, 2: {}, 3: {}, 4: {}, 5: {}, 6: {}}
c) Original set: {1, 2, 4, 6} Dictionary: {1: {}, 2: {}, 4: {}, 6: {}, 8: {}}
d) Original set: {1, 2, 4, 6} Dictionary: {1: {}, 2: {}, 4: {}, 6: {}, 1: {}}

Correct answer is: a) Original set: {1, 2, 4, 6} Dictionary: {1: {}, 2: {}, 4: {}, 6: {}}
Explanation: In the code, a set `a` is defined with elements [1, 2, 4, 6]. The set is then printed as “Original set: {1, 2, 4, 6}”. An empty dictionary `Dict` is created. The for loop iterates over each element in set `a` and assigns an empty dictionary as a value to each element in the `Dict` dictionary. Finally, the dictionary is printed as “Dictionary: {1: {}, 2: {}, 4: {}, 6: {}}”.

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

Set = set()
for num in range(1, 21):
    if num % 2 == 0:
        Set.add(num)
print(“Set of even numbers:”, Set)

a) Set of even numbers: {2, 4, 6, 8, 10, 12, 14, 16, 18, 20}
b) Set of even numbers: {1, 3, 5, 7, 9, 11, 13, 15, 17, 19}
c) Set of even numbers: {}
d) Set of even numbers: {2, 4, 6, 8, 10, 12, 14, 16, 18}

Correct answer is: a) Set of even numbers: {2, 4, 6, 8, 10, 12, 14, 16, 18, 20}
Explanation: The given code initializes an empty set, `Set`. It then iterates over the numbers from 1 to 20 using a `for` loop. For each number, if the number is divisible by 2 (i.e., an even number), it adds the number to the set using the `add()` method. Finally, it prints the set of even numbers, which includes all even numbers from 1 to 20. The correct answer is option a.

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

Set = set()
for num in range(1,21):
    if num%2 != 0:
        Set.add(num)
print(“Set of odd numbers: “, Set)

a) Set of odd numbers: {1, 3, 5, 7, 9, 11, 13, 15, 17, 19}
b) Set of odd numbers: {2, 4, 6, 8, 10, 12, 14, 16, 18, 20}
c) Set of odd numbers: {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20}
d) Set of odd numbers: {}

Correct answer is: a) Set of odd numbers: {1, 3, 5, 7, 9, 11, 13, 15, 17, 19}
Explanation: The code initializes an empty set and then iterates over numbers from 1 to 20. If a number is odd, it is added to the set using the add() method. Finally, the set is printed, showing the set of odd numbers from 1 to 20.

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

Set = {“Shan Rukh Khan”, “Akshay Kumar”, “Tom Hardy”, “Robert Pattinson”}
print(“Set of actors: “, Set)

a) Set of actors: {“Shan Rukh Khan”, “Akshay Kumar”, “Tom Hardy”, “Robert Pattinson”}
b) Set of actors: {“Shan Rukh Khan, Akshay Kumar, Tom Hardy, Robert Pattinson”}
c) Set of actors: {‘Shan Rukh Khan’, ‘Akshay Kumar’, ‘Tom Hardy’, ‘Robert Pattinson’}
d) Set of actors: [‘Shan Rukh Khan’, ‘Akshay Kumar’, ‘Tom Hardy’, ‘Robert Pattinson’]

Correct answer is: c) Set of actors: {‘Shan Rukh Khan’, ‘Akshay Kumar’, ‘Tom Hardy’, ‘Robert Pattinson’}
Explanation: The code defines a set named `Set` with four elements: “Shan Rukh Khan”, “Akshay Kumar”, “Tom Hardy”, and “Robert Pattinson”. When the `print()` function is called, it displays the set of actors enclosed in curly braces and single quotes.

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

Set1 = {“Lord of the Rings”, “Harry Potter and the Sorcerer’s Stone”, “The Magic Tree”, “Tower To The Stars”}
Set2 = {“Wizards of Ice”, “Call of the Forest”, “Lord of the Rings”}
print(“Original Set1: “, Set1)
print(“Original Set2: “, Set2)
print(“Common books: “)
for book_name in Set1:
    if book_name in Set2:
        print(book_name)

a) Original Set1: {“Lord of the Rings”, “Harry Potter and the Sorcerer’s Stone”, “The Magic Tree”, “Tower To The Stars”}
Original Set2: {“Wizards of Ice”, “Call of the Forest”, “Lord of the Rings”}
Common books: Lord of the Rings
b) Original Set1: {“Lord of the Rings”, “Harry Potter and the Sorcerer’s Stone”, “The Magic Tree”, “Tower To The Stars”}
Original Set2: {“Wizards of Ice”, “Call of the Forest”, “Lord of the Rings”}
Common books: Lord of the Rings, The Magic Tree
c) Original Set1: {“Lord of the Rings”, “Harry Potter and the Sorcerer’s Stone”, “The Magic Tree”, “Tower To The Stars”}
Original Set2: {“Wizards of Ice”, “Call of the Forest”, “Lord of the Rings”}
Common books: The Magic Tree
d) Original Set1: {“Lord of the Rings”, “Harry Potter and the Sorcerer’s Stone”, “The Magic Tree”, “Tower To The Stars”}
Original Set2: {“Wizards of Ice”, “Call of the Forest”, “Lord of the Rings”}
Common books: Wizards of Ice

Correct answer is: a) Original Set1: {“Lord of the Rings”, “Harry Potter and the Sorcerer’s Stone”, “The Magic Tree”, “Tower To The Stars”}
Original Set2: {“Wizards of Ice”, “Call of the Forest”, “Lord of the Rings”}
Common books: Lord of the Rings
Explanation: The code compares the elements in Set1 with Set2 and prints the books that exist in both sets. In this case, “Lord of the Rings” is the only book that appears in both sets, so it will be printed as the common book.

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

Set = {“I”, “am”, “Learning”, “Python”}
max_len = 0
max_word = 0
print(“Original Set: “, Set)
for word in Set:
    if len(word) > max_len:
        max_len = len(word)
        max_word = word
print(“Word having maximum length: “, max_word)
print(“Length of the word: “, max_len)

a) Original Set: {“I”, “am”, “Learning”, “Python”}
Word having maximum length: “Learning”
Length of the word: 8
b) Original Set: {“I”, “am”, “Learning”, “Python”}
Word having maximum length: “Python”
Length of the word: 6
c) Original Set: {“I”, “am”, “Learning”, “Python”}
Word having maximum length: “Learning”
Length of the word: 7
d) Original Set: {“I”, “am”, “Learning”, “Python”}
Word having maximum length: “am”
Length of the word: 2

Correct answer is: a) Original Set: {“I”, “am”, “Learning”, “Python”}
Word having maximum length: “Learning”
Length of the word: 8
Explanation: The code initializes the `Set` variable with a set of strings. It then iterates over each word in the set and checks if the length of the current word is greater than the current maximum length (`max_len`). If it is, it updates `max_len` and stores the current word as `max_word`. After the loop, it prints the original set, the word with the maximum length, and the length of that word.

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

a = {1,2,4,5}
b = {2,4}
print(“Original set1: “,a)
print(“Original set2: “,b)
count = 0
for ele in b:
    if ele in a:
        count +=1
if count == len(b):
    print(“b is subset of a”)
else:
    print(“b is not a subset of a”)

a) Original set1: {1, 2, 4, 5} Original set2: {2, 4} \n b is subset of a
b) Original set1: {1, 2, 4, 5} Original set2: {2, 4} \n b is not a subset of a
c) Original set1: {2, 4} Original set2: {1, 2, 4, 5} \n b is subset of a
d) Original set1: {2, 4} Original set2: {1, 2, 4, 5} \n b is not a subset of a

Correct answer is: a) Original set1: {1, 2, 4, 5} Original set2: {2, 4} \n b is a subset of a
Explanation: The code checks if every element in set b is also present in set a. If all elements in b are found in a, then b is considered a subset of a. Otherwise, it is not a subset. In this case, set a contains the elements [1, 2, 4, 5] and set b contains the elements [2, 4]. Since all elements in b (2 and 4) are present in a, the condition count == len(b) is satisfied, and the output is “b is a subset of a”.

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

a = {1,2,4,5}
b = {7,8,9}
print(“Original set1: “,a)
print(“Original set2: “,b)
print(“Are two sets dis-joint: “,a.isdisjoint(b))

a) Original set1: {1, 2, 4, 5} Original set2: {7, 8, 9} Are two sets disjoint: True
b) Original set1: {1, 2, 4, 5} Original set2: {7, 8, 9} Are two sets disjoint: False
c) Original set1: {1, 2, 4, 5} Original set2: {7, 8, 9} Are two sets disjoint: None
d) Error: The code contains a syntax error.

Correct answer is: a) Original set1: {1, 2, 4, 5} Original set2: {7, 8, 9} Are two sets disjoint: True
Explanation: The code initializes two sets, a and b, with the values {1, 2, 4, 5} and {7, 8, 9} respectively. The isdisjoint() method is then used to check if the two sets are disjoint (have no common elements). In this case, the sets have no common elements, so the output will be True.

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

a = {1, 2, 4, 5}
b = {2, 4}
print(“Original set1: “, a)
print(“Original set2: “, b)
print(“b is subset of a: “, b.issubset(a))

a) Original set1: {1, 2, 4, 5}
Original set2: {2, 4}
b is subset of a: True
b) Original set1: {1, 2, 4, 5}
Original set2: {2, 4}
b is subset of a: False
c) Original set1: {1, 2, 4, 5}
Original set2: {2, 4}
b is subset of a: None
d) Error: Invalid syntax in the code.

Correct answer is: a) Original set1: {1, 2, 4, 5}
Original set2: {2, 4}
b is subset of a: True
Explanation: The code defines two sets, `a` and `b`. `a` contains elements [1, 2, 4, 5], while `b` contains elements [2, 4]. The `issubset()` method is then used to check if `b` is a subset of `a`. Since all elements of `b` are present in `a`, the output is `True`.

17). Which statement is used to check if an element exists in a set?

a) if element in set:
b) if element exists(set):
c) if element.has(set):
d) if element.exists(set):

Correct answer is: a) if element in set:
Explanation: The “in” keyword is used to check if an element exists in a set.

18). What is the result of executing the following code:

set = {1, 2, 3}
print(2 in set)?

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

Correct answer is: a) True
Explanation: The “in” keyword checks if the element 2 exists in the set, which returns True.

19). Which method is used to return the maximum element from a set?

a) max()
b) maximum()
c) largest()
d) get_max()

Correct answer is: a) max()
Explanation: The max() function is used to return the maximum element from a set.

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

a = {1, 2, 4, 5, 7, 8, 9}
print(“Original set: “,a)
b = {7,8,9}
for ele in b:
    if ele in a:
        a.remove(ele)
print(“New set: “,a)

a) Original set: {1, 2, 4, 5, 7, 8, 9} New set: {1, 2, 4, 5}
b) Original set: {1, 2, 4, 5, 7, 8, 9} New set: {7, 8, 9}
c) Original set: {1, 2, 4, 5, 7, 8, 9} New set: {1, 2, 4, 5, 8, 9}
d) Original set: {1, 2, 4, 5, 7, 8, 9} New set: {1, 2, 4, 5, 7}

Correct answer is: c) Original set: {1, 2, 4, 5, 7, 8, 9} New set: {1, 2, 4, 5}
Explanation: The code starts with a set `a` containing elements {1, 2, 4, 5, 7, 8, 9}. It then defines another set `b` with elements {7, 8, 9}. The code then iterates over each element in `b` and checks if it exists in `a`. If an element is found in `a`, it is removed using the `remove()` method. After this process, the code prints the updated set `a`.

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

a = {1, 2, 4, 5, 7, 8, 9}
print(“Original set1: “,a)
if len(a) == 0:
    print(“Set is empty”)
else:
    print(“Set is not empty”)

a) Original set1: {1, 2, 4, 5, 7, 8, 9}
Set is empty
b) Original set1: {1, 2, 4, 5, 7, 8, 9}
Set is not empty
c) Original set1: {1, 2, 4, 5, 7, 8, 9}
Error: Set object has no attribute ’empty’
d) Original set1: {1, 2, 4, 5, 7, 8, 9}
Error: Set object has no attribute ‘len’

Correct answer is: b) Original set1: {1, 2, 4, 5, 7, 8, 9}
Set is not empty
Explanation: The code initializes a set a with elements [1, 2, 4, 5, 7, 8, 9]. The len(a) function returns the number of elements in the set, which is not equal to 0 in this case. Therefore, the condition len(a) == 0 evaluates to False. As a result, the code executes the else block and prints “Set is not empty”

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

a = {1, 2, 4, 5, 7, 8, 9}
b = {2,3,4}
print(“Original set1: “,a)
print(“Original set2: “,b)
if a == b:
   print(“Both sets are equal”)
else:
    print(“Both sets are not equal”)

a) Original set1: {1, 2, 4, 5, 7, 8, 9}
Original set2: {2, 3, 4}
Both sets are equal
b) Original set1: {1, 2, 4, 5, 7, 8, 9}
Original set2: {2, 3, 4}
Both sets are not equal
c) Original set1: {1, 2, 4, 5, 7, 8, 9}
Original set2: {2, 3, 4}
Error: Invalid comparison between sets
d) Error: Invalid syntax

Correct answer is: b) Original set1: {1, 2, 4, 5, 7, 8, 9}
Original set2: {2, 3, 4}
Both sets are not equal
Explanation: The code compares two sets, a and b, using the equality operator (==). Since the sets have different elements (set a has elements {1, 2, 4, 5, 7, 8, 9} and set b has elements {2, 3, 4}), the condition evaluates to False and the statement “Both sets are not equal” is printed.