What is Python?
Python is an interpreted, high-level, general-purpose programming language known for its easy-to-read syntax and dynamic semantics. It supports object-oriented, procedural, and functional programming styles.
What are the key features of Python?
- Easy to learn and use
- Open-source and free
- Interpreted language
- High-level language
- Platform-independent
- Large standard library
- Supports GUI programming
- Extensible and embeddable
What are Python’s data types?
Python supports the following core data types:
- Numeric (int, float, complex)
- Sequence (list, tuple, range)
- Text (str)
- Set
- Dictionary
- Boolean
What is the difference between list and tuple in Python?
| Feature |
List |
Tuple |
| Mutability |
Mutable |
Immutable |
| Syntax |
[] |
() |
| Performance |
Slower |
Faster |
| Use case |
Frequent modifications |
Fixed data |
What are Python functions?
Functions are blocks of reusable code that perform a specific task. You can define a function using the def keyword in Python.
def greet():
print("Hello, World!")
What is indentation in Python?
Indentation refers to the spaces at the beginning of a code line. In Python, indentation is mandatory and is used to define the blocks of code, such as loops, functions, and conditionals.
How do you implement cross-domain tracking in Google Tag Manager?
Cross-domain tracking allows you to track user interactions across multiple domains as a single session in Google Analytics. To implement it in GTM, you need to set up cross-domain tracking settings in both your GTM container and Google Analytics account, ensuring that the tracking codes on all domains are properly configured.
What is the difference between break, continue, and pass?
- break: Exits the loop immediately
- continue: Skips the current iteration and moves to the next
- pass: Does nothing; used as a placeholder
How does a for loop work in Python?
A for loop is used to iterate over a sequence like a list, tuple, dictionary, set, or string.
for i in range(5):
print(i)
What is a class and object in Python?
- Class: A blueprint for creating objects.
- Object: An instance of a class.
class Person:
def __init__(self, name):
self.name = name
p = Person("John")
What is inheritance in Python?
Inheritance allows a class to inherit methods and properties from another class.
class Animal:
def sound(self):
print("Animal Sound")
class Dog(Animal):
pass
d = Dog()
d.sound() # Output: Animal Sound
Write a Python program to check if a number is even or odd.
num = int(input("Enter a number: "))
if num % 2 == 0:
print("Even")
else:
print("Odd")
What is the output of print(2**3)?
8 — The ** operator is used for exponentiation.
What is a generator and how is it different from a normal function?
- A generator is a function that uses yield instead of return to produce a value and suspend its state. When called, it returns a generator object (an iterator) without executing its body immediately.
- On each .__next__() or next() call, it resumes execution from the last yield and runs until next yield or return.
- Memory efficiency: Generators yield one item at a time and don’t build the entire list in memory (unlike functions that return a list).
- Use-case: iterating over large data or streams.
What are decorators in Python?
- A decorator is a function that takes another function (or method) and returns a new function (or wrapper) that adds some behavior before or after (or both) of the original function, without changing its code.
- Decorators are commonly applied with the @decorator_name syntax.
Explain context managers and with statement. How do you make your own context manager?
- A context manager in Python lets you allocate and release resources precisely (e.g. open/close files). It is used via the with statement.
- A class becomes a context manager by implementing __enter__() and __exit__() methods.
- Or you can use the contextlib module’s @contextmanager decorator to create a generator-based context manager.
What is the Global Interpreter Lock (GIL) in Python? Does it affect multi-threading?
- The Global Interpreter Lock (GIL) is a mutex in CPython that allows only one thread to execute Python bytecode at once per process.
- This means that CPU-bound Python threads do not run in true parallelism (only one thread executes at a time), which limits performance gains from multi-threading for CPU-intensive tasks.
- However, for I/O-bound tasks (disk, network, etc.), threads can yield during I/O and so you can get concurrency, because while one thread waits for I/O, another can run.
- Alternatives: for CPU-bound tasks, use multiprocessing (separate processes, separate GIL). Or use Python implementations without GIL (e.g. Jython, IronPython), or C extensions, or combine with asynchronous programming.
What are metaclasses in Python? Can you give a use-case?
- A metaclass in Python is the “class of a class” — i.e., a class whose instances are classes. Metaclasses define how classes behave.
- The default metaclass is type, so normally class A: ... is equivalent to A = type('A', (BaseClasses,), dict_of_attributes).
- You can define a custom metaclass by inheriting from type and overriding methods like __new__ or __init__.
How does method resolution order (MRO) work in Python, especially in multiple inheritance?
- MRO is the order in which base classes are searched when looking for a method.
- Python uses the C3 linearization algorithm (also called “C3 superclass linearization”) to compute MRO, ensuring monotonicity and consistent order.
- You can inspect MRO of a class via ClassName.__mro__ or ClassName.mro().
- In multiple inheritance, the method is resolved by following the MRO order, not strictly left-to-right or right-to-left.
What is the difference between shallow copy and deep copy? How do you perform them?
- Shallow copy: creates a new object, but does not recursively copy inner objects; it just references them.
- Deep copy: creates a new object and recursively copies all inner objects, so no shared references.
What is monkey patching? Can you demonstrate an example?
- Monkey patching is the act of dynamically modifying or extending a module or class at runtime (i.e. after it has been defined).
- It allows you to change functions or methods on the fly, e.g. for testing, debugging, or fixing bugs without altering source.
Explain descriptor protocol in Python. How is it used (e.g. for properties)?
- A descriptor is an object attribute with “binding behavior” — i.e. it defines one or more of the methods: __get__, __set__, __delete__.
- When a descriptor is accessed as an attribute of another class, these methods are called.
- Built-in property is implemented via descriptors.
What are slots in Python classes? When would you use them?
- __slots__ is a class variable you can define as a tuple (or list) of attribute names that restrict which attributes instances can have.
- By using __slots__, Python avoids creating a __dict__ for each instance (if no dynamic attributes needed), thus saving memory.
- It can also speed up attribute access somewhat.
- Downside: you lose flexibility to add arbitrary new attributes, and you cannot use __slots__ in classes that need __dict__ or __weakref__ unless explicitly included.
What is the difference between @staticmethod, @classmethod, and a regular instance method in Python?
In Python, methods inside a class can be of three main types:
| Method Type |
First Argument |
Can Access Instance (self)? |
Can Access Class (cls)? |
Decorator Used |
| Instance Method |
self |
Yes |
Yes |
None |
| Class Method |
cls |
No |
Yes |
@classmethod |
| Static Method |
None |
No |
No |
@staticmethod |
What is the purpose of the __init__.py file in Python packages?
- The __init__.py file tells Python that the directory it’s in should be treated as a package.
- It can be empty or include initialization code for the package.
- It also controls what is imported when using from package import *.
What is the difference between is and == operators?
- == compares the values of two objects.
- is compares the identities (whether both refer to the same memory object).
What are docstrings in Python? How do you access them?
- Docstrings are special strings written just below a function, class, or module definition used for documentation.
- Defined using triple quotes """ ... """.
- You can access them via the .__doc__ attribute or the built-in help() function.
What is duck typing in Python?
- Python uses duck typing, meaning that it doesn’t care about the object’s type as long as it behaves like the expected one.
- “If it walks like a duck and quacks like a duck, it’s a duck.”
What is the difference between deep copy and assignment (=)?
- Using = doesn’t copy the object — it just creates a new reference to the same object.
- Changes made to one will affect the other.
- A deep copy (copy.deepcopy()) creates a completely new object with its own independent data.
What is the difference between @property and getter/setter methods?
- @property allows you to use methods like attributes, promoting cleaner syntax.
- It helps in encapsulation and data validation.
What is pickling and unpickling in Python?
- Pickling means serializing a Python object into a byte stream using the pickle module.
- Unpickling means deserializing it back into a Python object.
- Commonly used for saving and loading Python data structures.
What are lambda functions and when should you use them?
- A lambda function is a small anonymous function defined with the keyword lambda.
- It can have any number of arguments but only one expression.
- Commonly used with functions like map(), filter(), and sorted().
What is the purpose of the if __name__ == "__main__": statement?
It ensures that code inside this block runs only when the file is executed directly, not when imported as a module.
What is the difference between @staticmethod and @classmethod?
- @staticmethod doesn’t take self or cls arguments. It’s just a utility method that belongs to a class.
- @classmethod takes cls as the first argument and can modify class variables.
- Practice writing code regularly.
- Understand core concepts like data types, control flow, and OOP.
- Work on mini projects to improve your coding confidence.
- Revise your Python basics before interviews.
If you are looking for other courses checkout here -
Data Analytics Training |
HR Training |
SEO Training