0% found this document useful (0 votes)
19 views

Python & OOP's Interview Questions

The document provides a comprehensive overview of Python programming, covering its key features, data types, control flow statements, functions, object-oriented programming principles, file handling, exception handling, modules, and libraries like NumPy and Pandas. It also explains advanced concepts such as decorators, generators, and memory management. Overall, it serves as a detailed reference for Python programming concepts and practices.
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)
19 views

Python & OOP's Interview Questions

The document provides a comprehensive overview of Python programming, covering its key features, data types, control flow statements, functions, object-oriented programming principles, file handling, exception handling, modules, and libraries like NumPy and Pandas. It also explains advanced concepts such as decorators, generators, and memory management. Overall, it serves as a detailed reference for Python programming concepts and practices.
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/ 21

1. What is Python?

o Python is a high-level, interpreted, general-purpose programming language


known for its readability and simplicity. It's dynamically typed and supports
multiple programming paradigms.

2. What are the key features of Python?

o Easy to learn and read

o Interpreted and dynamically typed

o Extensive standard library

o Object-oriented

o Portable and open-source

o Supports modules and packages

3. What are Python's key data types?

o int, float, str, bool, list, tuple, set, dict, NoneType

4. What is the difference between a list and a tuple?

o List is mutable, while tuple is immutable.

5. What is the difference between is and ==?

o is compares object identity, == compares values.

6. What are Python’s numeric data types?

o int, float, complex

7. What is type casting in Python?

o Converting one data type to another using functions like int(), float(), str()
8. How do you check the type of a variable?

o Using type(variable)

9. What are Python’s built-in data structures?

o list, tuple, set, dict

10. What is the use of None in Python?

o Represents the absence of a value, similar to null in other languages.

11. What are the control flow statements in Python?

o if, elif, else

12. What are the looping constructs in Python?

o for loop and while loop

13. How do you iterate over a list?

14. for item in my_list:

15. print(item)

16. What is range() in Python?

o Returns an immutable sequence of numbers for looping.

17. What does break do in Python?

o Exits the loop immediately.

18. What does continue do in Python?

o Skips the current iteration and moves to the next.

19. What is the use of pass?

o A null operation; used as a placeholder.

20. What is a list comprehension?

o A concise way to create lists:

o [x**2 for x in range(5)]

21. Can you use else with loops?


o Yes, it runs if the loop doesn't encounter a break.

22. What is the difference between for and while loop?

o for is used for definite iteration, while for indefinite.

21. How do you define a function in Python?

22. def my_func():

23. pass

24. What is a return statement?

o Used to return a value from a function.

25. What is the difference between return and print?

o return gives back a value to the caller; print outputs to the console.

26. **What are *args and kwargs?

o *args for variable-length positional arguments; **kwargs for variable-length


keyword arguments.

27. What is recursion?

o A function calling itself to solve smaller instances of the problem.

28. What is the scope of a variable?

o The area in the code where a variable is accessible: local, enclosing, global, or
built-in.

29. What is a lambda function?

o Anonymous function:

o lambda x: x * 2

30. What is a docstring?

o Documentation string used to describe a function/class/module.

31. What is the difference between global and local variables?

o Global is defined outside functions; local is inside a function.

32. How can you modify a global variable inside a function?


o Using the global keyword.

31. What is Object-Oriented Programming in Python?

• A programming paradigm where code is organized into objects that combine data
and behavior.

32. What are classes and objects?

• A class is a blueprint; an object is an instance of a class.

33. How do you create a class in Python?

class Dog:

def __init__(self, name):

self.name = name

34. What is the __init__ method?

• A special method called when an object is created; like a constructor.

35. What is self in Python classes?

• Refers to the instance of the object itself.

36. What is inheritance in Python?

• Allows one class to inherit attributes and methods from another:

• class Dog(Animal):

• pass

37. What is method overriding?

• Providing a new implementation of a method in a derived class.

38. What is polymorphism?

• The ability to use a single interface for different types (e.g., function overloading).

39. What is encapsulation?

• Bundling data and methods together and restricting access using private members (_
or __).
40. What is the difference between @classmethod, @staticmethod, and instance
methods?

• @staticmethod: Doesn’t access class or instance.

• @classmethod: Accesses class (cls).

• Instance method: Accesses object (self).

41. How do you open a file in Python?

with open('file.txt', 'r') as f:

data = f.read()

42. What are the different file modes in Python?

• 'r', 'w', 'a', 'rb', 'wb', 'r+', etc.

43. How to read a file line by line?

for line in open('file.txt'):

print(line)

44. What is the difference between read(), readline(), and readlines()?

• read(): Whole file

• readline(): One line

• readlines(): List of all lines

45. How to write to a file?

with open('file.txt', 'w') as f:

f.write("Hello")

