0% found this document useful (0 votes)
3 views12 pages

Python Question Bank

This document is a comprehensive question bank covering various topics in Python, including NumPy, Pandas, Matplotlib, file handling, exception handling, Tkinter, and an overview of Python libraries for data science. Each section contains theoretical questions, practical programming tasks, and example code snippets. It serves as a study guide for theory and practical exams in Python programming.

Uploaded by

J.R PHYLM
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views12 pages

Python Question Bank

This document is a comprehensive question bank covering various topics in Python, including NumPy, Pandas, Matplotlib, file handling, exception handling, Tkinter, and an overview of Python libraries for data science. Each section contains theoretical questions, practical programming tasks, and example code snippets. It serves as a study guide for theory and practical exams in Python programming.

Uploaded by

J.R PHYLM
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

🧠 QUESTION BANK FOR THEORY + PRACTICAL EXAM

1️⃣ NumPy Questions

Theory

• Q1. What is NumPy? Why is it faster than Python lists?


➔ NumPy (Numerical Python) is a library for fast, memory-efficient, large numerical
computations. It supports vectorized operations (no loops needed).
• Q2. How do you create arrays in NumPy?

python
CopyEdit
import numpy as np
arr = np.array([1, 2, 3, 4])
print(arr)

• Q3. Differentiate between zeros(), ones(), full(), eye() in NumPy.


• Q4. Write a program to create a 2D array and reshape it into 3x3.

python
CopyEdit
arr = np.arange(1, 10)
new_arr = arr.reshape(3, 3)
print(new_arr)

• Q5. What are slicing and indexing? Give examples.


• Q6. Explain np.save(), np.load(), np.savetxt(), np.loadtxt() with syntax.

2️⃣ Pandas Questions

Theory

• Q1. What is Pandas? What are Series and DataFrame?


➔ Pandas is a Python library for data analysis; Series is 1D, DataFrame is 2D.
• Q2. Write a program to create a DataFrame from a dictionary.

python
CopyEdit
import pandas as pd
data = {'Name': ['A', 'B'], 'Age': [20, 25]}
df = pd.DataFrame(data)
print(df)

• Q3. What is pivot_table()? Why is it used?


• Q4. Explain how to handle missing values using dropna(), fillna(), interpolate().
• Q5. Write code to merge two DataFrames based on a common column.
python
CopyEdit
df1 = pd.DataFrame({'ID': [1, 2], 'Name': ['John', 'Jane']})
df2 = pd.DataFrame({'ID': [2, 3], 'Marks': [90, 80]})
df_merged = pd.merge(df1, df2, on="ID", how="inner")
print(df_merged)

3️⃣ Matplotlib Questions

Theory

• Q1. What is Matplotlib? Why is it used?


• Q2. Explain different types of plots supported by Matplotlib.
• Q3. Program to create a simple line plot.

python
CopyEdit
import matplotlib.pyplot as plt
x = [1, 2, 3, 4]
y = [10, 20, 30, 40]
plt.plot(x, y)
plt.title("Simple Line Plot")
plt.xlabel("x-axis")
plt.ylabel("y-axis")
plt.show()

• Q4. Write a program to plot a bar chart.

python
CopyEdit
x = ['A', 'B', 'C']
y = [30, 50, 70]
plt.bar(x, y)
plt.title('Bar Chart')
plt.show()

4️⃣ File Handling Questions

Theory

• Q1. What is file handling? Why is it necessary?


• Q2. Explain different file modes in Python (r, w, a, x, b, t).
• Q3. Write a program to write and read a file.

python
CopyEdit
# Writing
with open("testfile.txt", "w") as f:
f.write("Hello World")

# Reading
with open("testfile.txt", "r") as f:
content = f.read()
print(content)

• Q4. Explain seek() and tell() functions with examples.


• Q5. How to delete a file? Write the program.

python
CopyEdit
import os
if os.path.exists("testfile.txt"):
os.remove("testfile.txt")

5️⃣ Exception Handling Questions

Theory

• Q1. What are exceptions? How are they different from syntax errors?
• Q2. Explain try-except-finally with example.
• Q3. Program to handle ZeroDivisionError and ValueError.

python
CopyEdit
try:
a = int(input("Enter a number: "))
b = int(input("Enter another number: "))
print(a / b)
except ZeroDivisionError:
print("Cannot divide by zero!")
except ValueError:
print("Invalid input! Enter integers only.")

