0% found this document useful (0 votes)
32 views18 pages

CDFH

Uploaded by

mdajamansari099
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)
32 views18 pages

CDFH

Uploaded by

mdajamansari099
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/ 18

Basic Python Questions

Q1: What is Python?

○ Python is a high-level, interpreted, general-purpose programming


language known for its readability and versatility.

Q2: What are Python's key features?

○ Key features include simple syntax, dynamic typing, interpreted


execution, extensive standard library, and support for multiple
programming paradigms.

Q3: What is PEP 8?

○ PEP 8 is the Python Enhancement Proposal which provides guidelines


and best practices for writing clean and readable Python code.

Q4:What are lists and tuples?

○ Lists are mutable, ordered collections of items, while tuples are


immutable, ordered collections of items.

Q5: How do you declare a variable in Python?

○ Variables are declared by simply assigning a value to a name, for


example, x = 10.

Q6: What are Python's data types?


○ Common data types include int, float, str, list, tuple, dict, set, and bool.

Q7: What is a dictionary in Python?

○ A dictionary is a collection of key-value pairs, where keys are unique


and used to store and retrieve values.

Q8: What are list comprehensions?

○ List comprehensions provide a concise way to create lists by iterating


over sequences and optionally including conditionals, for example,
[x**2 for x in range(10)].

Q9:What is the difference between == and is?

○ == checks for value equality, while is checks for object identity.

Q10:What are functions in Python?

○ Functions are reusable blocks of code defined using the def keyword
and called by their name with arguments.

Q11:How do you handle exceptions in Python?

○ Using try, except, finally blocks to catch and handle exceptions.

Q12:What are lambda functions?

○ Lambda functions are anonymous, short functions defined with the


lambda keyword, for example, lambda x: x + 1.
Q13: **What are *args and kwargs?

○ *args is used to pass a variable number of positional arguments, and


**kwargs is used to pass a variable number of keyword arguments to
a function.

Q14: What is the difference between append() and extend() in lists?

○ append() adds a single element to the end of a list, while extend()


adds all elements from an iterable to the end of the list.

Q15: What are Python's built-in data structures?

○ Lists, tuples, sets, and dictionaries.

Q16: How do you read and write files in Python?

○ Using the open() function with modes like 'r', 'w', 'a', and 'b' for
binary files.

Q17: What is a module in Python?

○ A module is a file containing Python code that can be imported and


used in other Python scripts.

Q18: What is a package in Python?

○ A package is a collection of modules organized in directories, often


with an __init__.py file.
Q19: How do you import modules in Python?

○ Using the import statement, for example, import math or from


math import sqrt.

Q20: What is the Python Standard Library?

○ A collection of modules and packages included with Python, providing


a wide range of functionality.

Q21: What is a class in Python?

○ A class is a blueprint for creating objects, defined using the class


keyword.

Q22: What is inheritance in Python?

○ Inheritance allows a class to inherit attributes and methods from


another class, promoting code reuse.

Q23:What is polymorphism in Python?

○ Polymorphism allows methods to behave differently based on the


object calling them, often achieved through method overriding.

Q24: What is encapsulation in Python?

○ Encapsulation restricts access to an object's internal state, typically


using private variables and methods.
Q25: What is a decorator in Python?

○ A decorator is a function that modifies the behavior of another


function, typically using the @decorator_name syntax.

Q26: What are generators in Python?

○ Generators are iterators defined using a function with yield


statements, allowing iteration over large datasets efficiently.

Q27: What is a context manager in Python?

○ A context manager allows the setup and cleanup of resources using


the with statement, often used for file operations.

Q28: What is the Global Interpreter Lock (GIL)?

○ The GIL is a mutex that protects access to Python objects, ensuring


that only one thread executes Python bytecode at a time.

Q29: What is a virtual environment in Python?

○ A virtual environment is an isolated Python environment that allows


dependencies to be managed separately for different projects.

Q30: What is pip?

○ pip is the package installer for Python, used to install and manage
Python packages.
Intermediate Python Questions
Q1: What are list slicing and indexing?

○ Slicing allows you to access a portion of a list using


list[start:stop:step], while indexing retrieves individual
elements using list[index].

Q2: What are generators and iterators?

○ Generators are a type of iterator defined with yield and produce


items lazily. Iterators implement the iterator protocol with __iter__()
and __next__() methods.