46. What is the with statement in file handling?

• Ensures automatic file closing (context manager).

47. What happens if you try to read a closed file?

• It raises a ValueError.

48. How do you handle file not found errors?


try:

open('nofile.txt')

except FileNotFoundError:

print("Not found")

49. What is binary mode in file handling?

• Used for reading or writing binary files like images.

50. How to check if a file exists?

import os

os.path.exists('file.txt')

51. What is exception handling in Python?

• Mechanism to handle runtime errors using try, except, finally.

52. How do you catch exceptions in Python?

try:

risky_code()

except ValueError:

print("Caught error")

53. What is the purpose of the finally block?

• Executes code no matter what (error or no error).

54. What are some common Python exceptions?

• ZeroDivisionError, TypeError, ValueError, KeyError, IndexError, etc.

55. How to raise an exception manually?

raise ValueError("Custom error")

56. What is the assert statement?

• Used for debugging to test if a condition is true.

57. What is the difference between syntax error and exception?


• Syntax error: Detected during parsing

• Exception: Detected during execution

58. Can you catch multiple exceptions in one block?

except (TypeError, ValueError):

pass

59. How to define custom exceptions?

class MyError(Exception):

pass

60. How does exception propagation work in Python?

• If an exception isn’t handled, it moves up the call stack.

61. What is a module in Python?

• A file containing Python definitions and code (.py).

62. What is a package in Python?

• A directory with __init__.py that contains multiple modules.

63. How to import a module?

import math

from math import sqrt

64. What is __name__ == "__main__" used for?

• Checks if the script is being run directly or imported.

65. How to install external packages?

pip install package-name

66. What is the Python Standard Library?

• Built-in modules like math, datetime, os, sys, json, etc.

67. What is dir() function used for?

• Lists attributes and methods of an object/module.


68. How to get help about a module/function?

help(math)

69. What are relative and absolute imports?

• Relative: from . import module

• Absolute: import package.module

70. What is the role of __init__.py?

• Marks a directory as a Python package.

71. What is a decorator in Python?

• A function that takes another function and extends its behavior without modifying it:

def decorator(func):

def wrapper():

print("Before")

func()

print("After")

return wrapper

72. What are *args and **kwargs used for?

• *args: allows variable number of positional arguments

• **kwargs: allows variable number of keyword arguments

73. What is a generator in Python?

• A function that uses yield to return an iterator, producing items lazily:

def gen():

yield 1

yield 2

74. What is the difference between yield and return?


• return ends the function; yield pauses and resumes it.

75. What are iterators and iterables?

• Iterable: an object you can loop over (e.g., list)

• Iterator: object with __next__() and __iter__() methods.

76. What is a context manager in Python?

• An object that manages a resource using with:

with open('file.txt') as f:

data = f.read()

77. What are magic methods (dunder methods)?

• Special methods with __ prefix/suffix, like __init__, __str__, __len__

78. What is the use of __str__ and __repr__?

• __str__: user-friendly string

• __repr__: developer-friendly representation

79. What is monkey patching?

• Dynamically changing a class or module at runtime.

80. What is metaclass in Python?

• A class of a class; it defines how a class behaves.

81. How is memory managed in Python?

• Through reference counting and garbage collection.

82. What is the difference between deep copy and shallow copy?

• Shallow: references objects

• Deep: recursively copies all nested objects

83. How do you create a shallow copy?

import copy

shallow = copy.copy(obj)
84. How do you create a deep copy?

import copy

deep = copy.deepcopy(obj)

85. What is the Global Interpreter Lock (GIL)?

• A mutex that prevents multiple native threads from executing Python bytecodes
simultaneously.

86. How do you profile performance in Python?

• Using cProfile, timeit, or line_profiler.

87. What are some ways to improve Python performance?

• Use built-in functions, list comprehensions, avoid unnecessary loops, and use NumPy.

88. What are memory leaks in Python and how to avoid them?

• Caused by objects referencing each other cyclically. Use weak references or cleanup.

89. What is the use of gc module?

• Garbage collection for detecting and cleaning up cycles.

90. What is the difference between multiprocessing and multithreading?

• Multiprocessing: parallel execution using multiple CPU cores

• Multithreading: concurrent execution with threads (limited by GIL)

91. What is NumPy?

• A library for numerical computing with support for arrays, matrices, and linear
algebra.

92. How do you create a NumPy array?

import numpy as np

arr = np.array([1, 2, 3])

93. How do you perform element-wise operations in NumPy?

arr * 2 # Multiplies each element by 2

94. What is the difference between Python list and NumPy array?
• NumPy arrays are faster, support vectorized operations, and are more memory-
efficient.

95. What is Pandas in Python?

• A data manipulation library offering DataFrames for structured data.

96. How do you create a DataFrame in Pandas?

import pandas as pd

