1. File Handling¶
Q1. Log File Analyzer¶
In [ ]:
with open("log.txt", "w") as f:
f.write("""System started successfully
User logged in
ERROR: Invalid password
Connection established
ERROR: Database not found
User logged out
ERROR: Timeout occurred
System shutdown""")
In [ ]:
error_count = 0
with open("log.txt", "r") as f:
with open("errors.txt", "w") as out:
for line in f:
if "ERROR" in line:
error_count += 1
out.write(line)
print("Total errors:", error_count)
Total errors: 3
Q2. Student Record Cleaner¶
In [ ]:
with open("students.txt", "w") as f:
f.write("""Alice,85
Bob,abc
Charlie,90
David,78
Eva,9O
Frank,100
Grace,seven
Helen,88""")
In [ ]:
with open("students.txt", "r") as f:
with open("cleaned.txt", "w") as out:
for line in f:
name, mark = line.strip().split(",")
if mark.isdigit(): # checks if all characters are numbers
out.write(line)
Q3. Append vs Write Demonstration¶
In [ ]:
# Step 1 — Create data.txt
with open("data.txt", "w") as f:
f.write("Python\nJava\nC++")
# Step 2 — Append
with open("data.txt", "a") as f:
f.write("\nJavaScript")
print("After append:")
with open("data.txt") as f:
print(f.read())
# Step 3 — Overwrite
with open("data.txt", "w") as f:
f.write("JavaScript")
print("\nAfter write:")
with open("data.txt") as f:
print(f.read())
After append: Python Java C++ JavaScript After write: JavaScript
2. Modules & PIP¶
Q4. stats.py Module¶
stats.py
def mean(numbers):
return sum(numbers) / len(numbers)
def maximum(numbers):
return max(numbers)
def minimum(numbers):
return min(numbers)
In [ ]:
with open("stats.py", "w") as f:
f.write("""
def mean(numbers):
return sum(numbers) / len(numbers)
def maximum(numbers):
return max(numbers)
def minimum(numbers):
return min(numbers)
""")
In [ ]:
import stats
data = [12, 45, 23, 67, 34]
print("Mean:", stats.mean(data))
print("Max:", stats.maximum(data))
print("Min:", stats.minimum(data))
Mean: 36.2 Max: 67 Min: 12
Q5. Namespace Conflict¶
mathops.py
def add(a, b):
return a + b
stringops.py
def add(a, b):
return a + b
In [ ]:
with open("mathops.py", "w") as f:
f.write("""
def add(a, b):
return a + b
""")
with open("stringops.py", "w") as f:
f.write("""
def add(a, b):
return a + b
""")
In [ ]:
import mathops as m
import stringops as s
print(m.add(10, 5)) # 15
print(s.add("Hello ", "World")) # Hello World
15 Hello World
Q6. External Package Example (using camelcase)¶
In [ ]:
!pip install camelcase
Requirement already satisfied: camelcase in /usr/local/lib/python3.12/dist-packages (0.2)
In [ ]:
import camelcase
c = camelcase.CamelCase()
print(c.hump("python is very powerful"))
Python is Very Powerful
3. Introduction to Numpy¶
Q7. Marks Matrix¶
In [ ]:
import numpy as np
marks = np.array([
[80, 70, 90, 60],
[75, 85, 95, 65],
[60, 70, 80, 90]
])
print("2nd student:", marks[1])
print("Subject 3:", marks[:, 2])
print("Highest mark:", np.max(marks))
2nd student: [75 85 95 65] Subject 3: [90 95 80] Highest mark: 95
Q8. Slice Even Positions¶
In [ ]:
arr = np.array([10, 20, 30, 40, 50, 60, 70])
print(arr[1::2])
[20 40 60]
Q9. Copy vs Slice¶
In [ ]:
arr = np.array([10, 20, 30, 40])
copy_arr = arr.copy()
slice_arr = arr[1:3]
arr[1] = 99
print(arr) # [10 99 30 40]
print(copy_arr) # unchanged
print(slice_arr) # changed because slice is a view\
[10 99 30 40] [10 20 30 40] [99 30]
4. Introduction to Matplotlib¶
Q10. Weekly Temperature Plot¶
In [ ]:
import matplotlib.pyplot as plt
import numpy as np
temps = np.array([22, 24, 19, 23, 25, 21, 20])
days = np.array([1,2,3,4,5,6,7])
plt.plot(days, temps)
plt.title("Weekly Temperature")
plt.xlabel("Day")
plt.ylabel("Temperature")
plt.show()
Q11. Compare Two Students¶
In [ ]:
import matplotlib.pyplot as plt
import numpy as np
A = np.array([70, 75, 80, 85])
B = np.array([60, 65, 78, 88])
x = np.array([1, 2, 3, 4])
plt.plot(x, A)
plt.plot(x, B)
plt.title("Student Performance")
plt.xlabel("Test")
plt.ylabel("Marks")
plt.show()
Q12. Debugging the Graph¶
Wrong Code
x = np.array([1, 2, 3, 4])
y = np.array([10, 20, 30])
plt.plot(x, y)
Error: x and y must be the same length
In [ ]:
x = np.array([1, 2, 3])
y = np.array([10, 20, 30])
plt.plot(x, y)
plt.show()
Q13. Kinematics¶
In [ ]:
import matplotlib.pyplot as plt
import numpy as np
time = np.array([1,2,3,4])
speed = np.array([10,20,30,40])
distance = np.array([10,40,90,160])
plt.subplot(2,1,1)
plt.plot(time, speed)
plt.title("Speed vs Time")
plt.subplot(2,1,2)
plt.plot(time, distance)
plt.title("Distance vs Time")
plt.tight_layout()
plt.show()
Bonus: Mixed File Analyzer¶
In [ ]:
with open("mixed.txt", "w") as f:
f.write("""ERROR Disk full
User login
75
ERROR Network down
hello
100
ERROR Access denied
42""")
In [ ]:
with open("mixed.txt", "r") as f, \
open("errors.txt", "w") as e, \
open("numbers.txt", "w") as n:
for line in f:
line = line.strip()
if "ERROR" in line:
e.write(line + "\n")
elif line.isdigit():
n.write(line + "\n")
In [ ]:
import matplotlib.pyplot as plt
import numpy as np
xpoints = np.array([0, 6])
ypoints = np.array([0, 250])
plt.plot(xpoints, ypoints)
plt.show()
In [ ]:
import matplotlib.pyplot as plt
import numpy as np
xpoints = np.array([1, 8])
ypoints = np.array([3, 10])
plt.plot(xpoints, ypoints, 'o')
plt.show()
In [ ]:
import matplotlib.pyplot as plt
import numpy as np
xpoints = np.array([1, 2, 6, 8])
ypoints = np.array([3, 8, 1, 10])
plt.plot(xpoints, ypoints,"o")
plt.show()
In [ ]:
import matplotlib.pyplot as plt
import numpy as np
ypoints = np.array([3, 8, 1, 10, 5, 7])
plt.plot(ypoints)
plt.show()
In [ ]:
import matplotlib.pyplot as plt
import numpy as np
x = np.array([1,2,3,4])
temp = np.array([22, 24, 19, 23])
sales = np.array([200, 300, 250, 400])
plt.subplot(2, 1, 1)
plt.plot(x, temp)
plt.title("Temperature")
plt.subplot(2, 1, 2)
plt.plot(x, sales)
plt.title("Sales")
plt.tight_layout()
plt.show()
In [ ]: