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.