0% found this document useful (0 votes)
5 views10 pages

Python Interview Questions

Uploaded by

khajulrehaman77
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
Download as txt, pdf, or txt
0% found this document useful (0 votes)
5 views10 pages

Python Interview Questions

Uploaded by

khajulrehaman77
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1/ 10

##Python Basic to Advance Questions with Answers MADE BY |------__MDRK__-------|

1. What is Python?
Answer: Python is an interpreted, high-level, general-purpose programming
language. It is known for its simple syntax and readability, making it easy for
beginners to learn and use.

2. What are the key features of Python?


Answer:
- Easy to read and write.
- Dynamically typed (no need to declare variable types).
- Interpreted language (no compilation step).
- Large standard library.
- Supports both object-oriented and functional programming.

3. What is PEP 8?
Answer: PEP 8 is the Python Enhancement Proposal that outlines the style
guidelines for writing Python code to ensure readability and consistency across
Python projects.

4. What are Python’s built-in data types?


Answer:
- Numeric: int, float, complex
- Sequence: list, tuple, range
- Text: str
- Set types: set, frozenset
- Mapping type: dict
- Boolean type: bool
- Binary types: bytes, bytearray, memoryview

5. What is a Python list?


Answer: A list is a mutable, ordered collection of items in Python. Lists can
hold items of different data types and support operations like indexing, slicing,
and modifying elements.

6. How do you create a list in Python?


Answer: You create a list by placing items inside square brackets [], separated
by commas. For example:
my_list = [1, 2, 3, "apple", "banana"]

7. What is a tuple in Python?


Answer: A tuple is an immutable, ordered collection of items in Python. Once
created, its elements cannot be modified. Tuples are defined using parentheses ().

8. What’s the difference between a list and a tuple?


Answer:
- List: Mutable, can be changed after creation.
- Tuple: Immutable, cannot be changed after creation.

9. What is a dictionary in Python?


Answer: A dictionary is an unordered collection of key-value pairs. It allows
fast lookups by key. Dictionaries are defined using curly braces {}.

10. How do you access elements in a dictionary?


Answer: You can access elements in a dictionary by referencing the key:
my_dict = {"name": "John", "age": 25}
print(my_dict["name"]) # Output: John
11. What is a set in Python?
Answer: A set is an unordered collection of unique items in Python. Sets are
defined using curly braces {} or the set() constructor.

12. How do you create a set?


Answer: You can create a set like this:
my_set = {1, 2, 3}
another_set = set([1, 2, 3])

13. What are the common operations you can perform on sets?
Answer:
- Union: set1 | set2
- Intersection: set1 & set2
- Difference: set1 - set2
- Symmetric difference: set1 ^ set2

14. What is a function in Python?


Answer: A function is a block of reusable code that performs a specific task. It
is defined using the def keyword.

15. How do you define a function in Python?


Answer: You define a function using the def keyword followed by the function
name and parentheses:
def my_function():
print("Hello, World!")

16. What is the return statement used for?


Answer: The return statement is used to return a value from a function back to
the caller.

17. What is a lambda function in Python?


Answer: A lambda function is an anonymous, small function defined using the
lambda keyword. It can take multiple arguments but has only one expression.
Example:
square = lambda x: x ** 2
print(square(5)) # Output: 25

18. What is the difference between a regular function and a lambda function?
Answer:
- Regular Function: Defined using def, can have multiple expressions.
- Lambda Function: Defined using lambda, has only one expression.

19. What are Python decorators?


Answer: Decorators are functions that modify the behavior of other functions.
They are used to extend the functionality of functions or methods without changing
their actual code.

20. How do you create a decorator in Python?


Answer: A decorator is created using a function that takes another function as
an argument and returns a modified function:
def my_decorator(func):
def wrapper():
print("Before the function call")
func()
print("After the function call")
return wrapper

21. What is a module in Python?


Answer: A module is a file containing Python definitions, functions, and
variables. It allows code to be organized into reusable components.

22. How do you import a module in Python?


Answer: You can import a module using the import keyword:
import math
print(math.sqrt(16)) # Output: 4.0

23. What are Python packages?


