Basic Python interview questions - Set 1 - 55 Questions and Answers
What is Python?
- Python is a high-level, interpreted programming language known for its simplicity and readability. It supports multiple programming paradigms, including procedural, object-oriented, and functional programming.
What are the key features of Python?
- Some key features of Python include:
- Easy-to-read syntax
- Dynamic typing
- Automatic memory management (garbage collection)
- Extensive standard library
- Cross-platform compatibility
- Some key features of Python include:
What are the differences between Python 2 and Python 3?
- Python 3 is the latest version of the language and has several improvements over Python 2, including:
- Print function: In Python 3,
print
is a function whereas in Python 2, it's a statement. - Unicode: Python 3 handles strings as Unicode by default, while Python 2 treats strings as ASCII by default.
- Division: In Python 3, division of integers produces floating-point results by default, while in Python 2, it produces integer results (unless
from __future__ import division
is used). - Various library changes and improvements.
- Print function: In Python 3,
- Python 3 is the latest version of the language and has several improvements over Python 2, including:
What are decorators in Python?
- Decorators are a powerful feature in Python that allow you to dynamically modify the behavior of functions or methods at runtime. They are implemented using the
@decorator_name
syntax.
- Decorators are a powerful feature in Python that allow you to dynamically modify the behavior of functions or methods at runtime. They are implemented using the
Explain the difference between a list and a tuple in Python.
- Lists are mutable, meaning their elements can be changed after creation, while tuples are immutable, meaning their elements cannot be changed after creation.
- Lists are defined using square brackets
[]
, while tuples are defined using parentheses()
.
What is a generator in Python?
- A generator in Python is a special type of iterator that generates values on-the-fly using the
yield
keyword. Generators are memory-efficient and are commonly used for generating large sequences of values.
- A generator in Python is a special type of iterator that generates values on-the-fly using the
Explain the difference between
__str__
and__repr__
in Python.__str__
is called by thestr()
function and is intended to return a string representation of the object for end-users.__repr__
is called by therepr()
function and is intended to return an unambiguous string representation of the object for developers.
What is the purpose of
if __name__ == "__main__":
in Python scripts?- This conditional statement checks whether the Python script is being run as the main program or if it is being imported as a module. It allows you to write code that will only be executed when the script is run directly, not when it's imported as a module.
How do you handle exceptions in Python?
- Exceptions in Python are handled using
try
,except
,finally
blocks. Code that may raise an exception is placed inside thetry
block, and exception handling code is placed inside theexcept
block. Thefinally
block is used for code that should be executed regardless of whether an exception occurred or not.
- Exceptions in Python are handled using
What are some common built-in data types in Python?
- Some common built-in data types in Python include:
- Integers (
int
) - Floating-point numbers (
float
) - Strings (
str
) - Lists (
list
) - Tuples (
tuple
) - Dictionaries (
dict
) - Sets (
set
) - Boolean (
bool
) What is PEP 8?
- PEP 8 is the style guide for Python code, outlining coding conventions and recommendations for writing clean, readable code.
Explain the difference between
==
andis
operators in Python.- The
==
operator checks for equality of values, while theis
operator checks for identity, i.e., whether two variables refer to the same object in memory.
- The
What is a lambda function in Python?
- A lambda function, also known as an anonymous function, is a small, anonymous function defined using the
lambda
keyword. It can take any number of arguments, but can only have one expression.
- A lambda function, also known as an anonymous function, is a small, anonymous function defined using the
What are the advantages of using Python for web development?
- Python's simplicity, readability, and extensive libraries make it well-suited for web development. Frameworks like Django and Flask provide tools for building scalable and maintainable web applications.
How do you handle file I/O in Python?
- File I/O in Python is handled using the
open()
function to open files, and methods likeread()
,write()
,close()
, etc., to read from or write to files.
- File I/O in Python is handled using the
What is the purpose of the
__init__
method in Python classes?- The
__init__
method is a special method in Python classes used for initializing new objects. It is called when an instance of the class is created.
- The
Explain the difference between
append()
andextend()
methods in Python lists.- The
append()
method adds a single element to the end of a list, while theextend()
method adds all the elements of an iterable (such as another list) to the end of the list.
- The
How do you iterate over a dictionary in Python?
- You can iterate over a dictionary using a
for
loop, accessing keys, values, or key-value pairs using methods likekeys()
,values()
, anditems()
.
- You can iterate over a dictionary using a
What are list comprehensions in Python?
- List comprehensions provide a concise way to create lists in Python by applying an expression to each item in an iterable.
Explain the difference between shallow copy and deep copy in Python.
- A shallow copy creates a new object but inserts references to the original elements into it. A deep copy creates a new object and recursively inserts copies of the original elements into it.
What are decorators used for in Python?
- Decorators are used to modify the behavior of functions or methods without changing their code. They are often used for aspects such as logging, authentication, or caching.
What is the purpose of the
global
keyword in Python?- The
global
keyword is used inside a function to declare that a variable inside the function should refer to the globally scoped variable with the same name.
- The
How do you handle multiple exceptions in Python?
- Multiple exceptions in Python can be handled using multiple
except
blocks, a singleexcept
block with a tuple of exception types, or a catch-allexcept
block.
- Multiple exceptions in Python can be handled using multiple
What is the purpose of the
__doc__
attribute in Python?- The
__doc__
attribute is used to access the docstring of a Python object, which provides documentation about the object's purpose and usage.
- The
How do you create a virtual environment in Python?
- You can create a virtual environment in Python using the
venv
module, which is included in the Python standard library since version 3.3.
- You can create a virtual environment in Python using the
What is monkey patching in Python?
- Monkey patching is the practice of dynamically modifying or extending code at runtime. It's often used for adding or modifying behavior in third-party libraries or frameworks.
What is the purpose of the
__name__
variable in Python?- The
__name__
variable is a special variable in Python that contains the name of the current module. When a Python script is run as the main program, its__name__
variable is set to'__main__'
.
- The
Explain the difference between
__getitem__
and__iter__
methods in Python.__getitem__
is a method used to implement indexing in Python objects, allowing them to be accessed using square brackets[]
.__iter__
is a method used to make an object iterable, allowing it to be used in afor
loop.
What is the purpose of the
super()
function in Python?- The
super()
function is used to call methods and constructors of the parent class from a subclass. It's commonly used to initialize parent class attributes in the subclass constructor.
- The
What is a metaclass in Python?
- A metaclass is a class whose instances are classes themselves. Metaclasses are used to define the behavior of classes, such as how they are constructed or how their methods are inherited.
What is the GIL (Global Interpreter Lock) in Python?
- The GIL is a mutex that protects access to Python objects, preventing multiple native threads from executing Python bytecode simultaneously. This can limit the parallelism of Python programs, particularly CPU-bound ones.
How do you sort a dictionary by value in Python?
- Dictionaries in Python are inherently unordered, but you can sort them by value using the
sorted()
function along with a custom sorting key.
- Dictionaries in Python are inherently unordered, but you can sort them by value using the
Explain the difference between shallow copy and deep copy in Python.
- A shallow copy creates a new object but inserts references to the original elements into it. A deep copy creates a new object and recursively inserts copies of the original elements into it.
What is a context manager in Python?
- A context manager in Python is an object that is used to manage resources, such as files or database connections, in a way that ensures they are properly released when they are no longer needed. Context managers are implemented using the
with
statement.
- A context manager in Python is an object that is used to manage resources, such as files or database connections, in a way that ensures they are properly released when they are no longer needed. Context managers are implemented using the
What is the purpose of the
__slots__
attribute in Python?- The
__slots__
attribute is used to explicitly declare the attributes of a class, preventing the creation of dynamic attributes. This can reduce memory usage and improve performance for classes with a fixed set of attributes.
- The
How do you handle missing values in pandas?
- Missing values in pandas are typically represented as
NaN
(Not a Number) orNone
. You can handle missing values using methods likedropna()
,fillna()
, orisnull()
.
- Missing values in pandas are typically represented as
What is the purpose of the
__call__
method in Python?- The
__call__
method allows an object to be called as if it were a function. It's commonly used to implement callable objects, such as function-like classes or decorators.
- The
What are the differences between a list and a tuple in Python?
- Lists are mutable, meaning their elements can be changed after creation, while tuples are immutable, meaning their elements cannot be changed after creation. Lists are defined using square brackets
[]
, while tuples are defined using parentheses()
.
- Lists are mutable, meaning their elements can be changed after creation, while tuples are immutable, meaning their elements cannot be changed after creation. Lists are defined using square brackets
What are the advantages of using generators in Python?
- Generators in Python are memory-efficient and allow for lazy evaluation, meaning they generate values on-the-fly rather than storing them in memory. This can be useful for processing large datasets or infinite sequences.
How do you handle regular expressions in Python?
- Regular expressions in Python are handled using the
re
module, which provides functions for pattern matching, searching, and substitution.
- Regular expressions in Python are handled using the
What is the purpose of the
@staticmethod
decorator in Python?- The
@staticmethod
decorator is used to define a static method in a class. Static methods do not have access to the instance (self
) or class (cls
) variables and are primarily used for utility functions that do not depend on instance state.
- The
What is the purpose of the
@property
decorator in Python?- The
@property
decorator is used to define a property in a class that behaves like an attribute but allows for custom getter, setter, and deleter methods.
- The
What are docstrings in Python?
- Docstrings are strings enclosed in triple quotes (
'''
or"""
) that are used to provide documentation for functions, classes, or modules in Python. They are accessible via the__doc__
attribute.
- Docstrings are strings enclosed in triple quotes (
What is the purpose of the
__slots__
attribute in Python?- The
__slots__
attribute is used to explicitly declare the attributes of a class, preventing the creation of dynamic attributes. This can reduce memory usage and improve performance for classes with a fixed set of attributes.
- The
How do you install third-party packages in Python?
- Third-party packages in Python can be installed using package managers like
pip
, which is the standard package manager for Python. You can install packages by runningpip install package_name
.
- Third-party packages in Python can be installed using package managers like
What are some common design patterns used in Python?
- Some common design patterns used in Python include Singleton, Factory, Observer, Strategy, and Iterator patterns. These patterns provide solutions to common problems in software design.
How do you handle errors and exceptions in Python?
- Errors and exceptions in Python are handled using
try
,except
,finally
, and optionallyelse
blocks. Code that may raise an exception is placed inside thetry
block, and exception handling code is placed inside theexcept
block.
- Errors and exceptions in Python are handled using
What is monkey patching in Python?
- Monkey patching is the practice of dynamically modifying or extending code at runtime. It's often used for adding or modifying behavior in third-party libraries or frameworks.
What is the purpose of the
__getattr__
and__setattr__
methods in Python?- The
__getattr__
method is called when an attribute is accessed that does not exist, allowing you to define custom behavior for attribute access. The__setattr__
method is called when an attribute is assigned a value, allowing you to intercept and modify attribute assignments.
- The
What is the purpose of the
enumerate()
function in Python?- The
enumerate()
function is used to iterate over a sequence (such as a list or tuple) while keeping track of the index of each item. It returns an iterator of tuples containing the index and the corresponding item.
- The
What is the purpose of the
async
andawait
keywords in Python?- The
async
andawait
keywords are used for asynchronous programming in Python. They allow you to define asynchronous functions and await the results of asynchronous operations without blocking the event loop.
- The
What is the purpose of the
functools
module in Python?- The
functools
module in Python provides higher-order functions and operations on callable objects. It includes utilities for function composition, memoization, and partial function application.
- The
How do you handle timezones in Python?
- Timezones in Python are handled using the
datetime
module, which provides classes likedatetime
andtimezone
for working with dates, times, and timezones. Thepytz
library can also be used for more comprehensive timezone support.
- Timezones in Python are handled using the
What is the purpose of the
collections
module in Python?- The
collections
module in Python provides specialized container datatypes, such asCounter
,deque
,namedtuple
, anddefaultdict
, which are useful for various tasks such as counting elements, creating ordered collections, and handling dictionaries with default values.
- The
What is the purpose of the
argparse
module in Python?- The
argparse
module in Python is used for parsing command-line arguments. It provides a convenient way to define and parse command-line options and arguments, automatically generating help messages and usage documentation.
- The
Comments
Post a Comment