-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathday30_speakPython19.py
More file actions
268 lines (189 loc) Β· 6.76 KB
/
Copy pathday30_speakPython19.py
File metadata and controls
268 lines (189 loc) Β· 6.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
"""π§ Day 30 β Speak Python 19
Phase 6: Balanced Learning (Functions + OOP + File Handling)
Focus Areas:
Β» Functions deep dive (default parameters, *args, **kwargs, scope)
Β» OOP β Level 2 (class vs instance attributes, __init__ logic, multiple objects)
Β» File handling (read / write / save data)
Β» Building a small real-world mini project (Student Manager)
Β» Debugging common OOP / function bugs"""
"""β
Problem 1: Functions β Stats with *args
π Task:
Write a function that accepts unlimited numbers (*args) and returns a dictionary with sum, average, max, min.
π Example:
stats(2, 5, 7, 1) β {"sum":15, "avg":3.75, "max":7, "min":1}
π‘ Hint:
Handle the case when no arguments are given (return None or an informative message)."""
# def stats(*args):
# if not args:
# return None
# else:
# d = {
# "sum":sum(args),
# "avg":sum(args) / len(args),
# "max":max(args),
# "min":min(args)
# }
# return d
# print(stats(2, 5, 7, 1))
# print(stats(8, 7, 2, 89))
# print(stats())
"""β
Problem 2: Functions β Default params + **kwargs
π Task:
Write a greet(name, greeting="Hello", **kwargs) function that returns a formatted greeting. Use **kwargs to accept optional details (e.g., title="Mr.", lang="bn").
π Example:
greet("Jisan") β "Hello, Jisan!"
greet("Jisan", greeting="Hi", title="Mr.") β "Hi, Mr. Jisan!"
π‘ Hint:
Check for title in kwargs and prepend it if present. Use default greeting when none provided."""
# def greet(name, greeting="Hello", **kwargs):
# title = kwargs.get("title", "")
# if title:
# return f"{greeting}, {title} {name}!"
# return f"{greeting}, {name}!"
# print(greet("Jisan"))
# print(greet("Jisan", greeting="Hi", title="Mr."))
# print(greet("Sonnic", greeting="Welcome", title="Dr."))
"""β
Problem 3: OOP β Student Class (Level 2)
π Task:
Create a Student class with:
attributes: name, age, grade
method: get_details() β returns a details string
method: is_passed() β returns True if grade >= 40 else False
π Example:
s = Student("Jisan", 20, 85)
s.get_details() β "Name: Jisan, Age: 20, Grade: 85"
s.is_passed() β True
π‘ Hint:
Use __init__ to set attributes. Keep grade numeric."""
# class Student:
# def __init__(self, name, age, grade):
# self.name = name
# self.age = age
# self.grade = grade
# def get_details(self):
# print(f"Name: {self.name}, Age: {self.age}, Grade: {self.grade}")
# def is_passed(self):
# return self.grade >= 40
# s = Student("Jisan", 20, 85)
# s.get_details()
# s.is_passed()
"""β
Problem 4: File Handling β Save & Load Students
π Task:
Write two functions:
save_students(filename, students_list) β saves students (one per line, e.g. name|age|grade)
load_students(filename) β reads file and returns a list of Student objects
π Example file students.txt:
Jisan|20|85
Rafi|19|72
load_students("students.txt") β [Student("Jisan",20,85), Student("Rafi",19,72)]
π‘ Hint:
Use str.split("|") to parse each line. Handle missing file with try/except."""
def save_students(filename, students_list):
with open(filename, "a") as f:
for student in students_list:
f.write(f"{student}\n")
def load_students(filename):
students_list = []
try:
with open(filename, "r") as f:
data = f.readlines()
students_list = []
for student in data:
nag = student.replace("\n", "").split("|")
students_list.append((f"Student{nag[0], nag[1], nag[2]}"))
return students_list
except FileNotFoundError:
return []
return students_list
# save_students("students.txt", ["Jisan|20|93", "Rafi|19|83"])
# print(load_students("students.txt"))
"""βοΈ Mini Project β Student Management System (OOP + File)
π Task:
Build a StudentManager class that can:
add a student (add_student(name, age, grade))
list all students (list_students())
compute average grade (average_grade())
save to file (save(filename)) and load from file (load(filename))
π Example usage:
mgr = StudentManager()
mgr.add_student("Jisan",20,85)
mgr.add_student("Rafi",19,72)
mgr.list_students()
mgr.average_grade() β 78.5
mgr.save("students.txt")
π‘ Hint:
Internally keep a list of Student objects. Reuse save_students / load_students functions from Problem 4."""
class Student:
def __init__(self, name, age, grade):
self.name = name
self.age = age
self.grade = grade
def get_detalis(self):
return f"Name: {self.name}, Age: {self.age}, Grade: {self.grade}"
def save_students(filename, students_list):
with open(filename, "w") as f:
for student in students_list:
f.write(f"{student.name}|{student.age}|{student.grade}\n")
def load_students(filename):
students_list = []
try:
with open(filename, "r") as f:
for line in f:
name, age, grade = line.strip().split("|")
students_list.append(Student(name, int(age), int(grade)))
return students_list
except FileNotFoundError:
return []
return students_list
class StudentManager:
def __init__(self):
self.students = []
def add_student(self, name, age, grade):
self.students.append(Student(name, age, grade))
def list_students(self):
for student in self.students:
print(student.get_detalis())
def average_grade(self):
if not self.students:
return 0
return sum(s.grade for s in self.students) / len(self.students)
def save(self, filename):
save_students(filename, self.students)
def load(self, filename):
self.students = load_students(filename)
mgr = StudentManager()
mgr.add_student("Jisan",20,85)
mgr.add_student("Rafi",19,72)
mgr.list_students()
mgr.average_grade()
mgr.save("students.txt")
mgr.save("updata.txt")
"""π Debugging Task β Fix the Code (OOP gotcha: class vs instance attribute)
β Wrong Code:
class School:
students = []
def add_student(self, name):
self.students.append(name)
s1 = School()
s2 = School()
s1.add_student("A")
s2.add_student("B")
print(s1.students) # β ["A", "B"]
print(s2.students) # β ["A", "B"]
β
Expected Behavior:
Each School() instance should have its own students list.
print(s1.students) β ["A"]
print(s2.students) β ["B"]
π Fix it: move students into __init__ as an instance attribute (self.students = [])."""
# β
Fixed code:
# class School:
# def __init__(self):
# self.students = []
# def add_student(self, name):
# self.students.append(name)
# s1 = School()
# s2 = School()
# s1.add_student("A")
# s2.add_student("B")
# print(s1.students)
# print(s2.students)