Python Practical Questions with Answers
Core Python Question
Q1: Write a Python function to reverse a string without using slicing and built-in reversed(). Input:
"Abhilasha" Expected Output: "ahsalihbA"
Answer:
Answer: def reverse_string(s): result = "" for char in s: result = char + result
return result print(reverse_string("Abhilasha")) # ahsalihbA
Advanced Python (NumPy, Pandas, Seaborn, Matplotlib)
Q2: Using NumPy, create a 1D array of 20 random integers between 1 and 100. Then replace all
odd numbers with -1 without using loops.
Answer:
Answer: import numpy as np arr = np.random.randint(1, 101, 20) arr[arr % 2 != 0] =
-1 print(arr)
Pandas Question
Q3: Given a DataFrame of student names and scores, add a new column 'Grade' where score >=
90 is 'A', 70-89 is 'B', and below 70 is 'C'.
Answer:
Answer: import pandas as pd data = {'Name': ['Raj', 'Simran', 'Amit', 'Priya'],
'Score': [95, 75, 60, 88]} df = pd.DataFrame(data) def grade(score): if score >= 90:
return 'A' elif score >= 70: return 'B' else: return 'C' df['Grade'] =
df['Score'].apply(grade) print(df)
Visualization (Seaborn & Matplotlib)
Q4: Create a barplot using seaborn for the following data: Categories = ['A','B','C','D'], Values =
[23,45,12,36]. Add labels on top of each bar.
Answer:
Answer: import seaborn as sns import matplotlib.pyplot as plt categories =
['A','B','C','D'] values = [23,45,12,36] ax = sns.barplot(x=categories, y=values)
for i, v in enumerate(values): ax.text(i, v + 1, str(v), ha='center') plt.show()
Python AI/ML Question (Linear Regression)
Q5: Using sklearn, perform Linear Regression on dataset X=[1,2,3,4,5], Y=[2,4,5,4,5]. Predict the
value of Y when X=6.
Answer:
Answer: from sklearn.linear_model import LinearRegression import numpy as np X =
np.array([1,2,3,4,5]).reshape(-1,1) Y = np.array([2,4,5,4,5]) model =
LinearRegression() model.fit(X, Y) print(model.predict([[6]]))
Python AI/ML Question (Logistic Regression)
Q6: Train a Logistic Regression classifier using sklearn to predict if a student passes (1) or fails (0)
based on study hours. Dataset: Hours=[1,2,3,4,5,6], Pass=[0,0,0,1,1,1]. Predict for Hours=2.5.
Answer:
Answer: from sklearn.linear_model import LogisticRegression import numpy as np X =
np.array([1,2,3,4,5,6]).reshape(-1,1) Y = np.array([0,0,0,1,1,1]) model =
LogisticRegression() model.fit(X, Y) print(model.predict([[2.5]]))