Python Core Interview Questions
Python Core Interview Questions
1. What are Python’s key features that make it popular for AI and
automation?
a = [1, 2, 3]
b = [1, 2, 3]
a = [1, 2, 3]
b=a
lst = [1, 2, 3]
tup = (1, 2, 3)
Shallow Copy: Creates a new object but does not create copies of
nested objects; it only copies references to them. Example:
import copy
b = copy.copy(a)
b[0][0] = 100
import copy
b = copy.deepcopy(a)
b[0][0] = 100
lst = [1, 2, 3]
tup = (1, 2, 3)
st = {1, 2, 3}
Python supports multi-threading using the threading module, but due to the
Global Interpreter Lock (GIL), it is not suitable for CPU-bound tasks.
Python threads are better suited for I/O-bound tasks (e.g., file operations,
network requests). For CPU-bound tasks, multiprocessing is preferred
because it bypasses the GIL by creating separate processes.
import threading
def print_numbers():
for i in range(5):
print(i)
thread = threading.Thread(target=print_numbers)
thread.start()
thread.join()
Example:
f.write('Hello, World!')
__init__: This method initializes an instance of the class after the object
is created. It is called when a new object is instantiated.
class MyClass:
self.name = name
def __new__(cls):
return super().__new__(cls)
class MyClass:
def __call__(self):
return 'Hello'
obj = MyClass()
class Car:
def get_model(self):
return self.__model
class Vehicle:
def start(self):
return "Starting the vehicle"
class Car(Vehicle):
def drive(self):
class Dog:
def speak(self):
return "Woof"
class Cat:
def speak(self):
return "Meow"
class Animal(ABC):
@abstractmethod
def speak(self):
pass
class MyClass:
def instance_method(self):
print(self)
class MyClass:
@staticmethod
def static_method():
class MyClass:
@classmethod
def class_method(cls):
The Method Resolution Order (MRO) is the order in which Python looks
for a method in the class hierarchy. Python uses the C3 Linearization
algorithm to determine the MRO in the case of multiple inheritance.
Example:
class A:
def method(self):
print("Method in A")
class B(A):
def method(self):
print("Method in B")
class C(A):
def method(self):
print("Method in C")
pass
print(D.mro())
Output:
Example:
class Dog:
def speak(self):
print("Woof")
class Duck:
def speak(self):
print("Quack")
def make_speak(animal):
Example:
class Point:
self.x = x
self.y = y
The Singleton pattern ensures that only one instance of a class exists. You
can implement it by controlling the instantiation using a class variable.
Example:
class Singleton:
_instance = None
def __new__(cls):
if not cls._instance:
cls._instance = super().__new__(cls)
return cls._instance
18. What is the difference between AI, ML, and Deep Learning?
AI (Artificial Intelligence): The field of AI encompasses creating
intelligent systems that can simulate human-like tasks. This involves
reasoning, decision-making, perception, and language understanding.
AI can include rule-based systems, expert systems, and more complex
approaches.
Overfitting occurs when a model learns the details and noise in the
training data to such an extent that it negatively impacts the
performance of the model on new data (generalization).
Prevention Techniques:
22. What are the main differences between logistic regression and
decision trees?
Resampling Techniques:
4. Feature engineering: Create new features that may help the model.
1. Train and save the model using libraries like scikit-learn or TensorFlow.
2. Create a Flask web application with routes to handle input data and
return predictions.
4. Pass input data from HTTP requests to the model and return the
predictions as HTTP responses.
5. Deploy the Flask app on a server or cloud platform (e.g., AWS, Heroku).
import requests
url = 'https://news.ycombinator.com/'
response = requests.get(url)
print(headline.text)
To automate a browser in Python, you can use Selenium, which can control
web browsers like Chrome or Firefox. Selenium interacts with web elements
and performs tasks like clicking buttons, filling forms, and navigating
between pages.
Example:
driver = webdriver.Chrome()
driver.get('https://www.example.com')
button = driver.find_element_by_id('submit')
button.click()
driver.quit()
37. What are headless browsers, and why are they useful?
A headless browser is a web browser that does not display a graphical user
interface. It can be controlled programmatically to interact with web pages,
similar to a regular browser, but without the need for a visible interface.
Example: You can use Selenium with a headless browser to scrape a website
in an automated script:
options = Options()
options.headless = True
driver = webdriver.Chrome(options=options)
driver.get('https://www.example.com')
import requests
response = requests.get('https://api.example.com/data')
data = response.json()
To send a POST request in Python, you can use the requests library:
import requests
url = 'https://www.example.com/api'
print(response.text)
An API token is a unique identifier that grants access to an API. It is used for
authentication to verify the user or application making the request. Tokens
are typically passed in the HTTP headers to secure API endpoints.
Example:
import requests
Rate limiting restricts the number of API requests a user or application can
make within a specific time window. To handle this:
Check the rate limit headers: Many APIs return rate limit
information in the response headers (X-RateLimit-Remaining, X-
RateLimit-Reset).
Pause requests: If you hit the rate limit, implement a sleep or wait
mechanism to pause your requests until the limit is reset.
Example:
import time
response = requests.get('https://api.example.com/data')
remaining_requests = int(response.headers['X-RateLimit-Remaining'])
if remaining_requests == 0:
reset_time = int(response.headers['X-RateLimit-Reset'])
time.sleep(sleep_time)
Task Scheduling Questions:
44. What are cron jobs, and how do you schedule Python scripts?
2. Add a cron job entry, specifying the time and command to run the
Python script.
0 5 * * * /usr/bin/python3 /path/to/script.py
@app.task
return x + y
You can use Redis as the message broker for Celery, allowing you to manage
and distribute tasks across worker nodes. Redis stores tasks in a queue, and
Celery workers consume them asynchronously.
Coding Challenges:
# Setup WebDriver
driver = webdriver.Chrome()
driver.get('https://example.com/login')
driver.find_element(By.ID, 'username').send_keys('my_username')
driver.find_element(By.ID, 'password').send_keys('my_password')
driver.find_element(By.ID, 'submit').click()
driver.implicitly_wait(5)
print(data)
driver.quit()
import smtplib
@app.post("/send-email/")
sender_email = "[email protected]"
receiver_email = recipient
password = "mypassword"
msg = MIMEMultipart()
msg['From'] = sender_email
msg['To'] = receiver_email
msg['Subject'] = subject
msg.attach(MIMEText(body, 'plain'))
server.starttls()
server.login(sender_email, password)
text = msg.as_string()
Example: You can design a system where users send requests for
predictions. A web API (Flask/FastAPI) receives these requests, stores them in
a queue (Redis), and workers asynchronously process them using a trained
model stored in a model registry.
"user_id": 1234,
"timestamp": "2025-02-05T10:00:00",
1. Rate Limiting: Prevent abuse and protect the system by limiting the
number of requests from each user within a given time frame.
2. Log Shippers: Use agents like Filebeat or Fluentd to ship logs from
individual microservices to a central logging server.
For an AI-based automation tool, the database design would depend on the
type of tool and its functionality. Generally:
FROM users
GROUP BY email
Impact on Performance:
Coding Challenges:
FROM employees
LIMIT 5;
import redis
import time
app = FastAPI()
@app.get("/data/")
cached_data = cache.get("data_key")
if cached_data:
I prioritize tasks based on urgency and impact. I break down large projects
into smaller, manageable parts and use time management techniques like
the Pomodoro method to stay focused. When under pressure, I keep calm,
communicate effectively with the team, and adjust strategies as needed.
64. What would you do if you had to learn a new technology quickly?
I ensure that my automation scripts are well-tested by writing unit tests and
integrating them with a continuous integration pipeline. I also handle
exceptions properly, log errors for debugging, and use tools like linters to
ensure clean and maintainable code.
AI Libraries
1. TensorFlow
Interview Explanation:
Example:
import tensorflow as tf
model = tf.keras.Sequential([
tf.keras.layers.Dense(10, activation='softmax')
])
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
2. PyTorch
Interview Explanation:
o PyTorch is known for its flexibility and ease of use, which makes it
suitable for both research and production.
Example:
import torch
import torch.nn as nn
class SimpleModel(nn.Module):
def __init__(self):
super(SimpleModel, self).__init__()
x = torch.relu(self.fc1(x))
return self.fc2(x)
3. NumPy
Interview Explanation:
Example:
import numpy as np
arr_squared = np.square(arr)
4. Pandas
Interview Explanation:
import pandas as pd
5. Scikit-learn
Interview Explanation:
Example:
model = LogisticRegression()
model.fit(X_train, y_train)
Automation Libraries
6. Selenium
Interview Explanation:
Example:
driver = webdriver.Chrome()
driver.get("https://www.example.com")
element = driver.find_element_by_name("q")
element.send_keys("Hello, World!")
driver.quit()
7. BeautifulSoup
Interview Explanation:
Example:
import requests
response = requests.get('https://www.example.com')
title = soup.title.string
print(title)
When Discussing in Interviews:
Context: Depending on the role, the interviewer might ask you about
specific libraries to assess your knowledge in either AI (TensorFlow,
PyTorch, NumPy, etc.) or automation (Selenium, BeautifulSoup).
Be prepared to explain both high-level concepts (why and when you would
use these libraries) and low-level code implementation (how to
implement tasks using them).
1. Scikit-learn
What is Scikit-learn?
Key Features:
Easy integration with other Python libraries like Pandas and TensorFlow.
Interview Question:
2. TensorFlow
What is TensorFlow?
Key Features:
Interview Question:
Q: Have you worked with TensorFlow before? If so, what did you do?
3. Keras
What is Keras?
Keras is a high-level deep learning API that runs on top of TensorFlow. It is
used for building neural networks quickly and efficiently with a simpler
syntax.
Key Features:
Interview Question:
A:
4. OpenCV
What is OpenCV?
Key Features:
Interview Question:
Simplified
High-level API, Pre-trained Rapid prototyping,
Keras Deep
models, Easy-to-use model training
Learning
If the interviewer asks about these libraries, don't just define them—relate
them to your projects to show hands-on experience!
1. Regression
What is Regression?
Types of Regression:
Interview Question:
2. Classification
What is Classification?
Interview Question:
3. Clustering
What is Clustering?
Interview Question:
4. Feature Engineering
Interview Question:
values
3. Computer Vision
7. Databases