-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpython_learning_assistant.py
More file actions
540 lines (487 loc) · 20.7 KB
/
Copy pathpython_learning_assistant.py
File metadata and controls
540 lines (487 loc) · 20.7 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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
#!/usr/bin/env python3
"""
Python Learning Assistant for C# Developers
Based on: https://github.com/robch/python-for-csharp-devs
This interactive tool helps you navigate through 25 Python lessons designed
specifically for C# developers.
"""
import os
import json
from datetime import datetime
import urllib.request
import urllib.error
from rich.console import Console
from rich.markdown import Markdown
# Lesson structure from the repository
LESSONS = [
{
"number": 1,
"title": "Python Installation and Setup",
"url": "https://github.com/robch/python-for-csharp-devs/blob/main/learn-python-in-half-day-lesson-1.md",
"duration": "10 min",
"topics": [
"Install Python on your machine",
"Set up a Python development environment",
"Learn how to run Python scripts and interact with the Python interpreter"
]
},
{
"number": 2,
"title": "Basic Syntax and Indentation",
"url": "https://github.com/robch/python-for-csharp-devs/blob/main/learn-python-in-half-day-lesson-2.md",
"duration": "10 min",
"topics": [
"Understand Python's significant use of indentation for block structuring",
"Learn about statement terminators, comment syntax, and variable naming conventions",
"Explore Python's dynamic typing system"
]
},
{
"number": 3,
"title": "Data Types and Variables",
"url": "https://github.com/robch/python-for-csharp-devs/blob/main/learn-python-in-half-day-lesson-3.md",
"duration": "10 min",
"topics": [
"Learn about common data types like numbers, strings, lists, tuples, and dictionaries"
]
},
{
"number": 4,
"title": "Control Flow",
"url": "https://github.com/robch/python-for-csharp-devs/blob/main/learn-python-in-half-day-lesson-4.md",
"duration": "10 min",
"topics": [
"Understand Python's control flow statements: if-else, for loops, and while loops",
"Compare them to their C# counterparts"
]
},
{
"number": 5,
"title": "Functions",
"url": "https://github.com/robch/python-for-csharp-devs/blob/main/learn-python-in-half-day-lesson-5.md",
"duration": "10 min",
"topics": [
"Learn how to define and call functions in Python",
"Explore function arguments and return values"
]
},
{
"number": 6,
"title": "File I/O",
"url": "https://github.com/robch/python-for-csharp-devs/blob/main/learn-python-in-half-day-lesson-6.md",
"duration": "10 min",
"topics": [
"Read and write files using Python's file handling methods",
"Compare with C#'s file I/O"
]
},
{
"number": 7,
"title": "List Comprehensions",
"url": "https://github.com/robch/python-for-csharp-devs/blob/main/learn-python-in-half-day-lesson-7.md",
"duration": "10 min",
"topics": [
"Discover a powerful feature unique to Python for concise list operations"
]
},
{
"number": 8,
"title": "Dictionaries",
"url": "https://github.com/robch/python-for-csharp-devs/blob/main/learn-python-in-half-day-lesson-8.md",
"duration": "10 min",
"topics": [
"Understand Python dictionaries and their usage",
"Compare with C#'s dictionary or hash table data structure"
]
},
{
"number": 9,
"title": "Modules and Packages",
"url": "https://github.com/robch/python-for-csharp-devs/blob/main/learn-python-in-half-day-lesson-9.md",
"duration": "10 min",
"topics": [
"Learn how to organize code into modules and packages in Python"
]
},
{
"number": 10,
"title": "Classes and Objects",
"url": "https://github.com/robch/python-for-csharp-devs/blob/main/learn-python-in-half-day-lesson-10.md",
"duration": "10 min",
"topics": [
"Introduce classes and objects in Python",
"Compare with C#'s class-based approach"
]
},
{
"number": 11,
"title": "Exception Handling",
"url": "https://github.com/robch/python-for-csharp-devs/blob/main/learn-python-in-half-day-lesson-11.md",
"duration": "10 min",
"topics": [
"Explore Python's exception handling mechanism"
]
},
{
"number": 12,
"title": "Lambda Functions",
"url": "https://github.com/robch/python-for-csharp-devs/blob/main/learn-python-in-half-day-lesson-12.md",
"duration": "10 min",
"topics": [
"Understand anonymous functions using lambda expressions"
]
},
{
"number": 13,
"title": "Slicing and Indexing",
"url": "https://github.com/robch/python-for-csharp-devs/blob/main/learn-python-in-half-day-lesson-13.md",
"duration": "10 min",
"topics": [
"Learn about slicing and indexing in Python lists"
]
},
{
"number": 14,
"title": "Generators",
"url": "https://github.com/robch/python-for-csharp-devs/blob/main/learn-python-in-half-day-lesson-14.md",
"duration": "10 min",
"topics": [
"Introduce Python generators for lazy evaluation of sequences"
]
},
{
"number": 15,
"title": "Standard Library Overview",
"url": "https://github.com/robch/python-for-csharp-devs/blob/main/learn-python-in-half-day-lesson-15.md",
"duration": "10 min",
"topics": [
"Familiarize yourself with the extensive Python standard library"
]
},
{
"number": 16,
"title": "Third-Party Libraries and pip",
"url": "https://github.com/robch/python-for-csharp-devs/blob/main/learn-python-in-half-day-lesson-16.md",
"duration": "10 min",
"topics": [
"Learn how to install and use third-party libraries with pip",
"Understand the importance of virtual environments and how to create them"
]
},
{
"number": 17,
"title": "Pythonic Code and Idioms",
"url": "https://github.com/robch/python-for-csharp-devs/blob/main/learn-python-in-half-day-lesson-17.md",
"duration": "10 min",
"topics": [
"Discover Python-specific coding styles and idioms"
]
},
{
"number": 18,
"title": "Common Pitfalls",
"url": "https://github.com/robch/python-for-csharp-devs/blob/main/learn-python-in-half-day-lesson-18.md",
"duration": "10 min",
"topics": [
"Highlight common pitfalls and errors when transitioning from C# to Python"
]
},
{
"number": 19,
"title": "Practice Projects",
"url": "https://github.com/robch/python-for-csharp-devs/blob/main/learn-python-in-half-day-lesson-19.md",
"duration": "10 min",
"topics": [
"Start working on small projects to apply your knowledge and enhance your skills"
]
},
{
"number": 20,
"title": "Multi-Threading Basics",
"url": "https://github.com/robch/python-for-csharp-devs/blob/main/learn-python-in-half-day-lesson-20.md",
"duration": "10 min",
"topics": [
"Introduce the concept of multi-threading and its benefits",
"Learn how to create and manage threads in Python using the threading module",
"Discuss the Global Interpreter Lock (GIL) and its impact on multi-threading in Python"
]
},
{
"number": 21,
"title": "Thread Pools and Executors",
"url": "https://github.com/robch/python-for-csharp-devs/blob/main/learn-python-in-half-day-lesson-21.md",
"duration": "10 min",
"topics": [
"Learn about thread pools and how to use the concurrent.futures module"
]
},
{
"number": 22,
"title": "Synchronization and Thread Safety",
"url": "https://github.com/robch/python-for-csharp-devs/blob/main/learn-python-in-half-day-lesson-22.md",
"duration": "10 min",
"topics": [
"Understand the challenges of concurrent access in multi-threaded programs",
"Learn about thread synchronization techniques like locks, semaphores, and mutexes",
"Discuss thread safety and potential issues when sharing data between threads"
]
},
{
"number": 23,
"title": "Asynchronous Programming with Async/Await",
"url": "https://github.com/robch/python-for-csharp-devs/blob/main/learn-python-in-half-day-lesson-23.md",
"duration": "10 min",
"topics": [
"Introduce asynchronous programming and its advantages in I/O-bound tasks",
"Learn how to use async and await keywords to define and await asynchronous functions",
"Compare synchronous and asynchronous approaches for I/O-bound operations"
]
},
{
"number": 24,
"title": "Combining Threads and Async in Python",
"url": "https://github.com/robch/python-for-csharp-devs/blob/main/learn-python-in-half-day-lesson-24.md",
"duration": "10 min",
"topics": [
"Explore scenarios where multi-threading and asynchronous programming can be combined effectively",
"Discuss best practices and potential challenges when using both techniques together",
"Demonstrate an example of combining threads and async in a Python application"
]
},
{
"number": 25,
"title": "Performance Considerations with Threads and Async",
"url": "https://github.com/robch/python-for-csharp-devs/blob/main/learn-python-in-half-day-lesson-25.md",
"duration": "10 min",
"topics": [
"Compare the performance characteristics of multi-threading and asynchronous programming",
"Discuss the trade-offs between the two approaches in different scenarios",
"Explore tools and techniques to profile and optimize threaded and async code"
]
}
]
PROGRESS_FILE = os.path.expanduser("~/.python_learning_progress.json")
class LearningAssistant:
def __init__(self):
self.progress = self.load_progress()
self.console = Console()
self.content_cache = {} # Cache fetched markdown content
def load_progress(self):
"""Load learning progress from file"""
if os.path.exists(PROGRESS_FILE):
with open(PROGRESS_FILE, 'r') as f:
return json.load(f)
return {
"current_lesson": 1,
"completed_lessons": [],
"notes": {},
"start_date": datetime.now().isoformat()
}
def save_progress(self):
"""Save learning progress to file"""
with open(PROGRESS_FILE, 'w') as f:
json.dump(self.progress, f, indent=2)
def fetch_lesson_content(self, lesson_url):
"""Fetch markdown content from GitHub"""
# Check cache first
if lesson_url in self.content_cache:
return self.content_cache[lesson_url]
try:
# Convert GitHub blob URL to raw URL
raw_url = lesson_url.replace(
"github.com",
"raw.githubusercontent.com"
).replace("/blob/", "/")
# Fetch content
with urllib.request.urlopen(raw_url, timeout=10) as response:
content = response.read().decode('utf-8')
self.content_cache[lesson_url] = content
return content
except urllib.error.URLError as e:
return f"❌ Error fetching lesson content: {e}\n\nYou can view it online at:\n{lesson_url}"
except Exception as e:
return f"❌ Unexpected error: {e}\n\nYou can view it online at:\n{lesson_url}"
def show_dashboard(self):
"""Display learning dashboard"""
completed = len(self.progress["completed_lessons"])
total = len(LESSONS)
progress_pct = (completed / total) * 100
print("\n" + "="*60)
print("🐍 PYTHON LEARNING DASHBOARD (for C# Developers)")
print("="*60)
print(f"Progress: {completed}/{total} lessons ({progress_pct:.1f}%)")
print(f"Current Lesson: {self.progress['current_lesson']}")
if completed > 0:
print(f"Completed: {', '.join(map(str, sorted(self.progress['completed_lessons'])))}")
print("="*60 + "\n")
def show_lesson(self, lesson_num, show_content=True):
"""Display lesson details"""
if lesson_num < 1 or lesson_num > len(LESSONS):
print(f"❌ Invalid lesson number. Choose between 1 and {len(LESSONS)}")
return
lesson = LESSONS[lesson_num - 1]
is_completed = lesson_num in self.progress["completed_lessons"]
# Print lesson header
print("\n" + "="*60)
print(f"📚 Lesson {lesson['number']}: {lesson['title']}")
print("="*60)
print(f"Duration: {lesson['duration']}")
print(f"Status: {'✅ Completed' if is_completed else '⏳ Not Started'}")
print(f"\nTopics:")
for topic in lesson['topics']:
print(f" • {topic}")
# Show notes if available
if str(lesson_num) in self.progress.get("notes", {}):
print(f"\n📝 Your Notes:\n{self.progress['notes'][str(lesson_num)]}")
print("\n" + "="*60)
# Fetch and display content if requested
if show_content:
print(f"📖 Fetching lesson content from GitHub...")
content = self.fetch_lesson_content(lesson['url'])
print("\n" + "-"*60 + "\n")
# Render markdown using rich
md = Markdown(content)
self.console.print(md)
print("\n" + "-"*60)
else:
print(f"\n🔗 Lesson URL:\n{lesson['url']}")
print("="*60 + "\n")
def mark_complete(self, lesson_num):
"""Mark a lesson as complete"""
if lesson_num not in self.progress["completed_lessons"]:
self.progress["completed_lessons"].append(lesson_num)
self.progress["completed_lessons"].sort()
# Auto-advance to next lesson
if lesson_num == self.progress["current_lesson"] and lesson_num < len(LESSONS):
self.progress["current_lesson"] = lesson_num + 1
self.save_progress()
print(f"✅ Lesson {lesson_num} marked as complete!")
if lesson_num < len(LESSONS):
print(f"📚 Next up: Lesson {lesson_num + 1} - {LESSONS[lesson_num]['title']}")
else:
print("🎉 Congratulations! You've completed all lessons!")
else:
print(f"ℹ️ Lesson {lesson_num} was already marked as complete.")
def add_note(self, lesson_num, note):
"""Add a note for a specific lesson"""
if "notes" not in self.progress:
self.progress["notes"] = {}
self.progress["notes"][str(lesson_num)] = note
self.save_progress()
print(f"📝 Note added to Lesson {lesson_num}")
def list_all_lessons(self):
"""List all available lessons"""
print("\n" + "="*60)
print("📋 ALL LESSONS")
print("="*60)
for lesson in LESSONS:
status = "✅" if lesson['number'] in self.progress["completed_lessons"] else "⏳"
current = "👉" if lesson['number'] == self.progress['current_lesson'] else " "
print(f"{current} {status} Lesson {lesson['number']:2d}: {lesson['title']}")
print("="*60 + "\n")
def show_help(self):
"""Display help menu"""
print("\n" + "="*60)
print("📖 AVAILABLE COMMANDS")
print("="*60)
print(" dashboard - Show your learning progress")
print(" list - List all lessons")
print(" lesson <number> - View lesson with full content")
print(" current - View current lesson with content")
print(" next - Move to next lesson")
print(" complete <number> - Mark lesson as complete")
print(" note <number> <text>- Add a note to a lesson")
print(" reset - Reset all progress")
print(" help - Show this help menu")
print(" quit / exit - Exit the assistant")
print("="*60)
print("\nNote: Lesson content is fetched from GitHub and")
print("displayed inline with rich formatting.")
print("="*60 + "\n")
def reset_progress(self):
"""Reset all learning progress"""
confirm = input("⚠️ Are you sure you want to reset all progress? (yes/no): ")
if confirm.lower() == 'yes':
self.progress = {
"current_lesson": 1,
"completed_lessons": [],
"notes": {},
"start_date": datetime.now().isoformat()
}
self.save_progress()
print("✅ Progress reset successfully!")
else:
print("❌ Reset cancelled.")
def run(self):
"""Main interactive loop"""
print("\n🐍 Welcome to Python Learning Assistant for C# Developers!")
print("Based on: https://github.com/robch/python-for-csharp-devs")
print("Type 'help' for available commands\n")
self.show_dashboard()
while True:
try:
cmd = input("📚 > ").strip().lower()
if not cmd:
continue
parts = cmd.split(maxsplit=1)
command = parts[0]
if command in ['quit', 'exit']:
print("👋 Happy coding! Keep learning Python!")
break
elif command == 'help':
self.show_help()
elif command == 'dashboard':
self.show_dashboard()
elif command == 'list':
self.list_all_lessons()
elif command == 'current':
self.show_lesson(self.progress['current_lesson'])
elif command == 'next':
if self.progress['current_lesson'] < len(LESSONS):
self.progress['current_lesson'] += 1
self.save_progress()
self.show_lesson(self.progress['current_lesson'])
else:
print("🎉 You're already on the last lesson!")
elif command == 'lesson':
if len(parts) < 2:
print("❌ Usage: lesson <number>")
else:
try:
lesson_num = int(parts[1])
self.show_lesson(lesson_num)
except ValueError:
print("❌ Please provide a valid lesson number")
elif command == 'complete':
if len(parts) < 2:
print("❌ Usage: complete <number>")
else:
try:
lesson_num = int(parts[1])
self.mark_complete(lesson_num)
except ValueError:
print("❌ Please provide a valid lesson number")
elif command == 'note':
if len(parts) < 2:
print("❌ Usage: note <lesson_number> <your note text>")
else:
try:
note_parts = parts[1].split(maxsplit=1)
lesson_num = int(note_parts[0])
note_text = note_parts[1] if len(note_parts) > 1 else ""
self.add_note(lesson_num, note_text)
except (ValueError, IndexError):
print("❌ Usage: note <lesson_number> <your note text>")
elif command == 'reset':
self.reset_progress()
else:
print(f"❌ Unknown command: {command}")
print("Type 'help' for available commands")
except KeyboardInterrupt:
print("\n👋 Happy coding! Keep learning Python!")
break
except Exception as e:
print(f"❌ Error: {e}")
if __name__ == "__main__":
assistant = LearningAssistant()
assistant.run()