Q3: What is the difference between deep copy and shallow copy?

○ Shallow copy creates a new object but inserts references into it to the
objects found in the original. Deep copy creates a new object and
recursively copies all objects found in the original.

Q4: How do you handle multiple exceptions in Python?

○ By specifying multiple exceptions in a tuple within an except block, for


example, except (TypeError, ValueError):.
Q5: What is a lambda function, and when would you use it?

○ A lambda function is an anonymous, short function defined with the


lambda keyword. It is used for creating small, throwaway functions.

Q6: How do you sort a list of dictionaries by a key?

○ Using the sorted() function with a lambda function as the key, for
example, sorted(list_of_dicts, key=lambda x: x['key']).

Q7: What is the purpose of the __init__.py file in a package?

○ __init__.py indicates that the directory it is in is a Python package


and can execute initialization code for the package.

Q8: What is monkey patching in Python?

○ Monkey patching refers to modifying or extending a module or class at


runtime.

Q9: How do you merge two dictionaries in Python?

○ Using the {**dict1, **dict2} syntax or the update() method.

Q10: What are *args and **kwargs used for?


○ *args is used to pass a variable number of positional arguments, and
**kwargs is used to pass a variable number of keyword arguments.

Q11: How do you implement a singleton pattern in Python?

○ By ensuring that a class has only one instance and providing a global
point of access to it, typically using the __new__ method or a
decorator.

Q12: What is method overloading and method overriding?

○ Method overloading is not directly supported in Python, but can be


mimicked by default arguments. Method overriding occurs when a
subclass provides a specific implementation for a method already
defined in its superclass.

Q13: What is the difference between staticmethod and classmethod?

○ staticmethod does not receive an implicit first argument and is


called on the class itself. classmethod receives the class as its first
argument.

Q14: What is the difference between __str__ and __repr__?

○ __str__ is used for creating a human-readable string representation


of an object, while __repr__ is used for creating an unambiguous
string representation for debugging.

Q15: What is a metaclass in Python?


○ A metaclass is a class of a class that defines how a class behaves. It
allows customization of class creation.

Q16: How do you work with JSON data in Python?

○ Using the json module to parse (json.loads()) and serialize


(json.dumps()) JSON data.

Q17: What is the purpose of the super() function?

○ super() is used to call a method from the parent class in the context
of the current class.

Q18: How do you create a virtual environment in Python?

○ Using the venv module with the command python -m venv myenv.

Q19: What is the difference between @staticmethod and


@classmethod?

○ @staticmethod does not take any additional parameters, while


@classmethod takes a class parameter cls.

Q20: What are docstrings in Python?


○ Docstrings are string literals that appear right after the definition of a
function, method, class, or module and are used to document the
object.

Q21: How do you perform unit testing in Python?

○ Using the unittest module to create test cases and run them.

Q22: What is the purpose of the yield keyword?

○ yield is used to define a generator, allowing a function to return an


iterator one value at a time.

Q23: What is a context manager?

○ A context manager allows setup and cleanup actions to be taken


around a block of code using the with statement.

Q24: What are magic methods in Python?

○ Special methods with double underscores at the beginning and end of


their names (e.g., __init__, __str__, __repr__) that allow
customization of class behavior.

Q25: What is a property in Python?


○ A property is a special kind of attribute that computes its value when
accessed, typically using the property decorator.

Q26: How do you handle missing data in pandas?

○ Using methods like dropna(), fillna(), and interpolation


techniques.

Q27: How do you perform element-wise operations on arrays in NumPy?

○ Using arithmetic operators directly on NumPy arrays, which perform


element-wise operations.

Q28: What is the difference between loc and iloc in pandas?

○ loc is used for label-based indexing, while iloc is used for position-
based indexing.

Q29:How do you merge DataFrames in pandas?

○ Using the merge() function or the concat() function for


concatenation.

Q30: How do you handle time series data in pandas?


○ Using the datetime module along with pandas' to_datetime(),
resample(), and time-based indexing capabilities.

Advanced Python Questions


Q1: What is a coroutine in Python?

○ A coroutine is a function that can pause and resume its execution using
await, enabling asynchronous programming.
Q2: What is the GIL, and how does it affect multithreading in Python?

○ The Global Interpreter Lock (GIL) allows only one thread to execute
Python bytecode at a time, affecting the performance of CPU-bound
multithreaded programs.