Answer: A package is a collection of modules organized in a directory with an
__init__.py file. Packages allow for structuring larger Python programs.

24. What is the difference between a module and a package?


Answer:
- Module: A single file containing Python code.
- Package: A collection of modules organized in a directory.

25. What are global variables in Python?


Answer: Global variables are variables defined outside of any function and can
be accessed anywhere in the program.

26. What are local variables in Python?


Answer: Local variables are variables defined inside a function and can only be
accessed within that function.

27. What is a class in Python?


Answer: A class is a blueprint for creating objects. It defines attributes
(data) and methods (functions) that the objects created from the class will have.

28. How do you define a class in Python?


Answer: You define a class using the class keyword:
class MyClass:
d2ef __init__(self, name):
self.name = name

29. What is the `__init__` method in Python?


Answer: The __init__ method is a special method in Python that initializes an
object’s state when it is created. It is also known as the constructor.

30. What is inheritance in Python?


Answer: Inheritance allows one class (child class) to inherit attributes and
methods fr2om another class (parent class), enabling code reuse.

31. What are the types of inheritance in Python?


Answer:
- Single Inheritance
- Multiple Inheritance
- Multilevel Inheritance
- Hierarchical Inheritance
- Hybrid Inheritance

32. What is polymorphism in Python?


Answer: Polymorphism allows objects of different classes to be treated as
objects of a common superclass, mainly through methods like overriding and operator
overloading.

33. What is encapsulation in Python?


Answer: Encapsulation is the concept of wrapping data (variables) and methods
(functions) into a single unit, i.e., a class, while restricting direct access to
some attributes.

34. What is the difference between `__str__` and `__repr__` methods in Python?
Answer:
- __str__: Used for creating a readable string representation of an object.
- __repr__: Used for creating an official string representation, often used for
debugging.

35. What are Python exceptions?


Answer: Exceptions are errors that occur during the execution of a program.
Python handles exceptions using try, except, else, and finally blocks.

36. How do you handle exceptions in Python?


Answer: You handle exceptions using a try-except block:
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")

37. What is the difference between `try`, `except`, and `finally` in exception
handling?
Answer:
- try: Code that may raise an exception.
- except: Code that handles the exception.
- finally: Code that runs no matter what, even if an exception is raised.

38. What is the use of the `with` statement in Python?


Answer: The with statement simplifies exception handling when working with
resources like files by ensuring that they are properly cleaned up (e.g., file
closed) after their use.

39. What is file handling in Python?


Answer: File handling in Python involves operations like reading from or writing
to files using built-in functions like open(), read(), write(), and close().

40. How do you read from a file in Python?


Answer: You can read from a file using the open() function and the read()
method:
file = open("example.txt", "r")
content = file.read()
print(content)
file.close()

41. What are iterators in Python?


Answer: Iterators are objects that can be iterated (looped) upon. They implement
two methods: __iter__() and __next__().

42. What is a generator in Python?


Answer: Generators are functions that return an iterable set of items one at a
time, instead of storing the entire set in memory. They use the yield keyword
instead of return.

43. What is a `for` loop in Python?


Answer: A for loop is used to iterate over a sequence (such as a list, tuple, or
string) and perform a block of code for each item.
44. How do you write a `for` loop in Python?
Answer: A basic for loop looks like this:
for i in range(5):
print(i)

45. What is the `range()` function in Python?


Answer: range() generates a sequence of numbers. It is often used in loops.
Example:
for i in range(3):
print(i)

46. What is the difference between `range()` and `xrange()`?


Answer: In Python 2, range() returns a list, and xrange() returns an iterator.
In Python 3, xrange() was removed, and range() behaves like xrange() from Python 2.

47. What is a `while` loop in Python?


Answer: A while loop continues to execute as long as a given condition is True.

48. What is a `break` statement in Python?


Answer: The break statement is used to exit a loop prematurely when a certain
condition is met.

49. What is the `continue` statement in Python?


Answer: The continue statement is used to skip the rest of the code inside a
loop for the current iteration and continue with the next iteration.

50. What is the `pass` statement in Python?


Answer: The pass statement is a null operation used as a placeholder when a
statement is required but no action is needed. It does nothing when executed.

51. What is recursion in Python?


