-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPythonQ4.html
More file actions
334 lines (291 loc) Β· 11.6 KB
/
PythonQ4.html
File metadata and controls
334 lines (291 loc) Β· 11.6 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
333
334
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Question 4 - 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 4: Binary File Operations</h1>
<p>Write a menu-driven program to add and display records in a <b>binary file</b> which contains at least three
product records with the following fields:</p>
<ul>
<li><code>pname</code> (str)</li>
<li><code>price</code> (float)</li>
<li><code>qty</code> (int)</li>
</ul>
<h2>Solution</h2>
<div class="solution-actions">
<a href="https://www.online-python.com/RuJSklUEgp" 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">
# Q4. Write a program to create a binary file 'products.dat' using pickle module.
# The program should have a menu with options to:
# 1. Add a new product (with product name, price, and quantity)
# 2. Display all products stored in the file
# 3. Exit the program
import pickle
# Function to add a new record
def add_record():
# 'ab' opens for appending; it creates the file if it doesn't exist
with open("products.dat", "ab") as f:
pname = input("Enter Product Name: ")
price = float(input("Enter Price: "))
qty = int(input("Enter Quantity: "))
record = [pname, price, qty]
pickle.dump(record, f)
print("Product added successfully!")
# Function to display all records
def display_records():
print("\n--- Product List ---")
print('Product Name',",",'Price,',",",'Quantity')
print("-" * 40)
try:
with open("products.dat", "rb") as f:
while True:
try:
rec = pickle.load(f)
print(rec[0],",",rec[1],",",rec[2])
except EOFError:
break
except FileNotFoundError:
print("Error: The file does not exist yet. Add a record first!")
# --- Main Menu ---
while True:
print("\n1. Add Product")
print("2. Display All Products")
print("3. Exit")
choice = input("Enter choice (1-3): ")
if choice == "1":
add_record()
elif choice == "2":
display_records()
elif choice == "3":
print("Exiting...")
break
else:
print("Invalid choice!")
</code></pre>
<!-- Version 2: 3 inputs at once (hidden by default) -->
<pre style="display: none;"><code id="solution-code-v2">
# Q4. Write a program to create a binary file 'products.dat' using pickle module.
# The program should have a menu with options to:
# 1. Add 3 products at once (with product name, price, and quantity)
# 2. Display all products stored in the file
# 3. Exit the program
import pickle
# Function to add 3 records at once
def add_record():
# 'ab' opens for appending; it creates the file if it doesn't exist
with open("products.dat", "ab") as f:
for i in range(1, 4):
print(f"\n--- Enter details for Product {i} ---")
pname = input("Enter Product Name: ")
price = float(input("Enter Price: "))
qty = int(input("Enter Quantity: "))
record = [pname, price, qty]
pickle.dump(record, f)
print(f"Product {i} added successfully!")
print("\nAll 3 products have been added!")
# Function to display all records
def display_records():
print("\n--- Product List ---")
print('Product Name',",",'Price,',",",'Quantity')
print("-" * 40)
try:
with open("products.dat", "rb") as f:
while True:
try:
rec = pickle.load(f)
print(rec[0],",",rec[1],",",rec[2])
except EOFError:
break
except FileNotFoundError:
print("Error: The file does not exist yet. Add a record first!")
# --- Main Menu ---
while True:
print("\n1. Add Product")
print("2. Display All Products")
print("3. Exit")
choice = input("Enter choice (1-3): ")
if choice == "1":
add_record()
elif choice == "2":
display_records()
elif choice == "3":
print("Exiting...")
break
else:
print("Invalid choice!")
</code></pre>
<!-- Simple Solution Dropdown -->
<details class="simple-solution-dropdown">
<summary>π Simple Solution (Click to expand)</summary>
<pre><code id="solution-code-simple">
import pickle
def add_record():
pname = input("Product Name: ")
price = float(input("Price: "))
qty = int(input("Quantity: "))
rec = [pname, price, qty]
with open("products.dat", "ab+") as fh:
pickle.dump(rec, fh)
def display():
print("Start >----------")
with open("products.dat", "rb+") as fh:
try:
while True:
data = pickle.load(fh)
print(data)
except Exception:
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("Somthing went wromg")
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 = 'PythonQ4_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>