[go: up one dir, main page]

0% found this document useful (0 votes)
23 views19 pages

PML - MCQ PS

The document outlines the structure and content of an examination for a Python for Machine Learning course, consisting of multiple-choice questions (MCQs) and passage-based questions. It includes instructions for the exam format, total marks, and sample questions covering various Python concepts and functionalities. The passages and related questions focus on practical applications of Python in different scenarios such as e-commerce, grading systems, and game development.

Uploaded by

subhayu2024
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views19 pages

PML - MCQ PS

The document outlines the structure and content of an examination for a Python for Machine Learning course, consisting of multiple-choice questions (MCQs) and passage-based questions. It includes instructions for the exam format, total marks, and sample questions covering various Python concepts and functionalities. The passages and related questions focus on practical applications of Python in different scenarios such as e-commerce, grading systems, and game development.

Uploaded by

subhayu2024
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

Practice Sheet

Python for Machine Learning (23CSH-281)

MCQ-format breakdown

General Instructions :
1.​ The exam will be conducted in 2 sections
2.​ Section A will contain 40 MCQ’s (1-40) of 1 mark each.
3.​ Section B will contain 8 passage based questions with 5 questions respectively
(41-80), each of which would carry 3 marks each.
4.​ Time of the examination will be 2 hours. After that the test will not accept any further
answers.

Total marks : 160


Python for Machine Learning
1. What is the correct file extension for Python files?
A. .pt
B. .py
C. .pyt
D. .python

2. Which of the following functions is used to take user input in Python?


A. scanf()
B. cin>>
C. input()
D. read()

3. What will be the output of print(type(True)) ?


A. <class 'bool'>
B. <class 'int'>
C. <type 'boolean'>
D. True

4. Which of the following is not a valid Python data type?


A. List
B. Set
C. Map
D. Dictionary

