Python Question Bank
Python Question Bank
Theory
python
CopyEdit
import numpy as np
arr = np.array([1, 2, 3, 4])
print(arr)
python
CopyEdit
arr = np.arange(1, 10)
new_arr = arr.reshape(3, 3)
print(new_arr)
Theory
python
CopyEdit
import pandas as pd
data = {'Name': ['A', 'B'], 'Age': [20, 25]}
df = pd.DataFrame(data)
print(df)
Theory
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()
python
CopyEdit
x = ['A', 'B', 'C']
y = [30, 50, 70]
plt.bar(x, y)
plt.title('Bar Chart')
plt.show()
Theory
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)
python
CopyEdit
import os
if os.path.exists("testfile.txt"):
os.remove("testfile.txt")
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.")
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)
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()
root.mainloop()
Answers
• 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.
• Output:
[1 2 3 4 5]
• Output:
lua
CopyEdit
[[1 2 3]
[4 5 6]
[7 8 9]]
Function Purpose
• Answer:
o Pandas is used for data manipulation and analysis.
o Series: 1D labeled array.
o DataFrame: 2D table (rows and columns).
• 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)
• Output:
css
CopyEdit
ID Name Marks
0 2 Jane 90
• Answer:
o A library used for creating graphs (line, bar, scatter, pie).
o Helps in data visualization.
• Answer:
o Managing files: open, read, write, close files permanently stored on disk.
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())
• Answer:
o Exceptions occur during program execution (e.g., divide by zero).
def check(x):
if x < 0:
raise NegativeError("Negative numbers not allowed")
check(5)
print(avg([80, 90]))
• Answer:
o Tkinter is Python's standard library for creating GUI windows and buttons.
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()
Method Description
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()
Q2. Matching
Library Usage
Pandas DataFrames
Matplotlib Graphs
Scikit-learn ML algorithms
📚 DONE!