-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPythonQ3.html
More file actions
332 lines (289 loc) Β· 11.8 KB
/
PythonQ3.html
File metadata and controls
332 lines (289 loc) Β· 11.8 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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Question 3 - Python</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<main>
<a href="python.html" class="back-link">β Back to Python List</a>
<h1>Question 3: CSV File Operations</h1>
<p>Write a menu-driven program to add and display records in a <b>CSV file</b> (<code>students.csv</code>) which
contains at least three student records with the following fields:</p>
<ul>
<li><code>name</code> (str)</li>
<li><code>class</code> (int)</li>
<li><code>roll</code> (int)</li>
<li><code>marks</code> (int)</li>
</ul>
<h2>Solution</h2>
<div class="solution-actions">
<a href="https://www.online-python.com/lsFJPzTLjc" target="_blank" class="run-online-link">[Run Online]</a>
<button class="action-btn copy-btn" onclick="copySolution()">π Copy Solution</button>
<button class="action-btn download-btn" onclick="downloadSolution()">πΎ Download as TXT</button>
<button class="action-btn toggle-btn" onclick="toggleComments()">π¬ Hide Comments</button>
<button class="action-btn version-btn" onclick="toggleVersion()">π 3 Inputs at Once</button>
</div>
<pre><code id="solution-code">
# Question 3:
# Write a program to manage student records using CSV file.
# The program should allow user to add new student records
# (Name, Class, Roll No, Marks) and display all records.
import csv
# Function to add a new student record
def add_record():
with open("students.csv", "a", newline="") as f:
writer = csv.writer(f)
name = input("Enter Name: ")
clas = int(input("Enter Class: "))
roll = int(input("Enter Roll No: "))
marks = int(input("Enter Marks: "))
writer.writerow([name, clas, roll, marks])
print("Record added successfully!")
# Function to display all student records
def display_records():
try:
with open('students.csv', 'r') as f:
reader = csv.reader(f)
print("\n--- Raw CSV Output ---")
# Printing the Header
print("Name,Class,Roll,Marks")
print("-" * 25)
for row in reader:
# 'row' is a list like ['Rahul', '12', '1', '95']
# ','.join(row) sticks them together with commas
print(",".join(row))
except FileNotFoundError:
print("File not found! Add a record first.")
# Main Menu
while True:
print("\n--- Student Management System ---")
print("1. Add Student Record")
print("2. Display All Records")
print("3. Exit")
choice = input("Enter your choice (1-3): ")
if choice == "1":
add_record()
elif choice == "2":
display_records()
elif choice == "3":
print("Exiting program. Goodbye!")
break
else:
print("Invalid choice! Please try again.")
</code></pre>
<!-- Version 2: 3 inputs at once (hidden by default) -->
<pre style="display: none;"><code id="solution-code-v2">
# Question 3:
# Write a program to manage student records using CSV file.
# The program should allow user to add 3 student records at once
# (Name, Class, Roll No, Marks) and display all records.
import csv
# Function to add 3 student records at once
def add_record():
with open("students.csv", "a", newline="") as f:
writer = csv.writer(f)
for i in range(1, 4):
print(f"\n--- Enter details for Student {i} ---")
name = input("Enter Name: ")
clas = int(input("Enter Class: "))
roll = int(input("Enter Roll No: "))
marks = int(input("Enter Marks: "))
writer.writerow([name, clas, roll, marks])
print(f"Record {i} added successfully!")
print("\nAll 3 records have been added!")
# Function to display all student records
def display_records():
try:
with open('students.csv', 'r') as f:
reader = csv.reader(f)
print("\n--- Raw CSV Output ---")
# Printing the Header
print("Name,Class,Roll,Marks")
print("-" * 25)
for row in reader:
# 'row' is a list like ['Rahul', '12', '1', '95']
# ','.join(row) sticks them together with commas
print(",".join(row))
except FileNotFoundError:
print("File not found! Add a record first.")
# Main Menu
while True:
print("\n--- Student Management System ---")
print("1. Add Student Record")
print("2. Display All Records")
print("3. Exit")
choice = input("Enter your choice (1-3): ")
if choice == "1":
add_record()
elif choice == "2":
display_records()
elif choice == "3":
print("Exiting program. Goodbye!")
break
else:
print("Invalid choice! Please try again.")
</code></pre>
<!-- Simple Solution Dropdown -->
<details class="simple-solution-dropdown">
<summary>π Simple Solution (Click to expand)</summary>
<pre><code id="solution-code-simple">
import csv
def add_record():
name = input("Name: ")
cls = input("Class: ")
roll = int(input("Roll No: "))
marks = int(input("Marks: "))
with open("students.csv", "a", newline="") as fh:
csv.writer(fh).writerow([name, cls, roll, marks])
def display():
print("Start >----------")
with open("students.csv", "r") as fh:
for rec in csv.reader(fh):
print(rec)
print("End >----------")
def menu():
while True:
print("1.Add Record | 2.Display | 3.Exit")
ch = int(input("Enter your choice: "))
if ch == 1:
add_record()
elif ch == 2:
display()
elif ch == 3:
break
else:
print("Something went wrong")
menu()
</code></pre>
</details>
</main>
<footer>
<p>CS10 Laboratory</p>
</footer>
<script>
// Copy solution to clipboard
function copySolution() {
const code = document.getElementById('solution-code').textContent;
navigator.clipboard.writeText(code).then(() => {
const btn = document.querySelector('.copy-btn');
const originalText = btn.textContent;
btn.textContent = 'β
Copied!';
setTimeout(() => {
btn.textContent = originalText;
}, 2000);
}).catch(err => {
alert('Failed to copy: ' + err);
});
}
// Download question and solution as TXT
function downloadSolution() {
// Get the question text
const questionTitle = document.querySelector('h1').textContent;
const questionDesc = document.querySelector('main > p').textContent;
// Format question as comments
const questionComment = `# Question: ${questionTitle}\n# ${questionDesc}\n\n`;
// Get the solution code
const solutionCode = document.getElementById('solution-code').textContent;
// Combine question and solution
const fullContent = questionComment + solutionCode;
// Create and trigger download
const blob = new Blob([fullContent], { type: 'text/plain' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'PythonQ3_Solution.txt';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
}
// Toggle comments visibility
let commentsVisibleV1 = true;
let commentsVisibleV2 = true;
let originalCodeV1 = null;
let originalCodeV2 = null;
function toggleComments() {
// Determine which version is currently visible
const codeElementV1 = document.getElementById('solution-code');
const codeElementV2 = document.getElementById('solution-code-v2');
const btn = document.querySelector('.toggle-btn');
// Check which version is currently displayed
const isV2Visible = codeElementV2.parentElement.style.display !== 'none';
const codeElement = isV2Visible ? codeElementV2 : codeElementV1;
const commentsVisible = isV2Visible ? commentsVisibleV2 : commentsVisibleV1;
const originalCode = isV2Visible ? originalCodeV2 : originalCodeV1;
if (commentsVisible) {
// Save original code
if (originalCode === null) {
if (isV2Visible) {
originalCodeV2 = codeElement.innerHTML;
} else {
originalCodeV1 = codeElement.innerHTML;
}
}
// Hide comments - process line by line
const lines = codeElement.textContent.split('\n');
const processedLines = lines.map(line => {
const trimmed = line.trim();
// Check if line is a comment (starts with #)
if (trimmed.startsWith('#')) {
return '<span class="comment-line comment-hidden">' + escapeHtml(line) + '</span>';
}
return escapeHtml(line);
});
codeElement.innerHTML = processedLines.join('\n');
btn.textContent = 'π¬ Show Comments';
if (isV2Visible) {
commentsVisibleV2 = false;
} else {
commentsVisibleV1 = false;
}
} else {
// Restore original code
const savedCode = isV2Visible ? originalCodeV2 : originalCodeV1;
codeElement.innerHTML = savedCode;
btn.textContent = 'π¬ Hide Comments';
if (isV2Visible) {
commentsVisibleV2 = true;
} else {
commentsVisibleV1 = true;
}
}
}
function escapeHtml(text) {
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}
// Toggle between single input and 3 inputs at once versions
let isVersion2 = false;
function toggleVersion() {
const preV1 = document.getElementById('solution-code').parentElement;
const preV2 = document.getElementById('solution-code-v2').parentElement;
const btn = document.querySelector('.version-btn');
const toggleBtn = document.querySelector('.toggle-btn');
if (!isVersion2) {
// Switch to version 2 (3 inputs at once)
preV1.style.display = 'none';
preV2.style.display = 'block';
btn.textContent = 'π 1 Input at a Time';
isVersion2 = true;
// Update toggle button to reflect V2's comment state
toggleBtn.textContent = commentsVisibleV2 ? 'π¬ Hide Comments' : 'π¬ Show Comments';
} else {
// Switch back to version 1 (single input)
preV1.style.display = 'block';
preV2.style.display = 'none';
btn.textContent = 'π 3 Inputs at Once';
isVersion2 = false;
// Update toggle button to reflect V1's comment state
toggleBtn.textContent = commentsVisibleV1 ? 'π¬ Hide Comments' : 'π¬ Show Comments';
}
}
</script>
<script src="script.js"></script>
</body>
</html>