wayground logo

Free Printable Worksheets

Font size

S
M
L
XL
Worksheets

MSTIP-CC103-FinalExam

Total questions: 120

Worksheet time: 2hrs 0mins

Name
Class
Date
1.

What is the output of the following code? class A: def __init__(self): self.var = 1 a = A() print(a.var)

a)

0

b)

1

c)

None

d)

Error

2.

What will be the output? class A: def __init__(self): self.val = 5 def get_val(self): return self.val a = A() a.val = 10 print(a.get_val())

a)

5

b)

10

c)

None

d)

Error

3.

Which method is called when an object is created? class B: def __init__(self): print("Object created")

a)

__new__()

b)

__init__()

c)

__str__()

d)

__call__()

4.

What is the output? class A: def __str__(self): return "Hello" a = A() print(a)

a)

Hello

b)

A

c)
d)

Error

5.

What will be the output? class Parent: def greet(self): print("Hello from Parent") class Child(Parent): pass c = Child() c.greet()

a)

Error

b)

Nothing

c)

Hello from Parent

d)

Hello from Child

6.

Which of the following defines inheritance correctly? class Base: pass class Derived(Base): pass

a)

class Base(Derived)

b)

class Derived -> Base

c)

class Derived(Base)

d)

Derived inherits Base()

7.

What does the following code print? class A: def __init__(self): self.data = "A" class B(A): def __init__(self): super().__init__() self.data = "B" b = B() print(b.data)

a)

A

b)

B

c)

AB

d)

Error

8.

What is the output? class A: def show(self): print("A") class B(A): def show(self): print("B") obj = B() obj.show()

a)

A

b)

B

c)

AB

d)

Error

9.

What is the result? class A: __private = 10 def get_private(self): return A.__private a = A() print(a.get_private())

a)

10

b)

__private

c)

Error

d)

None

10.

What does the following code do? class A: count = 0 def __init__(self): A.count += 1 a = A() b = A() print(A.count)

a)

1

b)

2

c)

0

d)

Error

11.

What is the purpose of super()?

a)

Create a new superclass

b)

Access methods of the base class

c)

Override base methods

d)

Instantiate class attributes

12.

What does this code output? class A: def __init__(self): self.__x = 10 a = A() print(hasattr(a, '__x'))

a)

True

b)

False

c)

Error

d)

10

13.

What happens here? class A: def hello(self): print("Hello") a = A() a.hello = "Hi" print(a.hello)

a)

Hello

b)

Hi

c)

Error

d)

None

14.

What's the output? class A: def __del__(self): print("Destructor called") a = A() del a

a)

Destructor called

b)

Error

c)

None

d)

No output

15.

What is printed? class A: def __init__(self, x): self.x = x a = A(5) print(a.x)

a)

0

b)

5

c)

None

d)

Error

16.

What does isinstance() do in this code? class A: pass a = A() print(isinstance(a, A))

a)

Checks if a is a class

b)

Checks if A is an instance

c)

Returns True

d)

Returns False

17.

Output of this code? class A: def __init__(self): print("A init") class B(A): def __init__(self): super().__init__() print("B init") b = B()

a)

A init

b)

B init

c)

A init B init

d)

Error

18.

What will happen? class A: def __call__(self): print("Called") a = A() a()

a)

Error

b)

Called

c)

None

d)

__call__

19.

What does @staticmethod do? class A: @staticmethod def stat(): print("Static method")

a)

Binds method to instance

b)

Binds method to class

c)

No self or cls needed

d)

Makes method private

20.

What’s the output here? class A: val = 5 @classmethod def show(cls): print(cls.val) A.show()

a)

5

b)

Error

c)

cls

d)

None

21.

What will be the output of the following code? a = [1, 2, 3] b = a b.append(4) print(a)

a)

[1, 2, 3]

b)

[1, 2, 3, 4]

c)

Error

d)

[4, 1, 2, 3]

22.

Which of the following creates a shallow copy of a list? a = [1, 2, 3]

a)