• Q4. Write a custom exception in Python.

python
CopyEdit
class NegativeError(Exception):
pass

def check_number(x):
if x < 0:
raise NegativeError("Negative not allowed")
else:
print("Positive number:", x)

check_number(5)

• Q5. What is an assert statement? Give an example.

6️⃣ Tkinter (GUI Programming) Questions

Theory
• Q1. What is Tkinter? Why is it used?
• Q2. What are widgets in Tkinter? Name any 5 widgets.
• Q3. Program to create a simple Tkinter window with a button and label.

python
CopyEdit
import tkinter as tk

def clicked():
lbl.config(text="Button was clicked!")

root = tk.Tk()
root.title("Simple Window")
lbl = tk.Label(root, text="Hello")
lbl.pack()

btn = tk.Button(root, text="Click Me", command=clicked)


btn.pack()

root.mainloop()

• **Q4. Differentiate between pack(), grid(), and place().


• Q5. Write a program to create a login form with two Entry fields (username & password).

7️⃣ Python Libraries Overview (Theory Only)


• Q1. List libraries used for Data Science in Python. ➔ NumPy, Pandas, Matplotlib, Scikit-
learn, TensorFlow, Keras, Seaborn.
• Q2. Match the library to its use:
o NumPy ➔ Numerical computation
o Pandas ➔ Data analysis
o Matplotlib ➔ Plotting graphs
o Scikit-learn ➔ Machine learning
o TensorFlow ➔ Deep learning
o NLTK ➔ Natural language processing

Answers

✅ 1️⃣ NumPy (Numerical Python)

Q1. What is NumPy? Why is it faster than lists?

• Answer:
o NumPy is a Python library for fast numerical computation.
o It is faster than lists because:
▪ It uses vectorized operations (no for loops).
▪ It stores data in contiguous memory blocks (C language level speed).
▪ It supports broadcasting, multi-dimensional arrays, and mathematical
functions.

Q2. How to create arrays?


python
CopyEdit
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr)

• Output:
[1 2 3 4 5]

Q3. Differences: zeros(), ones(), full(), eye()

Function Description Example

np.zeros((2,3)) Array of zeros [[0. 0. 0.], [0. 0. 0.]]

np.ones((2,2)) Array of ones [[1. 1.], [1. 1.]]

np.full((2,2), 7) Filled with specific value [[7 7], [7 7]]

np.eye(3) Identity matrix [[1 0 0], [0 1 0], [0 0 1]]

Q4. Program to reshape 1D to 3x3


python
CopyEdit
import numpy as np
arr = np.arange(1, 10)
arr = arr.reshape(3, 3)
print(arr)

• Output:

lua
CopyEdit
[[1 2 3]
[4 5 6]
[7 8 9]]

Q5. Indexing and slicing


python
CopyEdit
arr = np.array([10, 20, 30, 40, 50])
print(arr[2]) # Output: 30
print(arr[1:4]) # Output: [20 30 40]
print(arr[::-1]) # Output: [50 40 30 20 10]

Q6. File Operations in NumPy

Function Purpose

np.save('file.npy', arr) Save array in binary file

np.load('file.npy') Load array from binary

np.savetxt('file.csv', arr, delimiter=',') Save array in text/csv

np.loadtxt('file.csv', delimiter=',') Load text/csv file

✅ 2️⃣ Pandas (Data Handling)

Q1. What is Pandas? What are Series and DataFrame?

• Answer:
o Pandas is used for data manipulation and analysis.
o Series: 1D labeled array.
o DataFrame: 2D table (rows and columns).

Q2. Program to create a DataFrame


python
CopyEdit
import pandas as pd
data = {'Name': ['A', 'B'], 'Age': [20, 25]}
df = pd.DataFrame(data)
print(df)

Q3. What is pivot_table()?

• Answer:
o It reshapes the table by summarizing data.
o Example:

python
CopyEdit
df.pivot_table(values='Sales', index='Date', columns='Product',
fill_value=0)

Q4. Handling Missing Data


python
CopyEdit
df.dropna() # Remove missing rows
df.fillna(0) # Fill missing values with 0
df.interpolate() # Fill missing values using interpolation

Q5. Merge two DataFrames