df = pd.DataFrame({'name': ['A', 'B'], 'age': [25, 30]})

97. How do you read a CSV file in Pandas?

df = pd.read_csv('data.csv')

98. What is the difference between loc[] and iloc[]?

• loc[]: label-based indexing

• iloc[]: integer-location based indexing

99. How do you handle missing values in Pandas?

df.fillna(0) # Replace with 0

df.dropna() # Remove rows with NaN

100. What is vectorization in NumPy/Pandas and why is it useful?

• Replacing loops with array operations for faster execution using low-level
optimizations.
1. What is Object-Oriented Programming?
A paradigm based on the concept of "objects", which contain data (attributes) and
behavior (methods).

2. What are the main principles of OOP?

o Encapsulation

o Abstraction

o Inheritance

o Polymorphism

3. What is a class in Python?


A class is a blueprint for creating objects.

4. What is an object in Python?


An instance of a class.

5. How do you define a class?

6. class Car:

7. def __init__(self, brand):

8. self.brand = brand

9. What is the __init__ method?


A constructor called when an object is instantiated.

10. What is self in Python?


Refers to the current instance of the class.

11. Can a class have multiple constructors in Python?


Python doesn't support method overloading; use default arguments or class
methods.

12. What is encapsulation?


Hiding internal state and requiring all interaction to be performed through methods.

13. How is encapsulation achieved in Python?


Using private variables: prefix with _ (protected) or __ (private).

11. What is inheritance?


One class (child) inherits attributes and methods from another (parent).
12. How do you inherit a class in Python?

class Dog(Animal):

pass

13. What types of inheritance does Python support?

• Single

• Multiple

• Multilevel

• Hierarchical

• Hybrid

14. What is super() in Python?


Calls the parent class's methods.

15. Can you override methods in Python?


Yes, simply redefine them in the subclass.

16. What is method resolution order (MRO)?


The order in which base classes are searched. Use Class.__mro__.

17. What is isinstance() used for?


Checks if an object is an instance of a class.

18. What is issubclass() used for?


Checks if a class is a subclass of another.

19. What is multilevel inheritance?


A -> B -> C (C inherits B, B inherits A)

20. What is multiple inheritance?


A class inherits from more than one class.

What is polymorphism?
The ability to use a shared interface for different data types.

21. What is method overloading?


Python does not support it directly; use default arguments.
22. What is method overriding?
Redefining a parent method in the child class.

23. How is polymorphism implemented in Python?


Using duck typing: "If it walks like a duck and quacks like a duck..."

24. Example of polymorphism:

class Cat:

def sound(self): return "Meow"

class Dog:

def sound(self): return "Woof"

def make_sound(animal):

print(animal.sound())

26. What is abstraction in OOP?


Hiding complex implementation and showing only the necessary features.

27. How is abstraction implemented in Python?


Using abstract base classes with the abc module.

28. What is an abstract class? A class with at least one abstract method that must be
implemented by its subclasses.

29. How do you define an abstract class?

from abc import ABC, abstractmethod

class Shape(ABC):

@abstractmethod

def area(self):

pass
30. What is the benefit of abstraction?
Improves code modularity and reusability, reduces complexity.

31. Can you instantiate an abstract class?


No, you must inherit and implement abstract methods first.

32. Can abstract classes have constructors?


Yes, they can have constructors and regular methods.

33. What is the difference between abstraction and encapsulation?

• Encapsulation: Hides data

• Abstraction: Hides implementation logic

34. What is an interface in Python?


Python doesn't have interfaces; abstract base classes are used instead.

35. Why are abstract methods used?


To enforce implementation in subclasses.

36. What are public, protected, and private members in Python?

• x: public

• _x: protected

• __x: private

37. How do you access private variables in Python?

obj._ClassName__var

38. What is name mangling in Python?


Changes the name of private attributes internally to avoid conflict.

39. What are getter and setter methods?


Used to read (get) or modify (set) private variables.

40. How to create properties using @property?

class Person:

@property

def age(self):
return self._age

41. How do you prevent access to a class variable?


Declare it private (__variable).

42. What is the use of __slots__?


Limits the attributes of a class to save memory.

43. Can you use encapsulation to hide methods?


Yes, use private methods with __methodname().

44. Why use encapsulation?

• Protects data

• Reduces complexity

• Increases modularity

45. How is encapsulation broken in Python?


By accessing private variables through name mangling.

46. What is a class method? A method that operates on the class itself, not instances.

47. How do you define a class method?

@classmethod

def my_class_method(cls):

pass

48. What is a static method? A method that does not access self or cls.

49. How is a static method declared?

@staticmethod

def my_static_method():

pass

50. Difference between classmethod and staticmethod?

• classmethod: accesses class

• staticmethod: no access to class or instance