b = a.copy()

b)

b = list(a)

c)

b = a[:]

d)

All of the above

23.

What does list1.extend(list2) do?

a)

Replaces list1 with list2

b)

Adds elements of list2 to the end of list1

c)

Appends list2 as an element to list1

d)

Returns a new list

24.

What will be the output of: x = [10, 20, 30] print(x.pop(1))

a)

10

b)

20

c)

30

d)

None

25.

Which method returns the number of times a value appears in the list?

a)

index()

b)

count()

c)

find()

d)

search()

26.

Which of the following list operations is not in-place?

a)

sort()

b)

append()

c)

sorted()

d)

extend()

27.

What is the result of list("abc")?

a)

['abc']

b)

['a', 'b', 'c']

c)

['a b c']

d)

['a-b-c']

28.

What will be the output? a = [1, 2, 3] a[1:2] = [4, 5] print(a)

a)

[1, 4, 5]

b)

[1, 4, 5, 2, 3]

c)

[1, 4, 5, 3]

d)

Error

29.

What does this list comprehension do? [x*x for x in range(3)]

a)

[1, 2, 3]

b)

[0, 1, 4]

c)

[0, 1, 2]

d)

[1, 4, 9]

30.

How to remove all items from a list?

a)

del list

b)

list.remove()

c)

list.clear()

d)

list = []

31.

Which of the following is a tuple?

a)

(1,)

b)

(1)

c)

1,

d)

All of the above

32.

Tuples are:

a)

Mutable

b)

Immutable

c)

Changeable

d)

Dynamic

33.

What will this output? t = (1, 2, 3) print(t[1])

a)

1

b)

2

c)

3

d)

Error

34.

Can a tuple contain a list?

a)

No

b)

Yes, but it's immutable

c)

Yes

d)

Only if the list is empty

35.

What will tuple("abc") return?

a)

('abc')

b)

['a', 'b', 'c']

c)

('a', 'b', 'c')

d)

('abc',)

36.

Which method is available for tuples?

a)

append()

b)

insert()

c)

count()

d)

pop()

37.

What is the result of: t = (1, 2, 3) t + (4, 5)

a)

(1, 2, 3, 4, 5)

b)

(1, 2, 3)

c)

Error

d)

None

38.

What is the result of len((1, [2, 3], 4))?

a)

3

b)

4

c)

5

d)

2

39.

What does t.index(2) return for t = (1, 2, 3, 2)?

a)

2

b)

1

c)

3

d)

Error

40.

Which is faster for iteration:

a)

List

b)

Tuple

c)

Both are same

d)

None

41.

What is the output of: d = {'a': 1, 'b': 2} print(d['c'])

a)

None

b)

0

c)

Error

d)

[]

42.

Which method returns a list of key-value tuple pairs?

a)

keys()

b)

values()

c)

items()

d)

get()

43.

How to safely access a key that may not exist in a dictionary?

a)

dict['key']

b)

dict.get('key')

c)

dict.key

d)

dict.fetch('key')

44.

What is the output of len({'a': 1, 'b': 2, 'a': 3})?

a)

3

b)

2

c)

1

d)

Error

45.

What does dict.update({'c': 3}) do?

a)

Adds key 'c' with value 3

b)

Replaces dictionary

c)

Clears dictionary

d)

Returns error

46.

What will dict.pop('x') do if 'x' does not exist?

a)

Returns None

b)

Raises KeyError

c)

Deletes key

d)

Returns 0

47.

How to loop over dictionary keys and values? for k, v in ___: ...

a)

dict

b)

dict.items()

c)

dict.keys()

d)

dict.values()

48.

Can a dictionary key be a list?

a)

Yes

b)

No

c)

Only if list is empty

d)

Only in Python 3

49.

What is the output of: d = dict([('a', 1), ('b', 2)]) print(d)

a)

['a': 1, 'b': 2]

b)

{('a', 1), ('b', 2)}

c)

{'a': 1, 'b': 2}

d)

Error

50.