python
CopyEdit
import pandas as pd
df1 = pd.DataFrame({'ID': [1,2], 'Name': ['John','Jane']})
df2 = pd.DataFrame({'ID': [2,3], 'Marks': [90,80]})
df = pd.merge(df1, df2, on="ID", how="inner")
print(df)

• Output:

css
CopyEdit
ID Name Marks
0 2 Jane 90

✅ 3️⃣ Matplotlib (Plotting)

Q1. What is Matplotlib?

• Answer:
o A library used for creating graphs (line, bar, scatter, pie).
o Helps in data visualization.

Q2. Different plot types

Function Plot Type

plot() Line chart

bar() Bar graph

scatter() Scatter plot


Function Plot Type

pie() Pie chart

Q3. Simple line plot


python
CopyEdit
import matplotlib.pyplot as plt
x = [1, 2, 3]
y = [4, 5, 6]
plt.plot(x, y)
plt.show()

Q4. Bar Chart


python
CopyEdit
import matplotlib.pyplot as plt
x = ['A', 'B', 'C']
y = [10, 20, 30]
plt.bar(x, y)
plt.show()

✅ 4️⃣ File Handling

Q1. What is file handling?

• Answer:
o Managing files: open, read, write, close files permanently stored on disk.

Q2. File modes

Mode Meaning

r Read

w Write

a Append

x Create
Q3. Write and read file
python
CopyEdit
# Write
with open("file.txt", "w") as f:
f.write("Hello!")

# Read
with open("file.txt", "r") as f:
print(f.read())

Q4. seek() and tell()


python
CopyEdit
with open("file.txt", "r") as f:
print(f.tell()) # Position in file
f.seek(2) # Move to 2nd character
print(f.read()) # Read from there

Q5. Delete file


python
CopyEdit
import os
if os.path.exists("file.txt"):
os.remove("file.txt")

✅ 5️⃣ Exception Handling

Q1. What are exceptions?

• Answer:
o Exceptions occur during program execution (e.g., divide by zero).

Q2. try-except-finally Example


python
CopyEdit
try:
x = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
finally:
print("Always runs!")
Q3. Handle ZeroDivisionError and ValueError
python
CopyEdit
try:
a = int(input())
b = int(input())
print(a / b)
except ZeroDivisionError:
print("Can't divide by zero!")
except ValueError:
print("Invalid input!")

Q4. Custom Exception


python
CopyEdit
class NegativeError(Exception):
pass

def check(x):
if x < 0:
raise NegativeError("Negative numbers not allowed")

check(5)

Q5. assert statement


python
CopyEdit
def avg(marks):
assert len(marks) != 0, "Marks cannot be empty"
return sum(marks)/len(marks)

print(avg([80, 90]))

✅ 6️⃣ Tkinter (GUI)

Q1. What is Tkinter?

• Answer:
o Tkinter is Python's standard library for creating GUI windows and buttons.

Q2. Name 5 widgets

• Answer: Label, Button, Entry, Checkbutton, Frame.


Q3. Program for Window with Button & Label
python
CopyEdit
import tkinter as tk

def clicked():
lbl.config(text="Clicked!")

root = tk.Tk()
lbl = tk.Label(root, text="Hello")
lbl.pack()
btn = tk.Button(root, text="Click me", command=clicked)
btn.pack()
root.mainloop()

Q4. pack() vs grid() vs place()

Method Description

pack() Stack widgets vertically/horizontally

grid() Place widgets in a table-like structure (rows & columns)

place() Place widgets at exact coordinates

Q5. Login form program


python
CopyEdit
import tkinter as tk

root = tk.Tk()

tk.Label(root, text="Username").pack()
username = tk.Entry(root)
username.pack()

tk.Label(root, text="Password").pack()
password = tk.Entry(root, show="*")
password.pack()

tk.Button(root, text="Login").pack()

root.mainloop()

✅ 7️⃣ Python Libraries Overview


Q1. Libraries for Data Science

• NumPy: Numerical operations


• Pandas: Data manipulation
• Matplotlib: Visualization
• Seaborn: Statistical plots
• Scikit-learn: Machine learning
• TensorFlow: Deep learning
• NLTK: Text processing

Q2. Matching

Library Usage

NumPy Fast arrays

Pandas DataFrames

Matplotlib Graphs

Scikit-learn ML algorithms

TensorFlow Neural networks

NLTK NLP tasks

📚 DONE!

You might also like