Answer: Recursion is a programming technique where a function calls itself to
solve smaller instances of the same problem.

52. What is the base case in recursion?


Answer: The base case is the condition that stops the recursion, preventing an
infinite loop.

53. What is the difference between `==` and `is` in Python?


Answer:
- ==: Compares the values of two objects.
- is: Compares the identity of two objects (whether they are the same object in
memory).

54. What is a shallow copy in Python?


Answer: A shallow copy creates a new object, but it only copies the reference of
the elements in the original object, not the objects themselves.

55. What is a deep copy in Python?


Answer: A deep copy creates a new object and recursively copies all objects
found within the original object.

56. What is list comprehension in Python?


Answer: List comprehension is a concise way to create lists using a single line
of code. Example:
squares = [x**2 for x in range(5)]
57. What is a map() function in Python?
Answer: The map() function applies a given function to all items in an iterable
(e.g., list) and returns a map object.

58. What is the filter() function in Python?


Answer: The filter() function filters elements from an iterable based on a
condition, returning only the elements that meet the condition.

59. What is the reduce() function in Python?


Answer: The reduce() function, from the functools module, applies a function
cumulatively to the items of an iterable, reducing them to a single value.

60. What is the difference between `map()`, `filter()`, and `reduce()`?


Answer:
- map(): Applies a function to all items in an iterable.
- filter(): Returns only the elements that meet a condition.
- reduce(): Reduces all elements in an iterable to a single value using a
function.

61. What are list slicing and indexing in Python?


Answer: Indexing retrieves a single element from a list, while slicing retrieves
a subset of the list. Example:
my_list = [1, 2, 3, 4, 5]
print(my_list[2]) # Output: 3 (indexing)
print(my_list[1:4]) # Output: [2, 3, 4] (slicing)

62. How do you reverse a list in Python?


Answer: You can reverse a list using slicing:
reversed_list = my_list[::-1]

63. What is the difference between mutable and immutable objects in Python?
Answer:
- Mutable: Can be modified after creation (e.g., lists, dictionaries).
- Immutable: Cannot be modified after creation (e.g., tuples, strings).

64. What is the difference between Python 2 and Python 3?


Answer:
- Python 2: Older version, deprecated.
- Python 3: Current and recommended version with several improvements, such as
print() as a function and better Unicode handling.

65. What are Python’s built-in functions?


Answer: Python has many built-in functions, such as len(), type(), input(),
sum(), sorted(), and max(), which are available without importing any module.

66. What is the `__name__` variable in Python?


Answer: The __name__ variable is a special built-in variable that evaluates to
"__main__" when the script is executed directly and the module name if it is
imported.

67. How do you create a virtual environment in Python?


Answer: You can create a virtual environment using venv:
python3 -m venv myenv

68. What is pip in Python?


Answer: pip is the package manager for Python that allows you to install and
manage Python libraries.

69. How do you install a package in Python?


Answer: You can install a package using pip:
pip install package_name

70. What is the `time` module in Python?


Answer: The time module provides functions for handling time-related tasks, such
as sleep(), time(), and strftime().

71. How do you measure time in Python?


Answer: You can measure time using the time module:
import time
start = time.time()
# some code
end = time.time()
print("Time taken:", end - start)

72. What is the `random` module in Python?


Answer: The random module provides functions to generate random numbers and
perform random operations, such as random(), randint(), and choice().

73. How do you generate a random number in Python?


Answer: You can generate a random number using the random module:
import random
print(random.randint(1, 10)) # Random integer between 1 and 10

74. What is the difference between `random()` and `randint()`?


Answer:
- random(): Generates a random float between 0 and 1.
- randint(): Generates a random integer between two specified values.

75. What is the difference between deep learning and machine learning in Python?
Answer:
- Machine Learning: Algorithms that learn from data and make predictions.
- Deep Learning: A subset of machine learning that uses neural networks
with multiple layers for more complex tasks like image recognition.

76. How do you handle exceptions in Python?


Answer: You can handle exceptions using try, except, finally blocks. Example:
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
finally:
print("End of code")

77. What is the difference between `try-except` and `try-finally`?