Which method removes all dictionary items?

a)

del dict

b)

dict.clear()

c)

dict.remove_all()

d)

dict.pop()

51.

What is the result of: s = {1, 2, 3, 2} print(s)

a)

{1, 2, 3, 2}

b)

{1, 2, 3}

c)

[1, 2, 3]

d)

Error

52.

What is the output of: a = {1, 2} b = {2, 3} print(a & b)

a)

{1, 2, 3}

b)

{2}

c)

{1}

d)

{}

53.

Which operation returns elements not common to both sets?

a)

a | b

b)

a & b

c)

a ^ b

d)

a - b

54.

How to check if an element exists in a set?

a)

in

b)

exists()

c)

has()

d)

include()

55.

What is the result of: a = set("abc") a.add("d") print(a)

a)

['a', 'b', 'c', 'd']

b)

{'a', 'b', 'c', 'd'}

c)

('a', 'b', 'c', 'd')

d)

{a, b, c, d}

56.

Which of the following is not allowed in a set?

a)

Integer

b)

Tuple

c)

List

d)

String

57.

How to remove all items from a set?

a)

set.remove_all()

b)

set.clear()

c)

set.delete()

d)

del set[:]

58.

Which method removes an item from a set if it exists?

a)

discard()

b)

remove()

c)

pop()

d)

delete()

59.

Which method can throw a KeyError if the item is not found?

a)

discard()

b)

remove()

c)

clear()

d)

pop()

60.

What does a - b do for sets a and b?

a)

Intersection

b)

Union

c)

Difference

d)

Symmetric difference

61.

What will be the output of the following code? try: x = 5 / 0 except ZeroDivisionError: print("Division by zero")

a)

Error

b)

Division by zero

c)

Zero

d)

None

62.

What is printed? try: int("hello") except ValueError: print("Caught ValueError")

a)

hello

b)

Caught ValueError

c)

Error

d)

None

63.

Identify the output: try: x = [1, 2, 3] print(x[5]) except IndexError: print("Index error")

a)

3

b)

Error

c)

Index error

d)

None

64.

What will be the result? try: print(10 / 2) except ZeroDivisionError: print("Can't divide") else: print("No error!")

a)

5.0

b)

5.0 No error!

c)

Can't divide

d)

No error!

65.

Output of this code: try: raise ValueError("Test error") except ValueError as e: print(e)

a)

ValueError

b)

Test error

c)

e

d)

None

66.

Result of the code? try: a = int("10a") except Exception: print("General error")

a)

10a

b)

General error

c)

ValueError

d)

None

67.

What will this print? try: {}["key"] except KeyError: print("Key not found")

a)

Error

b)

Key not found

c)

None

d)

"key"

68.

Choose the correct output: try: print("A") finally: print("B")

a)

A

b)

A B

c)

B

d)

Nothing

69.

What gets printed? try: 1 / 0 except ZeroDivisionError: print("Zero division") finally: print("Cleanup")

a)

Zero division

b)

Cleanup

c)

Zero division Cleanup

d)

Error

70.

What's the output? try: x = 10 finally: print("Always runs")

a)

Always runs

b)

Error

c)

x = 10

d)

None

71.

Behavior of this code: try: raise KeyboardInterrupt except: print("Exception caught")

a)

Exception caught

b)

Nothing

c)

Error

d)

Interrupt

72.

What gets printed? try: 1 / 1 except ZeroDivisionError: print("Divide by zero") else: print("Success") finally: print("Done")

a)

Success Done

b)

Divide by zero

c)

Done

d)

Error

73.

What is the result? try: open("nofile.txt") except FileNotFoundError: print("File missing")

a)

Error

b)

File missing

c)

FileNotFoundError

d)

None

74.

Output of the following: try: a = [1, 2, 3] print(a[3]) except Exception as e: print(type(e).__name__)

a)

IndexError

b)

Exception

c)

NameError

d)

ValueError

75.

Result of this code? try: print("Try") raise Exception("Oops") print("After raise") except: print("Except")