Q3: How do you optimize Python code for performance?

○ Using profiling tools, optimizing algorithms, leveraging built-in


functions, using efficient data structures, and utilizing libraries like
NumPy.

Q4: What is the purpose of the functools module?

○ The functools module provides higher-order functions that act on or


return other functions, such as partial, reduce, and lru_cache.

Q5: How do you use decorators to enforce function arguments types?

○ By creating a decorator that checks the types of the arguments and


raises exceptions if they don't match the expected types.

Q6: How do you implement a context manager without using with?

○ By defining __enter__() and __exit__() methods in a class and


explicitly calling them.

Q7: What is asyncio, and how is it used in Python?

○ asyncio is a library for writing asynchronous programs using


async/await syntax, enabling non-blocking I/O operations.
Q8: What is the purpose of the multiprocessing module?

○ The multiprocessing module allows parallel execution of code by


creating separate processes, bypassing the GIL limitations.

Q9: How do you handle memory leaks in Python?

○ By identifying and eliminating circular references, using weak


references, and using tools like gc and objgraph.

Q10: How do you use the subprocess module?

○ Using the subprocess module to spawn new processes, connect to


their input/output/error pipes, and obtain their return codes.

Q11: What are Python metaclasses, and how do you use them?

○ Metaclasses are the 'classes of classes' that define how classes


behave. They can be used to enforce class constraints, register
classes, or modify class creation.

Q12: How do you handle large data sets efficiently in pandas?

○ By using chunking, optimizing memory usage, and leveraging parallel


processing with Dask.
Q13: What is the purpose of the itertools module?

○ The itertools module provides a set of fast, memory-efficient tools


for working with iterators, including combinatoric generators.

Q14: How do you profile Python code?

○ Using the cProfile module or third-party libraries like


line_profiler to measure the performance of Python code.

Q15: What is a custom exception, and how do you create one?

○ A custom exception is a user-defined exception class that inherits from


the base Exception class. It is created by defining a new class and
optionally adding custom behavior.

Q16: How do you use pytest for testing in Python?

○ Using pytest to create test functions, assert conditions, and run tests
with the pytest command.

Q17: How do you implement memoization in Python?

○ By using the functools.lru_cache decorator or manually


implementing caching logic.
Q18: What is the difference between @staticmethod and
@classmethod decorators?

○ @staticmethod does not take any additional parameters, while


@classmethod takes a class parameter cls.

Q19: How do you implement a thread-safe singleton class in Python?

○ By using a metaclass or a decorator that ensures only one instance of


the class is created, with thread synchronization mechanisms like
locks.

Q20: How do you implement a priority queue in Python?

○ Using the heapq module to create and manage a heap-based priority


queue.

Q21: What are Python's memory management techniques?

○ Python uses reference counting, garbage collection, and memory


pools (via the pymalloc allocator).

Q22: How do you handle Unicode and string encoding in Python?

○ By using the str and bytes types for text and binary data,
respectively, and converting between them with encode() and
decode() methods.
Q23: What is the difference between deepcopy and copy?

○ copy creates a shallow copy, while deepcopy creates a deep copy,


recursively copying all objects.

Q24: How do you implement an Observer pattern in Python?

○ By creating a subject class with methods to attach, detach, and notify


observers, and observer classes with update methods.

Q25: How do you serialize and deserialize data in Python?

○ Using the pickle module for serializing Python objects and the json
module for serializing data to JSON format.

Q26: What is monkey patching, and when should you use it?

○ Monkey patching refers to modifying or extending a module or class at


runtime. It should be used cautiously, typically for debugging or quick
fixes.

Q27: How do you handle missing values in pandas?

○ Using methods like isna(), fillna(), dropna(), and interpolation


techniques to manage missing data.
Q28: What are broadcasting rules in NumPy?

○ Broadcasting rules allow NumPy to perform element-wise operations


on arrays of different shapes by automatically expanding their
dimensions.

Q29: How do you optimize pandas operations for large datasets?

○ By using vectorized operations, avoiding loops, using efficient data


types, and leveraging libraries like Dask for parallel processing.

Q30: What is the difference between map(), apply(), and applymap()


in pandas?

○ map() is used for element-wise transformations on Series, apply()


is used for applying functions along an axis of a DataFrame, and
applymap() is used for element-wise transformations on DataFrame.

You might also like