5. What will be the output of print(7 // 2) ?


A. 3.5
B. 3
C. 4
D. 3.0

6. Which of the following keywords is used for defining a function in Python?


A. define
B. function
C. func
D. def

7. In Python, which operator is used for exponentiation?


A. ^

1/18
B. **
C. %
D. //

8. What will be the result of:

python

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

A. A
B. B
C. C
D. A and B

9. Which function evaluates a string as a Python expression?


A. eval()
B. exec()
C. input()
D. str()

10. What is the output of the following code?

python

for i in range(3):
print(i, end=" ")

A. 0 1 2
B. 1 2 3
C. 0 1 2 3
D. 1 2

11. What is the output of the following function call?

python

2/18
def test(x):
return x * x
print(test(3))

A. 3
B. 6
C. 9
D. Error

12. Which keyword is used to exit the current loop in Python?


A. exit
B. stop
C. return
D. break

13. What will be the output of the following code?

python

s = "python"
print(s[2:5])

A. yth
B. tho
C. tho
D. tho

14. Which of the following is not a valid string method?


A. upper()
B. reverse()
C. find()
D. replace()

15. What does the following code print?

python

import numpy as np
a = np.array([[1, 2], [3, 4]])
print(a[1][0])

3/18
A. 2
B. 3
C. 4
D. Error

16. What is the output of the following list operation?

python

lst = [1, 2, 3]
lst.append([4, 5])
print(lst)

A. [1, 2, 3, 4, 5]
B. [1, 2, 3, [4, 5]]
C. [1, 2, 3, (4, 5)]
D. Error

17. Which of the following operations is not valid on a list?


A. Indexing
B. Appending
C. Popping
D. Hashing

18. What is the output of the following dictionary operation?

python

d = {'a': 1, 'b': 2}
d['c'] = 3
print(len(d))

A. 1
B. 2
C. 3
D. Error

19. What will the following code print?

python

4/18
t = (1, 2, 3)
print(t[1])

A. 1
B. 2
C. (2,)
D. Error

20. What is the result of the following set operation?

python

a = {1, 2, 3}
b = {3, 4, 5}
print(a & b)

A. {1, 2, 3, 4, 5}
B. {3}
C. {1, 2}
D. {}

21. Which method is used to remove an item from a set?


A. discard()
B. pop()
C. remove()
D. All of the above

22. What will be the output of the following code?

python

class Demo:
def __init__(self):
self.x = 10
obj = Demo()
print(obj.x)

A. 0
B. 10
C. Error
D. None

5/18
23. What is the output of the following code?

python

class A:
def show(self):
return "Class A"

class B(A):
def show(self):
return super().show() + " & Class B"

obj = B()
print(obj.show())

A. Class B
B. Class A & Class B
C. Class A
D. Error

24. Which of the following best defines polymorphism in Python?


A. One method with many forms
B. One class with many methods
C. Multiple classes with one method
D. Hiding internal state of object

25. What is the correct mode to open a file for reading and writing in text mode, without
truncating it?
A. 'r+'
B. 'w+'
C. 'a+'
D. 'x+'

26. What does the following code do?

python

f = open("data.txt", "w")
f.write("Hello")
f.close()

6/18
A. Appends "Hello" to data.txt
B. Writes "Hello" to data.txt, overwriting existing content
C. Reads "Hello" from data.txt
D. Causes an error

27. Which method is used to read a single line from a file?


A. readline()
B. readlines()
C. readline
D. fetchline()

28. What is the output of the following code?

python

try:
x = 10 / 0
except ZeroDivisionError:
print("Division by zero!")

A. Error
B. Division by zero!
C. ZeroDivisionError
D. None

29. Which clause is executed only if no exception is raised in the try block?
A. finally
B. except
C. else
D. raise

30. What is the purpose of the finally block in exception handling?


A. Executes only if exception occurs
B. Executes only if no exception occurs
C. Always executes
D. Only used with assertions

31. What will be the output of the following code?

python

7/18
try:
assert 2 + 2 == 5
except AssertionError:
print("Assertion Error!")

A. Assertion Error!
B. Error
C. 2 + 2 == 5
D. Nothing

32. Which Python module is primarily used for data analysis and manipulation?
A. NumPy
B. Matplotlib
C. Pandas
D. Tkinter

33. What will be the shape of the DataFrame created below?

python

import pandas as pd
df = pd.DataFrame([[1, 2], [3, 4], [5, 6]])
print(df.shape)

A. (3, 2)
B. (2, 3)
C. (6, 1)
D. (1, 6)

34. What function is used to plot a line graph using Matplotlib?


A. plt.draw()
B. plt.plot()
C. plt.line()
D. plt.graph()

35. Which method is used in Pandas to display the first 5 rows of a DataFrame?
A. df.top()
B. df.first()
C. df.head()
D. df.show()

8/18
36. What does the following code output?

python

import pandas as pd
df = pd.DataFrame({'A':[1,2],'B':[3,4]})
print(df['B'].mean())

A. 7
B. 3
C. 3.5
D. Error

37. Which of the following can be used to create GUI applications in Python?
A. Pandas
B. NumPy
C. Tkinter
D. Matplotlib

38. What is the output of the following code?

python

import os
print(os.getcwd())

A. Creates a new directory


B. Prints the current working directory
C. Deletes a file
D. Lists all directories

39. What does the raise keyword do in Python?


A. Catches an exception
B. Defines an exception
C. Triggers an exception
D. Ignores exceptions

40. What does with open("file.txt", "r") as f: ensure?


A. Manual closing of file is required
B. File is only opened temporarily

9/18
C. Automatic file closing after block execution
D. File is locked from writing

"Passage 1"
An e-commerce website is trying to calculate the total price of items a user adds to their cart.
They use Python to develop this feature. Initially, when the cart is empty, the total is zero.
Every time the user adds an item, its price is added to the total using a loop. A function
calculate_total() takes the list of item prices and returns the sum. The team also ensures
that only positive numbers are accepted by using a conditional expression before adding
prices. To take user input, they use input() and convert it to integers using eval() . This
script is part of a larger application written in Python 3.

"Questoins"
41. Which of the following is most suitable for checking if the entered item price is positive?
A. if price > 0:
B. if price < 0:
C. if price == 0:
D. if price != 0:

42. What data type is most appropriate to store the list of item prices?
A. Dictionary
B. Tuple
C. List
D. Set

43. Which function is used to take the item price as input from the user?
A. scanf()
B. input()
C. print()
D. read()

44. What is the purpose of using a function like calculate_total() in the script?
A. To take input
B. To format strings
C. To encapsulate the logic for total price
D. To raise exceptions

45. If the team wants to repeat the price entry process until the user types "done", which
loop is best?
A. For loop with fixed range

10/18
B. While loop with condition input != "done"
C. Do-while loop
D. Recursive call without condition

"Passage 2"
A school is digitizing its student grading system using Python. Each student’s name and
score are stored in a dictionary. The teacher enters data using the input() function, and
then a function called get_grade(score) returns a letter grade (A/B/C/etc.) based on the
score. The teacher can enter multiple scores using a loop, and at the end, the program
displays all students' names and their corresponding grades. This use of Python helps
teachers reduce manual workload and human errors.

"Questions"
46. What Python data structure is best for storing student names and scores?
A. List
B. Set
C. Tuple
D. Dictionary

47. Which of the following best describes the role of get_grade(score) ?


A. Input validation
B. Conditional expression
C. Grade mapping function
D. Recursion

48. Which statement can be used to traverse each key-value pair in the dictionary?
A. for i in range(len(dict))
B. for key, value in dict.items()
C. for key in dict.keys()
D. while True

49. Which Python control statement allows adding multiple student scores without knowing
how many will be entered?
A. for i in range(n)
B. while condition
C. do...while
D. goto

50. How can the program ensure the grade is shown for each student at the end?
A. Use print() inside the loop

11/18
B. Store output in a list
C. Use another function
D. Use print() after dictionary is fully populated

"Passage 3"
A local food delivery service is maintaining data about customer orders using Python. Each
order includes the customer's name, order ID, and items ordered. These details are stored
using a dictionary where the key is the order ID and the value is a list containing the
customer's name and items. String operations are used to format the receipt, while list
methods like append() are used to add items. The system also allows checking if a specific
item exists in the order using the in operator and slices a part of the list if needed to show
only main dishes.

"Questoins"
51. Which Python feature is used to store both the customer's name and items in one value
against an order ID?
A. Tuple
B. Set
C. List
D. String

52. Which method would be used to add a new item to the order list?
A. insert()
B. append()
C. add()
D. extend()

53. Which operator is used to check if an item exists in a list?


A. ==
B. !=
C. in
D. is

54. To display the first 3 items in an order, which of the following is correct?
A. order[0:2]
B. order[1:3]
C. order[0:3]
D. order[:2]

12/18
55. If you want to generate a formatted string showing a customer's name and item list,
which function is ideal?
A. len()
B. format()
C. sum()
D. map()

"Passage 4"
A game development company is using Python classes to build characters in a game. Each
character has attributes like name, health, and power, which are defined using class
properties. The class also contains methods like attack() and defend() . When a new
character is created, it uses the __init__() method. Inheritance is used to create specific
characters like “Warrior” and “Mage” from a common base class “Character.” The developers
also use method overriding to change the attack() method for different character types.

"Questions"
56. Which Python concept allows different character types like “Warrior” and “Mage” to be
derived from a base class?
A. Encapsulation
B. Inheritance
C. Composition
D. Polymorphism

57. What is the role of the __init__() method in a class?


A. Handle errors
B. Initialize object attributes
C. Overload operators
D. Create a list

58. How is method overriding implemented in subclasses?


A. Defining a new method with a different name
B. Using the same method name with updated logic
C. Using the super() method without changes
D. Creating static methods

59. If the base class is Character , which syntax correctly defines a derived class Warrior ?
A. class Warrior:
B. class Warrior[Character]:
C. class Warrior inherits Character:
D. class Warrior(Character):

13/18
60. What does the super() function do in inheritance?
A. Deletes the parent class
B. Calls the constructor of the child class
C. Calls methods from the parent class
D. Overrides the parent method automatically

"Passage 5"
A school management system records student attendance daily in a text file. The file
contains lines in the format: RollNo,Name,Present/Absent . Every evening, a Python script
reads the file line by line using open() in read mode, parses the data using the split()
function, and generates a summary of absentees. At the end of each week, the script
appends the weekly report to another file using write mode to maintain a permanent record.
This approach ensures automated file management for attendance tracking.

"Questoins"
61. Which Python function is used to open the file in read mode?
A. file.read()
B. open(filename, "r")
C. read("filename")
D. openfile("read")

62. If the file contains lines of text, which method will read all lines into a list?
A. read()
B. readline()
C. readlines()
D. splitlines()

63. What is the purpose of the split() function in this context?


A. To join text
B. To divide text into parts using a delimiter
C. To remove whitespace
D. To convert numbers to strings

64. Which mode should be used to append data to the end of a file?
A. "r"
B. "w"
C. "x"
D. "a"

14/18
65. What will happen if you try to open a file in "w" mode that already exists?
A. It will read the file
B. It will append to the file
C. It will delete the existing content
D. It will lock the file

"Passage 6"
A data analysis startup collects daily sales figures from multiple vendors and writes the
numbers to a file using Python. Later, a program reads these numbers, calculates the total
and average sales, and displays them using print statements. During file operations, the
team often uses try-except blocks to handle unexpected errors like missing files or corrupt
data. This ensures that the program does not crash and informs the user gracefully about
the issue.

"Questions"
66. What is the purpose of using a try-except block in file handling?
A. To format the file
B. To handle runtime errors
C. To write more data
D. To speed up execution

67. What will the except block execute if the file is missing?
A. Raise a SyntaxError
B. Ignore the code
C. Execute code inside the except block
D. Automatically create a new file

68. Which error is likely to occur if the file does not exist while opening in read mode?
A. ZeroDivisionError
B. FileNotFoundError
C. AssertionError
D. IndexError

69. Which clause can be added to the try-except structure to run only when no exceptions
occur?
A. finally
B. elif
C. else
D. pass

15/18
70. What does the finally block ensure during file handling?
A. That the file is read
B. That the program stops
C. That cleanup code runs regardless of exceptions
D. That the data is correct

"Passage 7"
A hospital management system built in Python processes patient data daily. Sometimes the
data files may be missing or improperly formatted. To ensure smooth execution, the system
uses try-except blocks. If a ValueError or FileNotFoundError occurs, the program
catches the exception and notifies the admin without crashing. In addition, the finally
block is used to close the file or release memory, regardless of whether an exception
occurred or not.

"Questoins"
71. What type of error is raised when a file that doesn't exist is accessed in read mode?
A. ValueError
B. KeyError
C. FileNotFoundError
D. TypeError

72. What is the correct syntax to catch a ValueError ?


A. try: ... except ValueError:
B. try: ... ValueError except:
C. try ValueError: ... except:
D. catch(ValueError):

73. What is the role of the finally block in exception handling?


A. Execute only if exception occurs
B. Skip execution after try
C. Execute regardless of exception occurrence
D. Store exception details

74. Which error is typically raised when converting non-numeric strings to integers using
int() ?
A. FileNotFoundError
B. ValueError
C. IndexError
D. TypeError

16/18
75. Which clause runs only when the try block does not raise any exception?
A. except
B. finally
C. raise
D. else

"Passage 8"
A data analyst uses the Pandas library in Python to clean and analyze customer purchase
data. The data is loaded into a DataFrame using pd.read_csv() . The analyst performs
operations like filtering rows, calculating mean values, and plotting graphs using Matplotlib.
Finally, a Tkinter-based GUI displays summarized reports, allowing managers to interact with
the data visually.

"Questions"
76. What is the primary data structure used in Pandas for tabular data?
A. List
B. Dictionary
C. DataFrame
D. Tuple

77. Which function is used to read CSV files in Pandas?


A. read_file()
B. csv.load()
C. pd.read_csv()
D. import_csv()

78. What is the use of Matplotlib in the above context?


A. File handling
B. GUI development
C. Plotting graphs
D. Handling exceptions

79. Which Python library is used to create GUIs?


A. Pandas
B. NumPy
C. Matplotlib
D. Tkinter

80. What does df.mean() compute in a DataFrame?


A. Total number of rows

17/18
B. Sum of values
C. Average of numeric columns
D. Maximum value

18/18

You might also like