a)

Try After raise Except

b)

Try Except

c)

Oops

d)

Error

76.

Identify the output: try: 5 + "5" except TypeError: print("Cannot add int and str")

a)

10

b)

Error

c)

Cannot add int and str

d)

None

77.

What will be printed? def div(a, b): try: return a / b except ZeroDivisionError: return "Error" print(div(10, 0))

a)

10

b)

0

c)

Error

d)

None

78.

What is the result? try: print(undefined_var) except NameError: print("Undefined variable")

a)

Error

b)

Undefined variable

c)

NameError

d)

None

79.

Output? try: pass except: print("Error") else: print("No error")

a)

Error

b)

No error

c)

Nothing

d)

Pass

80.

What happens here? try: x = int("123") y = int("abc") except ValueError as ve: print("Caught:", ve)

a)

Caught: invalid literal

b)

Error

c)

123

d)

Caught: abc

81.

What does the following code do? import tkinter as tk root = tk.Tk() label = tk.Label(root, text="Hello, World!") label.pack() root.mainloop()

a)

Displays a label with text inside a window

b)

Opens a text file

c)

Creates a button

d)

Closes a window

82.

What is the purpose of mainloop() in Tkinter? root.mainloop()

a)

Exits the application

b)

Creates a widget

c)

Starts the GUI event loop

d)

Destroys the root window

83.

What does the pack() method do? button.pack()

a)

Destroys a widget

b)

Adds a widget to the grid

c)

Arranges a widget in the window

d)

Changes a widget’s text

84.

How do you create a button that closes the window when clicked? import tkinter as tk root = tk.Tk() button = tk.Button(root, text="Exit", command=root.destroy) button.pack() root.mainloop()

a)

Closes the system

b)

Creates an exit dialog

c)

Closes the window

d)

Minimizes the window

85.

Which geometry manager allows specifying row and column?

a)

pack()

b)

grid()

c)

place()

d)

align()

86.

Which of the following correctly adds an entry widget? entry = tk.Entry(root) entry.pack()

a)

Adds a dropdown

b)

Adds a label

c)

Adds a text box for input

d)

Adds a button

87.

How can you get the content of an Entry widget? entry.get()

a)

entry.value()

b)

entry.text()

c)

entry.content()

d)

entry.get()

88.

What will this code do? label = tk.Label(root, text="Click Me") label.config(fg="blue") label.pack()

a)

Display a red label

b)

Make text bold

c)

Change text color to blue

d)

Set font size

89.

What happens if you call pack() and grid() on the same widget?

a)

Works fine

b)

Raises a warning

c)

Raises a TclError

d)

Automatically chooses one

90.

What does this snippet do? tk.Label(root, text="Name").grid(row=0, column=0) tk.Entry(root).grid(row=0, column=1)

a)

Adds a dropdown

b)

Adds a label only

c)

Adds a label and input field side by side

d)

Adds a label below input field

91.

How do you set the window title in Tkinter? root.title("My App")

a)

root.name("My App")

b)

root.label("My App")

c)

root.set_title("My App")

d)

root.title("My App")

92.

Which widget allows multiline text input?

a)

Entry

b)

Label

c)

Text

d)

StringVar

93.

How to change the background color of a window? root.configure(bg="lightblue")

a)

root.color("lightblue")

b)

root.setBackground("lightblue")

c)

root.background = "lightblue"

d)

root.configure(bg="lightblue")

94.

What does command=my_function mean in a button?

a)

Runs the function immediately

b)

Attaches the function to button click

c)

Creates a new window

d)

Changes button color

95.

What is the default layout manager in Tkinter?

a)

grid

b)

pack

c)

place

d)

flex

96.

Which method can position a widget at an absolute location?

a)

grid()

b)

pack()

c)

place()

d)

align()

97.

How to bind a keypress to an event handler? root.bind("", on_enter)

a)

root.set("", on_enter)

b)

root.event("", on_enter)

c)

root.bind("", on_enter)