51. Why use static methods?
For utility functions related to the class but not needing access to it.

52. Can you call a static method with an instance?


Yes, but it doesn't receive the instance as a parameter.

53. Can class methods be overridden?


Yes, like any regular method.

54. Use case for class method?


Factory methods to create instances with predefined settings.

55. What happens if you call a static method without @staticmethod?


Python passes self as the first argument and throws an error.

56. What are dunder methods?


Special methods with double underscores (e.g., __init__, __str__).

57. What is operator overloading?


Changing the behavior of operators for user-defined classes.

58. How do you overload the + operator?

def __add__(self, other):

return self.value + other.value

59. What is __str__ vs __repr__?

• __str__: readable output

• __repr__: unambiguous debug output

60. What is the use of __eq__?


Defines custom behavior for the == operator.

61. What is __len__ used for?


Defines the behavior of the built-in len().

62. What is __call__ method?


Allows instances to be called like functions.

63. What is the __del__ method?


Destructor called when an object is deleted.
64. What is __contains__ used for?
Implements behavior for in keyword.

65. Can you overload comparison operators?


Yes: __lt__, __le__, __gt__, __ge__, __eq__, __ne__

66. What is duck typing in Python?


Type is determined by behavior: "If it walks like a duck..."

67. What is composition in OOP?


A "has-a" relationship where a class contains objects of other classes.

68. What is aggregation?


A weaker form of composition where the contained object can exist independently.

69. What is association in OOP?


A relationship between two independent classes.

70. Difference between association, aggregation, and composition?

• Association: loosely connected

• Aggregation: has reference

• Composition: strong containment

71. What is a mixin class?


A small class with reusable methods to be used with other classes via multiple
inheritance.

72. What is the SOLID principle?

• Single Responsibility

• Open/Closed

• Liskov Substitution

• Interface Segregation

• Dependency Inversion

73. What is Liskov Substitution Principle?


Subclasses should be substitutable for their base classes.
74. What is the Open/Closed Principle?
Software entities should be open for extension, closed for modification.

75. What is dependency injection?


Passing dependencies as parameters rather than hard-coding them.

76. What are design patterns?


Proven solutions to common software design problems (e.g., Singleton, Factory).

77. What is the Singleton pattern?


Ensures a class has only one instance and provides a global access point.

class Singleton:

_instance = None

def __new__(cls):

if not cls._instance:

cls._instance = super().__new__(cls)

return cls._instance

78. What is the Factory Method pattern?


Defines an interface for creating objects but lets subclasses decide which class to
instantiate.

79. What is the difference between a factory and an abstract factory?

• Factory: produces one type of object

• Abstract factory: produces families of related objects

80. What is the Builder pattern?


Separates construction of complex objects from their representation.

81. What is the Observer pattern?


One-to-many dependency between objects so that one change updates all others.

82. What is the Strategy pattern?


Enables selecting an algorithm's behavior at runtime.
83. Why use design patterns in OOP?
They improve code maintainability, flexibility, and readability.

84. What is tight coupling?


When classes are highly dependent on one another — it's bad for flexibility.

85. What is loose coupling?


When classes are independent or use abstraction — preferred in OOP.

86. How would you model a library management system in OOP?


Classes: Book, Member, Librarian, Transaction, Library using composition and
inheritance.

87. How would you represent a car rental system?


Classes: Car, Customer, Rental, Invoice, Fleet

88. What is object composition?


Building complex objects using other objects (e.g., Car has Engine).

89. Why prefer composition over inheritance?


Composition provides more flexibility and less coupling than inheritance.

90. What is a metaclass in Python?


A class for classes. Defines how classes behave. Default is type.

91. How do you define a metaclass?

class MyMeta(type):

def __new__(cls, name, bases, dct):

return super().__new__(cls, name, bases, dct)

92. When do you use metaclasses?


When you want to control class creation (e.g., enforcing coding conventions).

93. Can Python classes be created dynamically?


Yes, using type() or metaclasses.

94. What is monkey patching in Python?


Dynamically modifying a class or module at runtime.

95. Is Python fully OOP?


Yes, everything in Python is an object, including classes and functions.
96. Is OOP slower than procedural programming?
Yes, slightly due to abstraction layers, but it's more maintainable.

97. How does garbage collection work in Python?


Python uses reference counting and cyclic garbage collection to reclaim memory.

98. What is the difference between shallow copy and deep copy in OOP?

• Shallow: copies object references

• Deep: copies entire object graph

import copy

shallow = copy.copy(obj)

deep = copy.deepcopy(obj)

99. What is a memory leak in Python OOP?


When objects are not garbage collected due to reference cycles or poor design.

100. How to make classes more memory efficient?


Use __slots__ to prevent creation of __dict__ for each object:

class Point:

__slots__ = ['x', 'y']

You might also like