Python Interview Prepp Q&A Compilation_dark
Python Interview Prepp Q&A Compilation_dark
1. Basic Syntax
Q1: What is Python? A1: Python is a high-level, interpreted programming language known
for its readability and versatility. It supports multiple programming paradigms, including
procedural, object-oriented, and functional programming.
Q2: How do you write a comment in Python? A2: Single-line comments start with a # .
Multi-line comments can be written using triple quotes ( ''' comment ''' or """ comment
""" ).
Q3: How do you print a message in Python? A3: Use the print() function. For example:
python
print("Hello, World!")
Q4: How do you get input from the user in Python? A4: Use the input() function. For
example:
python
1/26
Q6: How do you declare a variable in Python? A6: Simply assign a value to a variable name.
For example:
python
x = 5
name = "Alice"
Q7: How do you check the type of a variable? A7: Use the type() function. For example:
python
3. Data Structures
Q8: What are lists in Python? A8: Lists are ordered, mutable collections of items. They are
defined using square brackets. For example:
python
my_list = [1, 2, 3, 4, 5]
Q9: How do you add an item to a list? A9: Use the append() method. For example:
python
my_list.append(6)
Q10: How do you remove an item from a list? A10: Use the remove() method or the pop()
method. For example:
python
my_list.remove(3)
# or
my_list.pop(2) # Removes the item at index 2
2/26
Q11: What are tuples in Python? A11: Tuples are ordered, immutable collections of items.
They are defined using parentheses. For example:
python
my_tuple = (1, 2, 3)
Q12: What are dictionaries in Python? A12: Dictionaries are unordered collections of key-
value pairs. They are defined using curly braces. For example:
python
Q13: How do you access a value in a dictionary? A13: Use the key inside square brackets.
For example:
python
4. Control Flow
Q14: How do you write an if-else statement in Python? A14: Use the if , elif , and else
keywords. For example:
python
x = 10
if x > 0:
print("Positive")
elif x == 0:
print("Zero")
else:
print("Negative")
Q15: How do you write a for loop in Python? A15: Use the for keyword followed by an
iterable. For example:
3/26
python
for i in range(5):
print(i)
Q16: How do you write a while loop in Python? A16: Use the while keyword followed by a
condition. For example:
python
count = 0
while count < 5:
print(count)
count += 1
5. Functions
Q17: How do you define a function in Python? A17: Use the def keyword followed by the
function name and parentheses. For example:
python
def greet(name):
return f"Hello, {name}!"
Q18: How do you call a function in Python? A18: Use the function name followed by
parentheses. For example:
python
print(greet("Alice"))
Q19: What are default arguments in a function? A19: Default arguments are specified by
assigning a value in the function definition. For example:
python
4/26
Q20: What are *args and kwargs? A20: *args allows a function to accept any number of
positional arguments, and **kwargs allows a function to accept any number of keyword
arguments. For example:
python
python
class Dog:
def __init__(self, name):
self.name = name
def bark(self):
return f"{self.name} says woof!"
Q22: How do you create an object of a class? A22: Use the class name followed by
parentheses. For example:
python
my_dog = Dog("Buddy")
print(my_dog.bark())
Q23: What is inheritance in Python? A23: Inheritance allows a class to inherit attributes and
methods from another class. For example:
python
5/26
class Animal:
def __init__(self, name):
self.name = name
class Dog(Animal):
def bark(self):
return f"{self.name} says woof!"
python
class Cat:
def speak(self):
return "Meow"
class Dog:
def speak(self):
return "Woof"
def make_sound(animal):
print(animal.speak())
make_sound(Cat())
make_sound(Dog())
python
import math
print(math.sqrt(16))
Q26: How do you install a package in Python? A26: Use the pip command. For example:
6/26
sh
Q27: How do you import specific functions from a module? A27: Use the from keyword.
For example:
python
8. File Handling
Q28: How do you open a file in Python? A28: Use the open() function. For example:
python
Q29: How do you read from a file? A29: Use the read() method. For example:
python
content = file.read()
print(content)
file.close()
Q30: How do you write to a file? A30: Use the write() method. For example:
python
Q31: How do you handle file exceptions? A31: Use a try-except block. For example:
python
7/26
try:
file = open("example.txt", "r")
except FileNotFoundError:
print("File not found")
9. Exception Handling
Q32: How do you handle exceptions in Python? A32: Use the try-except block. For
example:
python
try:
x = 1 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
Q33: How do you catch multiple exceptions? A33: Use multiple except blocks. For
example:
python
try:
x = int("abc")
except ValueError:
print("ValueError")
except TypeError:
print("TypeError")
Q34: How do you use the finally block? A34: The finally block executes regardless of
whether an exception occurs. For example:
python
try:
x = 1 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
8/26
finally:
print("This will always execute")
python
def decorator_func(func):
def wrapper():
print("Something is happening before the function is called.")
func()
print("Something is happening after the function is called.")
return wrapper
@decorator_func
def say_hello():
print("Hello!")
say_hello()
Q36: What are generators in Python? A36: Generators are functions that return an iterable
set of items, one at a time, in a special way using the yield keyword. For example:
python
def my_generator():
yield 1
yield 2
yield 3
gen = my_generator()
print(next(gen))
print(next(gen))
print(next(gen))
9/26
Q37: What is a lambda function in Python? A37: Lambda functions are small anonymous
functions defined with the lambda keyword. For example:
python
add = lambda x, y: x + y
print(add(2, 3))
Q38: What is list comprehension? A38: List comprehension provides a concise way to create
lists. For example:
python
Q39: What is a context manager in Python? A39: Context managers are used to manage
resources, such as file streams. They are implemented using the with statement. For
example:
python
11. Testing
Q40: What is unit testing in Python? A40: Unit testing is a method where individual units or
components of the software are tested. Python's unittest module is commonly used for
this. For example:
python
import unittest
10/26
class TestMath(unittest.TestCase):
def test_add(self):
self.assertEqual(add(2, 3), 5)
if __name__ == "__main__":
unittest.main()
python
import re
pattern = r"\d+"
text = "There are 123 numbers in this text."
matches = re.findall(pattern, text)
print(matches)
This is a subset of the questions you might encounter when learning Python. To reach a total
of 100 questions and answers, you would continue to delve deeper into each topic and
introduce additional topics such as working with external libraries, advanced data structures,
concurrency, and more.
Would you like to continue with more questions, or focus on any particular section in more
detail?
more
Sure! Let's continue with more questions across various topics, aiming for a total of 100.
11/26
expression to the caller.
Q43: How do you write a multi-line string in Python? A43: Use triple quotes, either ''' or
""" . For example:
python
multi_line_string = """This is a
multi-line string."""
Q44: What is PEP 8? A44: PEP 8 is the Python Enhancement Proposal that provides
guidelines and best practices on how to write Python code.
Q46: How do you convert a string to an integer in Python? A46: Use the int() function.
For example:
python
num = int("123")
Q47: How do you convert an integer to a string in Python? A47: Use the str() function.
For example:
python
num_str = str(123)
python
12/26
my_set = {1, 2, 3}
# or
my_set = set([1, 2, 3])
Q49: What is the difference between a list and a tuple in Python? A49: A list is mutable,
meaning it can be changed, while a tuple is immutable, meaning it cannot be changed once
created.
Q50: How do you perform a union of sets in Python? A50: Use the union() method or the
| operator. For example:
python
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1.union(set2)
# or
union_set = set1 | set2
Q51: How do you perform an intersection of sets in Python? A51: Use the intersection()
method or the & operator. For example:
python
intersection_set = set1.intersection(set2)
# or
intersection_set = set1 & set2
Q52: How do you create a dictionary comprehension in Python? A52: Use curly braces with
a key-value expression. For example:
python
13/26
Q53: What is the purpose of the break statement in Python? A53: The break statement
exits the nearest enclosing loop immediately.
Q54: What is the purpose of the continue statement in Python? A54: The continue
statement skips the current iteration and moves to the next iteration of the loop.
Q55: How do you use a for loop with an else clause? A55: The else clause in a for
loop executes after the loop completes normally (without encountering a break statement).
For example:
python
for i in range(5):
print(i)
else:
print("Loop completed")
5. Functions (Continued)
Q56: How do you define a recursive function in Python? A56: A recursive function is a
function that calls itself. For example:
python
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n-1)
Q57: How do you use the map() function in Python? A57: The map() function applies a
given function to all items in an input list. For example:
python
def square(x):
return x * x
numbers = [1, 2, 3, 4]
14/26
squared_numbers = list(map(square, numbers))
print(squared_numbers) # Output: [1, 4, 9, 16]
Q58: How do you use the filter() function in Python? A58: The filter() function
constructs a list from elements of an iterable for which a function returns true. For example:
python
def is_even(x):
return x % 2 == 0
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = list(filter(is_even, numbers))
print(even_numbers) # Output: [2, 4, 6]
Q60: What is an abstract class in Python? A60: An abstract class is a class that cannot be
instantiated and typically includes one or more abstract methods that must be implemented
by subclasses. Use the abc module to define abstract classes. For example:
python
class Animal(ABC):
@abstractmethod
def make_sound(self):
pass
class Dog(Animal):
def make_sound(self):
return "Woof"
15/26
Q61: What is method overloading in Python? A61: Python does not support method
overloading directly. Instead, you can achieve similar functionality by using default
arguments or by checking types within a method.
Q62: What is method overriding in Python? A62: Method overriding occurs when a subclass
provides a specific implementation of a method that is already defined in its superclass.
python
# mymodule.py
def greet(name):
return f"Hello, {name}!"
Q64: How do you use the dir() function in Python? A64: The dir() function returns a list
of valid attributes for an object. For example:
python
import math
print(dir(math))
Q65: How do you reload a module in Python? A65: Use the importlib.reload() function
from the importlib module. For example:
python
import mymodule
import importlib
importlib.reload(mymodule)
16/26
Q66: How do you read a file line by line in Python? A66: Use a for loop to iterate over the
file object. For example:
python
Q67: How do you write multiple lines to a file in Python? A67: Use the writelines()
method. For example:
python
Q68: How do you append data to a file in Python? A68: Open the file in append mode using
"a" . For example:
python
python
Q70: How do you define a custom exception in Python? A70: Create a new class that
inherits from the built-in Exception class. For example:
17/26
python
class CustomError(Exception):
pass
try:
raise CustomError("This is a custom error")
except CustomError as e:
print(e)
python
def outer_func(msg):
def inner_func():
print(msg)
return inner_func
closure = outer_func("Hello")
closure() # Output: Hello
Q72: What are metaclasses in Python? A72: Metaclasses are classes of classes that define
how a class behaves. A class is an instance of a metaclass. Use the type function to create
metaclasses.
Q73: How do you use the itertools module in Python? A73: The itertools module
provides various functions that work on iterators to produce complex iterators. For example:
python
import itertools
18/26
11. Testing (Continued)
Q74: What is the assert statement in Python? A74: The assert statement is used during
debugging to check for conditions that should always be true. For example:
python
Q75: How do you use the pytest framework in Python? A75: pytest is a testing
framework that makes it easy to write small tests. Install it using pip install pytest and
write test functions prefixed with test_ . For example:
python
def test_add():
assert add(2, 3) == 5
assert add(-1, 1) == 0
python
import re
pattern = r"\d+"
text = "The number is 123"
match = re.search(pattern, text)
19/26
if match:
print(match.group())
Q77: How do you use the re.sub() function in Python? A77: The re.sub() function
replaces occurrences of a pattern with a replacement string. For example:
python
import re
pattern = r"\d+"
text = "The number is 123"
new_text = re.sub(pattern, "456", text)
print(new_text) # Output: The number is 456
python
def repeat(n):
def decorator(func):
def wrapper(*args, **kwargs):
for _ in range(n):
func(*args, **kwargs)
return wrapper
return decorator
@repeat(3)
def say_hello():
print("Hello!")
say_hello()
Q79: What are coroutines in Python? A79: Coroutines are a more generalized form of
subroutines, used for cooperative multitasking. Use the async and await keywords. For
example:
20/26
python
import asyncio
asyncio.run(greet())
Q80: What is the yield from statement in Python? A80: The yield from statement is
used to delegate part of a generator's operations to another generator. For example:
python
def generator1():
yield from range(5)
def generator2():
yield from generator1()
yield 5
Q81: How do you handle binary data in Python? A81: Use the struct module to work with
binary data. For example:
python
import struct
21/26
Q82: What is the collections module in Python? A82: The collections module provides
specialized data structures such as namedtuple , deque , Counter , and OrderedDict . For
example:
python
Q83: What is the functools module in Python? A83: The functools module provides
higher-order functions that act on or return other functions. For example, use
functools.reduce() :
python
numbers = [1, 2, 3, 4]
product = reduce(lambda x, y: x * y, numbers)
print(product) # Output: 24
Q84: How do you use the json module in Python? A84: The json module is used to work
with JSON data. For example:
python
import json
parsed_data = json.loads(json_data)
print(parsed_data) # Output: {'name': 'John', 'age': 30}
Q85: How do you use the datetime module in Python? A85: The datetime module is used
for manipulating dates and times. For example:
22/26
python
now = datetime.now()
print(now)
Q86: What is the pathlib module in Python? A86: The pathlib module provides an
object-oriented interface to working with filesystem paths. For example:
python
path = Path("example.txt")
print(path.exists())
print(path.read_text())
14. Concurrency
Q87: What is the difference between threading and multiprocessing in Python? A87:
threading is used for concurrent execution of code in multiple threads, sharing the same
memory space. multiprocessing is used for concurrent execution of code in separate
processes, each with its own memory space.
Q88: How do you create a thread in Python? A88: Use the threading module. For example:
python
import threading
def print_numbers():
for i in range(5):
print(i)
thread = threading.Thread(target=print_numbers)
23/26
thread.start()
thread.join()
Q89: How do you create a process in Python? A89: Use the multiprocessing module. For
example:
python
import multiprocessing
def print_numbers():
for i in range(5):
print(i)
process = multiprocessing.Process(target=print_numbers)
process.start()
process.join()
Q90: What is the Global Interpreter Lock (GIL) in Python? A90: The GIL is a mutex that
protects access to Python objects, preventing multiple native threads from executing Python
bytecodes at once. This can be a bottleneck in CPU-bound and multi-threaded code.
python
import socket
while True:
client_socket, addr = server_socket.accept()
print(f"Connection from {addr}")
24/26
client_socket.send(b"Hello, client!")
client_socket.close()
Q92: How do you create a TCP client in Python? A92: Use the socket module. For example:
python
import socket
Q93: How do you perform HTTP requests in Python? A93: Use the requests module. For
example:
python
import requests
response = requests.get("https://api.example.com/data")
print(response.json())
Q94: How do you handle URLs in Python? A94: Use the urllib module. For example:
python
import urllib.parse
url = "https://www.example.com/index.html?name=John&age=30"
parsed_url = urllib.parse.urlparse(url)
print(parsed_url)
16. Databases
Q95: How do you connect to a SQLite database in Python? A95: Use the sqlite3 module.
For example:
25/26
python
import sqlite3
connection = sqlite3.connect('example.db')
cursor = connection.cursor()
cursor.execute('''CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name
TEXT)''')
cursor.execute('''INSERT INTO users (name) VALUES ('John')''')
connection.commit()
connection.close()
Q96: How do you connect to a MySQL database in Python? A96: Use the mysql-connector-
python module. For example:
python
import mysql.connector
connection = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="yourdatabase"
)
cursor = connection.cursor()
cursor.execute("SHOW TABLES")
for table in cursor:
print(table)
connection.close()
26/26