Loading samples...
Loading samples...
py-sample-17
Mixed topics: Functions, OOP, File handling
Which defines a function?
What is self in class methods?
Which opens file for append?
What does json.loads() do?
Which catches all exceptions?
What is a decorator?
Which creates instance variable?
What does super() do?
Which module handles CSV?
What is __init__.py?
Explain *args and **kwargs with examples.
[3 marks]What is inheritance? Explain with example.
[3 marks]Explain try-except-else-finally blocks.
[3 marks]What is the difference between @staticmethod and @classmethod?
[3 marks]Explain file context manager and its benefits.
[3 marks]What is method overriding? When to use it?
[3 marks]Explain the difference between read() and readlines().
[3 marks]What is a lambda function? When is it useful?
[3 marks]Explain __str__ and __repr__ methods.
[3 marks]What is the purpose of if __name__ == '__main__':?
[3 marks]Write a decorator that logs function calls with arguments.
[5 marks]Create a Shape class with Circle and Rectangle subclasses.
[5 marks]Write a program to copy CSV file with data transformation.
[5 marks]Create a custom exception hierarchy for banking errors.
[5 marks]Write a recursive function with memoization for Fibonacci.
[5 marks]Create a config manager class that reads/writes JSON settings.
[5 marks]Predict output: class A: def __init__(self): self.x = 10 a = A() print(a.x)
[2 marks]Explanation:__init__ sets instance variable x to 10. Accessible via instance a.
Find error: def outer(): x = 5 def inner(): x += 1 inner() outer()
[3 marks]Explanation:Need 'nonlocal x' in inner() to modify outer's x. Otherwise Python thinks x is local.
Predict output: try: 1/0 except ZeroDivisionError: print('Zero') except Exception: print('General')
[2 marks]Explanation:Specific exception caught first. ZeroDivisionError is subclass of Exception but matches first.
Find error: with open('file.txt', 'w') as f: f.write('Hello') print(f.read())
[2 marks]Explanation:with statement closes file when block exits. Can't read from closed file outside with block.
Predict output: @decorator def func(): return 42 print(func())
[2 marks]Explanation:Decorator must be defined. If decorator returns wrapped function properly, prints 42 or decorated result.
Find error: import json data = {'date': datetime.now()} print(json.dumps(data))
[3 marks]Explanation:datetime not JSON serializable by default. Use custom encoder or convert to string first.
Predict output: class B(A): def __init__(self): super().__init__() self.y = 20 b = B() print(b.x, b.y)
[2 marks]Explanation:super().__init__() calls parent's __init__ setting x=10. Then y=20 set in B's __init__.
Find error: for i in range(5): if i == 3: break else: print('Done')
[2 marks]Explanation:for-else: else only executes if loop completed without break. break at i=3 prevents else execution.