d)

root.attach("", on_enter)

98.

How do you insert text into a Text widget? text.insert("1.0", "Hello!")

a)

text.add("Hello!")

b)

text.put("1.0", "Hello!")

c)

text.insert("1.0", "Hello!")

d)

text.set("Hello!")

99.

What does this code create? from tkinter import messagebox messagebox.showinfo("Info", "Operation Complete")

a)

A label

b)

A warning box

c)

A confirmation box

d)

An informational pop-up

100.

Which widget is used to group related widgets?

a)

Label

b)

Frame

c)

Entry

d)

Listbox

101.

What does the following code print? with open("sample.txt", "w") as f: f.write("Line 1\nLine 2\nLine 3") with open("sample.txt", "r") as f: print(len(f.readlines()))

a)

1

b)

2

c)

3

d)

0

102.

What will be the file content after executing the code? with open("file.txt", "w") as f: f.write("Hello\nWorld") with open("file.txt", "a") as f: f.write("\nPython")

a)

Overwritten with "Python"

b)

Contains only "Python"

c)

Contains "Hello\nWorld\nPython"

d)

Error

103.

What does the with statement ensure in file handling?

a)

File is opened in append mode

b)

File is deleted after use

c)

Automatic closing of file

d)

File is locked

104.

What happens if you read a file that does not exist? with open("nonexistent.txt", "r") as f: print(f.read())

a)

Returns empty string

b)

Creates the file

c)

Raises FileNotFoundError

d)

Raises IOError

105.

Which mode opens a file for both reading and writing?

a)

"w"

b)

"r"

c)

"a"

d)

"r+"

106.

What is the output? with open("file.txt", "w+") as f: f.write("12345") f.seek(0) print(f.read(2))

a)

12345

b)

12

c)

345

d)

1

107.

What is the effect of seek(0)?

a)

Closes the file

b)

Resets file pointer to beginning

c)

Moves to end of file

d)

Deletes file contents

108.

What does this code do? with open("file.txt", "w") as f: pass

a)

Deletes the file

b)

Creates an empty file

c)

Appends text

d)

Raises an error

109.

Which method checks if file is closed?

a)

isclosed()

b)

closed()

c)

f.closed

d)

f.isclosed()

110.

What will this print? with open("file.txt", "w") as f: f.write("test") print(f.closed)

a)

False

b)

True

c)

Error

d)

None

111.

What does "a" mode do?

a)

Replaces content

b)

Adds to existing content

c)

Only reads file

d)

Deletes file

112.

Which method reads all lines into a list?

a)

readline()

b)

readlines()

c)

read()

d)

readall()

113.

Output? with open("test.txt", "w") as f: f.writelines(["A\n", "B\n"])

a)

Writes string "writelines"

b)

Writes "A" and "B" on separate lines

c)

Error

d)

Writes only A

114.

What does this code do? f = open("log.txt", "x")

a)

Appends if file exists

b)

Overwrites file

c)

Creates file, error if exists

d)

Reads file

115.

What will f.tell() return? with open("a.txt", "w") as f: f.write("abc") print(f.tell())

a)

0

b)

1

c)

3

d)

Error

116.

Which function writes a string to file?

a)

writefile()

b)

writelines()

c)

write()

d)

put()

117.

What is the correct way to read a file line by line? with open("data.txt", "r") as f: for line in f: print(line)

a)

Correct

b)

Error

c)

Needs readline()

d)

Needs readlines()

118.

What does f.flush() do?

a)

Closes file

b)

Writes buffer to disk

c)

Reopens file

d)

Deletes content

119.

What does this code output? with open("test.txt", "w") as f: f.write("abc") f = open("test.txt", "r") print(f.read(1)) f.close()

a)

"abc"

b)

"a"

c)

"b"

d)

Error

120.

What's the result? with open("data.txt", "w") as f: f.write("line1\nline2") with open("data.txt") as f: print(f.readline())

a)

"line1"

b)

"line1\n"

c)

"line2"

d)

Error