Answer:
- try-except: Catches exceptions that occur inside the try block.
- try-finally: Ensures that the finally block is always executed, regardless of
whether an exception occurs.

78. What are regular expressions (regex) in Python?


Answer: Regular expressions are patterns used for matching strings. Python's re
module provides support for regex operations like searching, matching, and
splitting.

79. How do you match a pattern in Python using regex?


Answer: You can match a pattern using the re.match() function:
import re
result = re.match(r"hello", "hello world")
print(result) # Output: Match object if pattern matches

80. What is the `re` module in Python used for?


Answer: The re module provides support for working with regular expressions,
such as matching patterns, searching, and replacing strings.

81. How do you work with JSON in Python?


Answer: Python has a json module to work with JSON data. Example to convert a
Python dictionary to a JSON string:
import json
data = {"name": "John", "age": 30}
json_data = json.dumps(data)
print(json_data) # Output: JSON formatted string

82. How do you decode JSON in Python?


Answer: You can decode (deserialize) JSON data into a Python object using
json.loads(). Example:
json_data = '{"name": "John", "age": 30}'
data = json.loads(json_data)
print(data) # Output: {'name': 'John', 'age': 30}

-83. What are Python decorators?


Answer: A decorator is a function that takes another function as an argument,
extends its behavior, and returns a modified function.

84. How do you define a Python decorator?


Answer: You can define a decorator like this:
def my_decorator(func):
def wrapper():
print("Something before the function")
func()
print("Something after the function")
return wrapper

@my_decorator
def say_hello():
print("Hello!")

say_hello()

85. What is the `@staticmethod` decorator in Python?


Answer: The @staticmethod decorator defines a method inside a class that does
not modify class or instance state. It can be called without creating an instance
of the class.

86. What is the `@classmethod` decorator in Python?


Answer: The @classmethod decorator defines a method that takes the class as its
first argument (cls) and can be called on the class itself rather than an instance
of the class.

87. What is method overriding in Python?


Answer: Method overriding allows a subclass to provide a specific implementation
of a method that is already defined in its superclass.

88. What is method overloading in Python?


Answer: Python does not support traditional method overloading (as in Java or C+
+), but we can achieve similar functionality using default arguments or *args and
kwargs.

89. What are magic methods in Python?


Answer: Magic methods (also known as dunder methods) are special methods with
double underscores before and after their names (e.g., __init__(), __str__()). They
are used to define behavior for built-in operations.

90. What is the `__str__()` method in Python?


Answer: The __str__() method is used to define how an object is represented as a
string. It is called when you use print() on an object.

91. What is the `__init__()` method in Python?


Answer: The __init__() method is a constructor that initializes an object when
it is created.

92. What is the `__del__()` method in Python?


Answer: The __del__() method is a destructor that is called when an object is
about to be destroyed, used to clean up resources.

93. What is the purpose of the `__repr__()` method in Python?


Answer: The __repr__() method is used to provide a string representation of an
object, primarily for debugging purposes.

94. What is a lambda function in Python?


Answer: A lambda function is a small anonymous function defined using the lambda
keyword. Example:
add = lambda x, y: x + y
print(add(2, 3)) # Output: 5

95. What is the difference between a lambda function and a normal function in
Python?
Answer: A lambda function is defined in a single line and can have only one
expression. Normal functions are defined using def and can have multiple
expressions.

96. What is the purpose of the `assert` statement in Python?


Answer: The assert statement is used for debugging purposes. It tests if a
condition is True. If it is False, an AssertionError is raised.

97. What is monkey patching in Python?


Answer: Monkey patching is the practice of dynamically modifying or extending a
class or module at runtime. It is generally considered a bad practice because it
can lead to unexpected behavior.

98. What is the `collections` module in Python?


Answer: The collections module provides specialized container types such as
deque, namedtuple, Counter, and defaultdict for handling collections of data.

99. What is the `os` module in Python?


Answer: The os module provides functions for interacting with the operating
system, such as file manipulation, working with directories, and getting
environment variables.

100. How do you work with environment variables in Python?


Answer: You can work with environment variables using the os module. Example:
import os
print(os.environ.get('HOME')) # Gets the value of the 'HOME' environment
variable

You might also like