Font size
WorksheetsMSTIP-CC103-FinalExam
Total questions: 120
Worksheet time: 2hrs 0mins
What is the output of the following code? class A: def __init__(self): self.var = 1 a = A() print(a.var)
0
1
None
Error
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())
5
10
None
Error
Which method is called when an object is created? class B: def __init__(self): print("Object created")
__new__()
__init__()
__str__()
__call__()
What is the output? class A: def __str__(self): return "Hello" a = A() print(a)
Hello
A
Error
What will be the output? class Parent: def greet(self): print("Hello from Parent") class Child(Parent): pass c = Child() c.greet()
Error
Nothing
Hello from Parent
Hello from Child
Which of the following defines inheritance correctly? class Base: pass class Derived(Base): pass
class Base(Derived)
class Derived -> Base
class Derived(Base)
Derived inherits Base()
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
B
AB
Error
What is the output? class A: def show(self): print("A") class B(A): def show(self): print("B") obj = B() obj.show()
A
B
AB
Error
What is the result? class A: __private = 10 def get_private(self): return A.__private a = A() print(a.get_private())
10
__private
Error
None
What does the following code do? class A: count = 0 def __init__(self): A.count += 1 a = A() b = A() print(A.count)
1
2
0
Error
What is the purpose of super()?
Create a new superclass
Access methods of the base class
Override base methods
Instantiate class attributes
What does this code output? class A: def __init__(self): self.__x = 10 a = A() print(hasattr(a, '__x'))
True
False
Error
10
What happens here? class A: def hello(self): print("Hello") a = A() a.hello = "Hi" print(a.hello)
Hello
Hi
Error
None
What's the output? class A: def __del__(self): print("Destructor called") a = A() del a
Destructor called
Error
None
No output
What is printed? class A: def __init__(self, x): self.x = x a = A(5) print(a.x)
0
5
None
Error
What does isinstance() do in this code? class A: pass a = A() print(isinstance(a, A))
Checks if a is a class
Checks if A is an instance
Returns True
Returns False
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 init
B init
A init B init
Error
What will happen? class A: def __call__(self): print("Called") a = A() a()
Error
Called
None
__call__
What does @staticmethod do? class A: @staticmethod def stat(): print("Static method")
Binds method to instance
Binds method to class
No self or cls needed
Makes method private
What’s the output here? class A: val = 5 @classmethod def show(cls): print(cls.val) A.show()
5
Error
cls
None
What will be the output of the following code? a = [1, 2, 3] b = a b.append(4) print(a)
[1, 2, 3]
[1, 2, 3, 4]
Error
[4, 1, 2, 3]
Which of the following creates a shallow copy of a list? a = [1, 2, 3]
b = a.copy()
b = list(a)
b = a[:]
All of the above
What does list1.extend(list2) do?
Replaces list1 with list2
Adds elements of list2 to the end of list1
Appends list2 as an element to list1
Returns a new list
What will be the output of: x = [10, 20, 30] print(x.pop(1))
10
20
30
None
Which method returns the number of times a value appears in the list?
index()
count()
find()
search()
Which of the following list operations is not in-place?
sort()
append()
sorted()
extend()
What is the result of list("abc")?
['abc']
['a', 'b', 'c']
['a b c']
['a-b-c']
What will be the output? a = [1, 2, 3] a[1:2] = [4, 5] print(a)
[1, 4, 5]
[1, 4, 5, 2, 3]
[1, 4, 5, 3]
Error
What does this list comprehension do? [x*x for x in range(3)]
[1, 2, 3]
[0, 1, 4]
[0, 1, 2]
[1, 4, 9]
How to remove all items from a list?
del list
list.remove()
list.clear()
list = []
Which of the following is a tuple?
(1,)
(1)
1,
All of the above
Tuples are:
Mutable
Immutable
Changeable
Dynamic
What will this output? t = (1, 2, 3) print(t[1])
1
2
3
Error
Can a tuple contain a list?
No
Yes, but it's immutable
Yes
Only if the list is empty
What will tuple("abc") return?
('abc')
['a', 'b', 'c']
('a', 'b', 'c')
('abc',)
Which method is available for tuples?
append()
insert()
count()
pop()
What is the result of: t = (1, 2, 3) t + (4, 5)
(1, 2, 3, 4, 5)
(1, 2, 3)
Error
None
What is the result of len((1, [2, 3], 4))?
3
4
5
2
What does t.index(2) return for t = (1, 2, 3, 2)?
2
1
3
Error
Which is faster for iteration:
List
Tuple
Both are same
None
What is the output of: d = {'a': 1, 'b': 2} print(d['c'])
None
0
Error
[]
Which method returns a list of key-value tuple pairs?
keys()
values()
items()
get()
How to safely access a key that may not exist in a dictionary?
dict['key']
dict.get('key')
dict.key
dict.fetch('key')
What is the output of len({'a': 1, 'b': 2, 'a': 3})?
3
2
1
Error
What does dict.update({'c': 3}) do?
Adds key 'c' with value 3
Replaces dictionary
Clears dictionary
Returns error
What will dict.pop('x') do if 'x' does not exist?
Returns None
Raises KeyError
Deletes key
Returns 0
How to loop over dictionary keys and values? for k, v in ___: ...
dict
dict.items()
dict.keys()
dict.values()
Can a dictionary key be a list?
Yes
No
Only if list is empty
Only in Python 3
What is the output of: d = dict([('a', 1), ('b', 2)]) print(d)
['a': 1, 'b': 2]
{('a', 1), ('b', 2)}
{'a': 1, 'b': 2}
Error
Which method removes all dictionary items?
del dict
dict.clear()
dict.remove_all()
dict.pop()
What is the result of: s = {1, 2, 3, 2} print(s)
{1, 2, 3, 2}
{1, 2, 3}
[1, 2, 3]
Error
What is the output of: a = {1, 2} b = {2, 3} print(a & b)
{1, 2, 3}
{2}
{1}
{}
Which operation returns elements not common to both sets?
a | b
a & b
a ^ b
a - b
How to check if an element exists in a set?
in
exists()
has()
include()
What is the result of: a = set("abc") a.add("d") print(a)
['a', 'b', 'c', 'd']
{'a', 'b', 'c', 'd'}
('a', 'b', 'c', 'd')
{a, b, c, d}
Which of the following is not allowed in a set?
Integer
Tuple
List
String
How to remove all items from a set?
set.remove_all()
set.clear()
set.delete()
del set[:]
Which method removes an item from a set if it exists?
discard()
remove()
pop()
delete()
Which method can throw a KeyError if the item is not found?
discard()
remove()
clear()
pop()
What does a - b do for sets a and b?
Intersection
Union
Difference
Symmetric difference
What will be the output of the following code? try: x = 5 / 0 except ZeroDivisionError: print("Division by zero")
Error
Division by zero
Zero
None
What is printed? try: int("hello") except ValueError: print("Caught ValueError")
hello
Caught ValueError
Error
None
Identify the output: try: x = [1, 2, 3] print(x[5]) except IndexError: print("Index error")
3
Error
Index error
None
What will be the result? try: print(10 / 2) except ZeroDivisionError: print("Can't divide") else: print("No error!")
5.0
5.0 No error!
Can't divide
No error!
Output of this code: try: raise ValueError("Test error") except ValueError as e: print(e)
ValueError
Test error
e
None
Result of the code? try: a = int("10a") except Exception: print("General error")
10a
General error
ValueError
None
What will this print? try: {}["key"] except KeyError: print("Key not found")
Error
Key not found
None
"key"
Choose the correct output: try: print("A") finally: print("B")
A
A B
B
Nothing
What gets printed? try: 1 / 0 except ZeroDivisionError: print("Zero division") finally: print("Cleanup")
Zero division
Cleanup
Zero division Cleanup
Error
What's the output? try: x = 10 finally: print("Always runs")
Always runs
Error
x = 10
None
Behavior of this code: try: raise KeyboardInterrupt except: print("Exception caught")
Exception caught
Nothing
Error
Interrupt
What gets printed? try: 1 / 1 except ZeroDivisionError: print("Divide by zero") else: print("Success") finally: print("Done")
Success Done
Divide by zero
Done
Error
What is the result? try: open("nofile.txt") except FileNotFoundError: print("File missing")
Error
File missing
FileNotFoundError
None
Output of the following: try: a = [1, 2, 3] print(a[3]) except Exception as e: print(type(e).__name__)
IndexError
Exception
NameError
ValueError
Result of this code? try: print("Try") raise Exception("Oops") print("After raise") except: print("Except")
Try After raise Except
Try Except
Oops
Error
Identify the output: try: 5 + "5" except TypeError: print("Cannot add int and str")
10
Error
Cannot add int and str
None
What will be printed? def div(a, b): try: return a / b except ZeroDivisionError: return "Error" print(div(10, 0))
10
0
Error
None
What is the result? try: print(undefined_var) except NameError: print("Undefined variable")
Error
Undefined variable
NameError
None
Output? try: pass except: print("Error") else: print("No error")
Error
No error
Nothing
Pass
What happens here? try: x = int("123") y = int("abc") except ValueError as ve: print("Caught:", ve)
Caught: invalid literal
Error
123
Caught: abc
What does the following code do? import tkinter as tk root = tk.Tk() label = tk.Label(root, text="Hello, World!") label.pack() root.mainloop()
Displays a label with text inside a window
Opens a text file
Creates a button
Closes a window
What is the purpose of mainloop() in Tkinter? root.mainloop()
Exits the application
Creates a widget
Starts the GUI event loop
Destroys the root window
What does the pack() method do? button.pack()
Destroys a widget
Adds a widget to the grid
Arranges a widget in the window
Changes a widget’s text
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()
Closes the system
Creates an exit dialog
Closes the window
Minimizes the window
Which geometry manager allows specifying row and column?
pack()
grid()
place()
align()
Which of the following correctly adds an entry widget? entry = tk.Entry(root) entry.pack()
Adds a dropdown
Adds a label
Adds a text box for input
Adds a button
How can you get the content of an Entry widget? entry.get()
entry.value()
entry.text()
entry.content()
entry.get()
What will this code do? label = tk.Label(root, text="Click Me") label.config(fg="blue") label.pack()
Display a red label
Make text bold
Change text color to blue
Set font size
What happens if you call pack() and grid() on the same widget?
Works fine
Raises a warning
Raises a TclError
Automatically chooses one
What does this snippet do? tk.Label(root, text="Name").grid(row=0, column=0) tk.Entry(root).grid(row=0, column=1)
Adds a dropdown
Adds a label only
Adds a label and input field side by side
Adds a label below input field
How do you set the window title in Tkinter? root.title("My App")
root.name("My App")
root.label("My App")
root.set_title("My App")
root.title("My App")
Which widget allows multiline text input?
Entry
Label
Text
StringVar
How to change the background color of a window? root.configure(bg="lightblue")
root.color("lightblue")
root.setBackground("lightblue")
root.background = "lightblue"
root.configure(bg="lightblue")
What does command=my_function mean in a button?
Runs the function immediately
Attaches the function to button click
Creates a new window
Changes button color
What is the default layout manager in Tkinter?
grid
pack
place
flex
Which method can position a widget at an absolute location?
grid()
pack()
place()
align()
How to bind a keypress to an event handler? root.bind("", on_enter)
root.set("", on_enter)
root.event("", on_enter)
root.bind("", on_enter)
root.attach("", on_enter)
How do you insert text into a Text widget? text.insert("1.0", "Hello!")
text.add("Hello!")
text.put("1.0", "Hello!")
text.insert("1.0", "Hello!")
text.set("Hello!")
What does this code create? from tkinter import messagebox messagebox.showinfo("Info", "Operation Complete")
A label
A warning box
A confirmation box
An informational pop-up
Which widget is used to group related widgets?
Label
Frame
Entry
Listbox
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()))
1
2
3
0
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")
Overwritten with "Python"
Contains only "Python"
Contains "Hello\nWorld\nPython"
Error
What does the with statement ensure in file handling?
File is opened in append mode
File is deleted after use
Automatic closing of file
File is locked
What happens if you read a file that does not exist? with open("nonexistent.txt", "r") as f: print(f.read())
Returns empty string
Creates the file
Raises FileNotFoundError
Raises IOError
Which mode opens a file for both reading and writing?
"w"
"r"
"a"
"r+"
What is the output? with open("file.txt", "w+") as f: f.write("12345") f.seek(0) print(f.read(2))
12345
12
345
1
What is the effect of seek(0)?
Closes the file
Resets file pointer to beginning
Moves to end of file
Deletes file contents
What does this code do? with open("file.txt", "w") as f: pass
Deletes the file
Creates an empty file
Appends text
Raises an error
Which method checks if file is closed?
isclosed()
closed()
f.closed
f.isclosed()
What will this print? with open("file.txt", "w") as f: f.write("test") print(f.closed)
False
True
Error
None
What does "a" mode do?
Replaces content
Adds to existing content
Only reads file
Deletes file
Which method reads all lines into a list?
readline()
readlines()
read()
readall()
Output? with open("test.txt", "w") as f: f.writelines(["A\n", "B\n"])
Writes string "writelines"
Writes "A" and "B" on separate lines
Error
Writes only A
What does this code do? f = open("log.txt", "x")
Appends if file exists
Overwrites file
Creates file, error if exists
Reads file
What will f.tell() return? with open("a.txt", "w") as f: f.write("abc") print(f.tell())
0
1
3
Error
Which function writes a string to file?
writefile()
writelines()
write()
put()
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)
Correct
Error
Needs readline()
Needs readlines()
What does f.flush() do?
Closes file
Writes buffer to disk
Reopens file
Deletes content
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()
"abc"
"a"
"b"
Error
What's the result? with open("data.txt", "w") as f: f.write("line1\nline2") with open("data.txt") as f: print(f.readline())
"line1"
"line1\n"
"line2"
Error
