-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
1739 lines (1563 loc) · 78.6 KB
/
main.py
File metadata and controls
1739 lines (1563 loc) · 78.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
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
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""Python Features Explorer - Interactive CLI application with enhanced features.
This application provides a structured learning experience for Python programming
with search, progress tracking, quizzes, and a user-friendly interface.
"""
import subprocess
import os
import sys
import json
import re
import shutil
from typing import Dict, List, Tuple, Optional, Any
from dataclasses import dataclass, field
from datetime import datetime
from pathlib import Path
import yaml
import logging
# Import colorama for cross-platform terminal colors
try:
from colorama import init, Fore, Back, Style
init(autoreset=True)
COLORAMA_AVAILABLE = True
except ImportError:
COLORAMA_AVAILABLE = False
Fore = Back = Style = None
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
filename='python_explorer.log'
)
logger = logging.getLogger(__name__)
# QuizQuestion dataclass for quiz functionality
@dataclass
class QuizQuestion:
"""Represents a quiz question."""
chapter_number: str
question: str
options: List[str]
answer: int # 1-indexed
explanation: str
@dataclass
class Chapter:
"""Dataclass representing a learning chapter."""
number: str
name: str
readme_path: str
examples: List[str] = field(default_factory=list)
description: str = ""
quiz_questions: List[Dict] = field(default_factory=list)
@dataclass
class UserProgress:
"""Dataclass representing user progress."""
username: str = "default"
completed_chapters: List[str] = field(default_factory=list)
viewed_examples: Dict[str, List[str]] = field(default_factory=dict)
quiz_scores: Dict[str, float] = field(default_factory=dict)
quiz_history: Dict[str, List] = field(default_factory=dict)
example_ratings: Dict[str, float] = field(default_factory=dict)
favorites: List[str] = field(default_factory=list)
last_session: Optional[str] = None
total_time_spent: int = 0 # in minutes
def to_dict(self) -> Dict[str, Any]:
"""Convert to serializable dictionary."""
return {
'username': self.username,
'completed_chapters': self.completed_chapters,
'viewed_examples': self.viewed_examples,
'quiz_scores': {k: float(v) if isinstance(v, (int, float)) else v
for k, v in self.quiz_scores.items()},
'quiz_history': self.quiz_history,
'example_ratings': self.example_ratings,
'favorites': self.favorites,
'last_session': self.last_session,
'total_time_spent': self.total_time_spent
}
class ConfigurationError(Exception):
"""Exception raised when there's a configuration issue."""
pass
class ExampleExecutionError(Exception):
"""Exception raised when example execution fails."""
pass
class ChapterNotFoundError(Exception):
"""Exception raised when a chapter is not found."""
pass
class PythonExplorer:
"""Main application class for exploring Python features."""
DEFAULT_CONFIG = {
'app': {'name': 'Python Features Explorer', 'version': '2.0.0'},
'theme': {'mode': 'auto', 'colors': {}},
'execution': {'timeout_seconds': 30},
'progress': {'enabled': True, 'storage_file': 'user_progress.json'},
'search': {'fuzzy_match': True, 'min_characters': 2},
'quizzes': {
'enabled': False,
'questions_per_quiz': 5,
'passing_score': 70,
'max_quiz_retries': -1,
'show_explanations': True,
'retry_after_fail': True
},
'favorites': {'enabled': False, 'max_favorites': 10},
'display': {'show_descriptions': True, 'content_width': 80},
}
def __init__(self, config_path: str = 'config.yaml'):
"""Initialize the explorer with configuration."""
self.chapters: List[Chapter] = []
self.config = self.DEFAULT_CONFIG.copy()
self.user_progress = UserProgress()
self._load_config(config_path)
self.chapters = self._load_chapters()
self._load_user_progress()
def _load_config(self, config_path: str) -> None:
"""Load configuration from YAML file."""
if os.path.exists(config_path):
try:
with open(config_path, 'r') as f:
yaml_config = yaml.safe_load(f)
if yaml_config:
self.config = self._deep_merge(self.DEFAULT_CONFIG, yaml_config)
logger.info(f"Configuration loaded from {config_path}")
except Exception as e:
logger.warning(f"Failed to load config: {e}, using defaults")
print(f"Warning: Could not load config file ({config_path}), using defaults")
else:
logger.info(f"Config file {config_path} not found, using defaults")
@staticmethod
def _deep_merge(base: Dict, override: Dict) -> Dict:
"""Deep merge two dictionaries."""
result = base.copy()
for key, value in override.items():
if key in result and isinstance(result[key], dict) and isinstance(value, dict):
result[key] = PythonExplorer._deep_merge(result[key], value)
else:
result[key] = value
return result
def _load_chapters(self) -> List[Chapter]:
"""Load chapter data from content directories."""
chapters = []
try:
content_dir = 'content'
if not os.path.exists(content_dir):
print(f"Error: Content directory '{content_dir}' not found")
logger.error(f"Content directory not found: {content_dir}")
return chapters
for chapter_dir in sorted(os.listdir(content_dir)):
if chapter_dir.startswith('ch') and os.path.isdir(
os.path.join(content_dir, chapter_dir)
):
chapter_info = self._process_chapter(content_dir, chapter_dir)
if chapter_info:
chapters.append(chapter_info)
chapters.sort(key=lambda c: int(c.number) if c.number.isdigit() else 999)
logger.info(f"Loaded {len(chapters)} chapters")
except Exception as e:
logger.error(f"Error loading chapters: {e}")
print(f"Error loading chapters: {e}")
return chapters
def _process_chapter(self, content_dir: str, chapter_dir: str) -> Optional[Chapter]:
"""Process a single chapter directory."""
try:
chapter_path = os.path.join(content_dir, chapter_dir)
readme_path = os.path.join(chapter_path, 'README.md')
if not os.path.exists(readme_path):
logger.warning(f"README.md not found in {chapter_path}")
return None
with open(readme_path, 'r', encoding='utf-8') as f:
chapter_content = f.readlines()
# Extract chapter description
description = self._extract_description(chapter_content)
# Get chapter name
chapter_name = chapter_dir.replace('_', ' ').title()
# Get examples
examples = []
examples_path = os.path.join('examples', chapter_dir)
if os.path.exists(examples_path):
for file in sorted(os.listdir(examples_path)):
if file.endswith('.py'):
examples.append(file.replace('.py', ''))
# Extract chapter number
number = self._extract_chapter_number(chapter_content)
# Load quiz questions if available
quiz_questions = []
quiz_file = os.path.join('quizzes', f'quiz_ch{number}.json')
if os.path.exists(quiz_file):
try:
with open(quiz_file, 'r') as f:
quiz_data = json.load(f)
quiz_questions = quiz_data.get('questions', [])
logger.info(f"Loaded {len(quiz_questions)} questions from {quiz_file}")
except Exception as e:
logger.warning(f"Failed to load quiz file {quiz_file}: {e}")
quiz_questions = []
return Chapter(
number=number,
name=chapter_name,
readme_path=readme_path,
examples=examples,
description=description,
quiz_questions=quiz_questions
)
except Exception as e:
logger.error(f"Error processing {chapter_dir}: {e}")
print(f"Error processing {chapter_dir}: {e}")
return None
def _extract_chapter_number(self, chapter_content: List[str]) -> str:
"""Extract chapter number from content."""
if not chapter_content:
return '00'
match = re.search(r'Chapter\s+(\d+)', chapter_content[0].strip())
return match.group(1) if match else '00'
def _extract_description(self, chapter_content: List[str]) -> str:
"""Extract chapter description from README."""
if len(chapter_content) < 10:
return ' '.join(chapter_content[:5])
# Look for first paragraph after title
in_body = False
description_lines = []
for line in chapter_content[1:10]:
line = line.strip()
if line.startswith('#'):
if in_body:
break
continue
if line and not line.startswith('-') and not line.startswith('*'):
description_lines.append(line)
in_body = True
if len(description_lines) >= 2:
break
return ' '.join(description_lines) if description_lines else ''
def _load_user_progress(self) -> None:
"""Load user progress from file."""
if not self.config.get('progress', {}).get('enabled', True):
return
storage_file = self.config['progress'].get('storage_file', 'user_progress.json')
if os.path.exists(storage_file):
try:
with open(storage_file, 'r') as f:
data = json.load(f)
self.user_progress = UserProgress(**data)
logger.info(f"Loaded progress for user: {self.user_progress.username}")
except Exception as e:
logger.warning(f"Failed to load progress: {e}")
print(f"Warning: Could not load previous progress")
else:
logger.info("No progress file found, starting fresh")
def _save_user_progress(self) -> None:
"""Save user progress to file."""
if not self.config.get('progress', {}).get('enabled', True):
return
storage_file = self.config['progress'].get('storage_file', 'user_progress.json')
try:
data = {
'username': self.user_progress.username,
'completed_chapters': self.user_progress.completed_chapters,
'viewed_examples': self.user_progress.viewed_examples,
'quiz_scores': self.user_progress.quiz_scores,
'example_ratings': self.user_progress.example_ratings,
'favorites': self.user_progress.favorites,
'last_session': self.user_progress.last_session,
'total_time_spent': self.user_progress.total_time_spent
}
with open(storage_file, 'w') as f:
json.dump(data, f, indent=2)
logger.info(f"Saved progress to {storage_file}")
except Exception as e:
logger.error(f"Failed to save progress: {e}")
print(f"Error saving progress: {e}")
def display_menu(self) -> str:
"""Display the main menu with search, favorites, and progress."""
print("\n" + self._get_formatted_header("PYTHON FEATURES EXPLORER"))
print("=" * 60)
# Show progress
if self.chapters:
completed = len(self.user_progress.completed_chapters)
total = len(self.chapters)
progress_pct = int((completed / total) * 100) if total > 0 else 0
print(f"Progress: {completed}/{total} chapters ({progress_pct}%)")
# Search bar
search_results = None
while True:
search_input = self._get_input("Search chapters (press Enter to see all)> ").strip().lower()
if search_input:
search_results = self._search_chapters(search_input)
print(f"\nFound {len(search_results)} matching chapter(s):")
for chapter in search_results:
print(f" {chapter.number}. {chapter.name} - {chapter.description[:50]}")
print()
else:
search_results = self.chapters
break
if not self._get_input("Continue searching? (y/n) ").lower().startswith('y'):
search_results = self.chapters
break
# Favorites section
if self.user_progress.favorites:
print("\n" + self._get_formatted_text("⭐ FAVORITES", "yellow"))
for fav_id in self.user_progress.favorites[:5]:
try:
chapter = next(ch for ch in self.chapters if ch.number == fav_id)
print(f" ⭐ {chapter.number}. {chapter.name}")
except StopIteration:
pass
# Main menu
print("\n" + "-" * 60)
print("AVAILABLE CHAPTERS")
print("-" * 60)
for idx, chapter in enumerate(self.chapters, 1):
status = ""
if chapter.number in self.user_progress.completed_chapters:
status = " ✓"
elif chapter.number in self.user_progress.favorites:
status = " ⭐"
display_name = f"{idx}. {chapter.name}"
print(f" {self._get_formatted_color(display_name + status, 'green')}")
if self.config.get('display', {}).get('show_descriptions', True) and chapter.description:
print(f" {self._get_formatted_color(chapter.description[:70], 'dim')}")
print(f"\n{len(self.chapters) + 1}. Exit")
return self._get_input(f"\nSelect a chapter (1-{len(self.chapters) + 1})> ")
def _search_chapters(self, query: str) -> List[Chapter]:
"""Search chapters by name, description, or examples."""
search_scope = self.config['search'].get('search_scope', 'all')
min_chars = self.config['search'].get('min_characters', 2)
if len(query) < min_chars:
return []
results = []
for chapter in self.chapters:
match = False
if search_scope in ['all', 'titles'] and query in chapter.name.lower():
match = True
if search_scope in ['all', 'descriptions'] and query in chapter.description.lower():
match = True
if search_scope in ['all', 'examples']:
for example in chapter.examples:
if query in example.lower():
match = True
break
if match:
results.append(chapter)
return results
def display_chapter_details(self, chapter: Chapter, rendered_content: str = None):
"""Display chapter content and examples with progress tracking."""
print("\n" + self._get_formatted_text(f"CHAPTER {chapter.number}: {chapter.name.upper()}", "cyan"))
print("=" * 60)
# Show cached or fresh content
if not rendered_content:
try:
with open(chapter.readme_path, 'r', encoding='utf-8') as f:
rendered_content = f.read()
# Cache the rendered content for this session
if not hasattr(self, '_chapter_cache'):
self._chapter_cache = {}
self._chapter_cache[chapter.number] = rendered_content
except Exception as e:
print(f"Error reading chapter content: {e}")
rendered_content = ""
display_width = self.config.get('display', {}).get('content_width', 80)
self._print_formatted_text(rendered_content, display_width)
print("\n" + self._get_formatted_text("Available Examples", "blue"))
print("-" * 60)
if chapter.examples:
for idx, example in enumerate(chapter.examples, 1):
viewed = "✓" if example in self.user_progress.viewed_examples.get(chapter.number, []) else " "
print(f" {viewed} {idx}. {example}")
print(f"\n{len(chapter.examples) + 1}. Back to menu")
if self.user_progress.favorites and chapter.number in self.user_progress.favorites:
print(" ⭐ Already marked as favorite")
else:
print("\nNo examples available.")
input("\nPress Enter to continue...")
return None
return self._get_input("\nSelect an example to run (1-{})> ".format(len(chapter.examples) + 1))
def run_example(self, chapter_name: str, example_name: str, chapter_number: str) -> None:
"""Run a Python example script with error handling and timeout."""
example_path = os.path.join('examples', chapter_name.lower().replace(' ', '_'), f"{example_name}.py")
if not os.path.exists(example_path):
print(f"\n{self._get_formatted_text('Error', 'red')}: Example '{example_name}' not found at {example_path}")
logger.error(f"Example not found: {example_path}")
input("\nPress Enter to continue...")
return
print("\n" + self._get_formatted_text(f"Running example: {example_name}", "yellow"))
print("=" * 40)
timeout = self.config.get('execution', {}).get('timeout_seconds', 30)
try:
start_time = datetime.now()
result = subprocess.run(
['python3', example_path],
capture_output=True,
text=True,
timeout=timeout
)
end_time = datetime.now()
duration = (end_time - start_time).total_seconds()
if result.stdout:
print(self._get_formatted_text("OUTPUT:", "green"))
print(result.stdout)
if result.stderr:
print(self._get_formatted_text("STDERR:", "red"))
print(result.stderr)
print(f"\nExample completed in {duration:.2f}s with exit code: {result.returncode}")
except subprocess.TimeoutExpired as e:
print(f"{self._get_formatted_text('Error', 'red')}: Example execution timed out ({timeout}s)")
logger.warning(f"Example {example_name} timed out after {timeout}s")
input("\nPress Enter to continue...")
except Exception as e:
print(f"{self._get_formatted_text('Error running example:', 'red')} {e}")
logger.error(f"Error running example {example_name}: {e}")
input("\nPress Enter to continue...")
return
# Update progress
self._update_progress(chapter_number, example_name)
input("\nPress Enter to continue...")
def _update_progress(self, chapter_number: str, example_name: str) -> None:
"""Update user progress for viewed example."""
if chapter_number not in self.user_progress.viewed_examples:
self.user_progress.viewed_examples[chapter_number] = []
if example_name not in self.user_progress.viewed_examples[chapter_number]:
self.user_progress.viewed_examples[chapter_number].append(example_name)
logger.info(f"Viewed example {example_name} in chapter {chapter_number}")
def complete_chapter(self, chapter_number: str) -> None:
"""Mark chapter as completed."""
if chapter_number not in self.user_progress.completed_chapters:
self.user_progress.completed_chapters.append(chapter_number)
self.user_progress.last_session = datetime.now().isoformat()
logger.info(f"Completed chapter {chapter_number}")
print(f"{self._get_formatted_text('✓', 'green')} Chapter {chapter_number} marked as completed!")
def toggle_favorite(self, chapter_number: str) -> bool:
"""Toggle favorite status for a chapter."""
if chapter_number in self.user_progress.favorites:
self.user_progress.favorites.remove(chapter_number)
print(f"Removed {chapter_number} from favorites")
return False
else:
if len(self.user_progress.favorites) >= self.config.get('favorites', {}).get('max_favorites', 10):
print("Maximum favorites reached!")
return False
self.user_progress.favorites.append(chapter_number)
print(f"Added {chapter_number} to favorites")
return True
def rate_example(self, chapter_number: str, example_name: str, rating: int) -> None:
"""Rate an example (1-5)."""
if 1 <= rating <= 5:
key = f"{chapter_number}:{example_name}"
self.user_progress.example_ratings[key] = rating
logger.info(f"Rated example {example_name} as {rating} stars")
print(f"{self._get_formatted_text('✓', 'green')} Example rated {rating}/5 stars")
else:
print("Rating must be between 1 and 5")
def display_quiz(self, chapter: Chapter) -> bool:
"""Display quiz for a chapter with enhanced randomized questions."""
quiz_config = self.config.get('quizzes', {})
if not quiz_config.get('enabled', False):
print("\nQuizzes are not enabled. Enable in config.yaml to use.")
return True
# Get questions from chapter (loaded from JSON)
questions = getattr(chapter, 'quiz_questions', [])
if not questions:
print(f"\nNo quiz questions available for {chapter.name}")
return True
# Randomly select questions if pool is larger than needed
num_questions = quiz_config.get('questions_per_quiz', 11)
if len(questions) > num_questions:
import random
questions = random.sample(questions, num_questions)
# Update chapter's quiz_questions to reflect selection
chapter.quiz_questions = questions
# Handle retry logic
retry_config = quiz_config.get('retry_after_fail', True)
max_retries = quiz_config.get('max_quiz_retries', -1)
# Check if user can retry
can_retry = retry_config and max_retries != 0
# Display quiz header
print(f"\n{self._get_formatted_text('QUIZ', 'cyan')} - {chapter.name}")
print("=" * 50)
print(f"Questions: {len(questions)} | Passing score: {quiz_config.get('passing_score', 70)}%")
if can_retry:
attempts = self.user_progress.quiz_history.get(chapter.number, [])
if max_retries > 0:
print(f"Retries: {len(attempts)}/{max_retries}")
else:
print(f"Unlimited retries allowed")
score = 0
total = min(len(questions), quiz_config.get('questions_per_quiz', 5))
attempts = []
# Process each question
for i, question in enumerate(questions[:total], 1):
print(f"\n{i}. {question['question']}")
# Display options without revealing the answer
for j, option in enumerate(question['options'], 1):
print(f" ○ {j}. {self._get_formatted_text(option, 'white')}")
try:
answer = int(self._get_input(f"Enter your answer ({1}-{len(question['options'])})> "))
if 1 <= answer <= len(question['options']):
is_correct = (answer == question['answer'])
attempts.append({
'question': i,
'user_answer': answer,
'correct': question['answer'],
'correct_answer': question['options'][question['answer'] - 1],
'is_correct': is_correct
})
if is_correct:
print(f"{self._get_formatted_text('✓ Correct!', 'green')}")
score += 1
else:
print(f"{self._get_formatted_text('✗ Incorrect!', 'red')}")
correct_answer_text = question['options'][question['answer'] - 1]
print(f" Correct answer: {correct_answer_text}")
if quiz_config.get('show_explanations', True) and question.get('explanation'):
print(f" Explanation: {question['explanation']}")
else:
print(f"{self._get_formatted_text('Invalid number!', 'yellow')}")
attempts.append({
'question': i,
'user_answer': None,
'correct': question['answer'],
'correct_answer': question['options'][question['answer'] - 1],
'is_correct': False
})
except ValueError:
print(f"{self._get_formatted_text('Invalid input!', 'yellow')}")
attempts.append({
'question': i,
'user_answer': None,
'correct': question['answer'],
'correct_answer': question['options'][question['answer'] - 1],
'is_correct': False
})
# Calculate results
percentage = (score / total) * 100
passing = quiz_config.get('passing_score', 70)
# Save attempt to history
if chapter.number not in self.user_progress.quiz_history:
self.user_progress.quiz_history[chapter.number] = []
self.user_progress.quiz_history[chapter.number].append(attempts)
# Display summary
print("\n" + self._get_formatted_text('QUIZ RESULTS', 'yellow'))
print("=" * 50)
print(f"Score: {score}/{total} ({percentage:.1f}%)")
status_color = 'green' if percentage >= passing else 'red'
print(f"Status: {self._get_formatted_text('PASSED' if percentage >= passing else 'FAILED', status_color)}")
print(f"Required: {passing}% to pass")
# Detailed review if failed
if percentage < passing:
print("\n" + self._get_formatted_text('REVIEW YOUR ANSWERS:', 'yellow'))
correct_count = sum(1 for a in attempts if a['is_correct'])
incorrect_count = total - correct_count
print(f" Correct: {correct_count}/{total}")
print(f" Incorrect: {incorrect_count}/{total}")
for attempt in attempts:
if not attempt['is_correct']:
answer_display = f"{attempt['user_answer']}" if attempt['user_answer'] else "Skipped/Invalid"
print(f" - Q{attempt['question']}: You answered '{answer_display}'")
print(f" Correct: {attempt['correct_answer']}")
if can_retry:
print(f"\n{self._get_formatted_text('Tip: You can retry the quiz!', 'cyan')}")
else:
print(f"\n{self._get_formatted_text('Complete the examples and try again later.', 'yellow')}")
# Update progress
if percentage >= passing:
print(f"\n{self._get_formatted_text('✓ Congratulations! Quiz passed!', 'green')}")
self.complete_chapter(chapter.number)
self.user_progress.quiz_scores[chapter.number] = percentage
return True
else:
print(f"\n{self._get_formatted_text('✗ Keep practicing! Retake quiz after reviewing content', 'yellow')}")
return False
def _generate_fallback_quiz_questions(self, chapter: Chapter, content: str = "") -> List[Dict]:
"""Generate 11 quiz questions from chapter content as fallback."""
questions = []
chapter_num = int(chapter.number) if chapter.number.isdigit() else 1
if chapter_num == 1:
questions = [
{
'question': 'What is the correct function to output text in Python?',
'options': ['output()', 'print()', 'write()', 'echo()'],
'answer': 2,
'explanation': 'The print() function in Python outputs text to the console.'
},
{
'question': 'What symbol is used for single-line comments in Python?',
'options': ['//', '#', '/*', '--'],
'answer': 2,
'explanation': 'The # symbol starts a single-line comment in Python.'
},
{
'question': 'Which keyword is used to import modules in Python?',
'options': ['include', 'import', 'using', 'require'],
'answer': 2,
'explanation': 'The import keyword is used to import modules in Python.'
},
{
'question': 'What is Python primarily known for?',
'options': ['Complex syntax', 'Readability', 'Speed', 'Hardware control'],
'answer': 2,
'explanation': 'Python is known for its simple and readable syntax.'
},
{
'question': 'Which data type represents decimal numbers?',
'options': ['int', 'float', 'str', 'bool'],
'answer': 2,
'explanation': 'float data type represents decimal (floating-point) numbers.'
},
{
'question': 'What is the correct extension for Python files?',
'options': ['.py', '.python', '.pt', '.pc'],
'answer': 1,
'explanation': 'Python files use the .py extension.'
},
{
'question': 'Which keyword defines a function in Python?',
'options': ['func', 'define', 'def', 'function'],
'answer': 3,
'explanation': 'The def keyword is used to define functions in Python.'
},
{
'question': 'What does Python use to define code blocks?',
'options': ['Braces', 'Indentation', 'Semicolons', 'Keywords'],
'answer': 2,
'explanation': 'Python uses indentation to define code blocks.'
},
{
'question': 'Which built-in function returns the type of an object?',
'options': ['kind()', 'type()', 'category()', 'class()'],
'answer': 2,
'explanation': 'The type() function returns the data type of an object.'
},
{
'question': 'What is the result of 10 / 3 in Python 3?',
'options': ['3', '3.33', '3.0', '3.333...'],
'answer': 4,
'explanation': 'Python 3 division returns a float result.'
},
{
'question': 'Which statement creates a variable in Python?',
'options': ['var x = 5', 'int x = 5', 'x = 5', 'declare x = 5'],
'answer': 3,
'explanation': 'Python uses simple assignment: variable_name = value.'
}
]
elif chapter_num == 2:
questions = [
{
'question': 'Which data structure is ordered and mutable?',
'options': ['list', 'tuple', 'set', 'dict'],
'answer': 1,
'explanation': 'Lists are ordered and mutable (can be changed).'
},
{
'question': 'Which data structure is ordered but immutable?',
'options': ['list', 'tuple', 'set', 'dict'],
'answer': 2,
'explanation': 'Tuples are ordered and immutable (cannot be changed).'
},
{
'question': 'What syntax is used to create a dictionary?',
'options': ['[]', '()', '{}', '<>'],
'answer': 3,
'explanation': 'Curly braces {} are used to create dictionaries.'
},
{
'question': 'How do you access an element by index in a list?',
'options': ['list.key', 'list[index]', 'list.name', 'list(0)'],
'answer': 2,
'explanation': 'Square brackets with index: list[index] accesses elements.'
},
{
'question': 'Which method adds an element to the end of a list?',
'options': ['push()', 'add()', 'append()', 'insert()'],
'answer': 3,
'explanation': 'append() adds an element to the end of a list.'
},
{
'question': 'What does set() do with duplicate values?',
'options': ['Keeps all duplicates', 'Removes duplicates', 'Errors out', 'Counts them'],
'answer': 2,
'explanation': 'Sets automatically remove duplicate values.'
},
{
'question': 'Which syntax creates a list comprehension?',
'options': ['for x in list: x', '[x for x in list]', 'list(x for x in list)', '(x for x in list)'],
'answer': 2,
'explanation': 'List comprehensions use square brackets: [expression for item in iterable].'
},
{
'question': 'How do you get the number of elements in a list?',
'options': ['list.size()', 'list.length', 'len(list)', 'size(list)'],
'answer': 3,
'explanation': 'The len() function returns the number of elements.'
},
{
'question': 'Which data structure stores key-value pairs?',
'options': ['list', 'tuple', 'set', 'dict'],
'answer': 4,
'explanation': 'Dictionaries store data as key-value pairs.'
},
{
'question': 'What is the main difference between list and tuple?',
'options': ['Lists are immutable', 'Tuples are immutable', 'Lists can only store ints', 'Tuples are unordered'],
'answer': 2,
'explanation': 'Tuples are immutable (cannot be modified after creation).'
},
{
'question': 'Which operator checks if an item is in a list?',
'options': ['in', 'contains', 'has', 'is'],
'answer': 1,
'explanation': 'The in operator checks membership: item in list.'
}
]
elif chapter_num == 3:
questions = [
{
'question': 'Which keyword starts a conditional statement?',
'options': ['when', 'else', 'if', 'case'],
'answer': 3,
'explanation': 'The if keyword begins conditional statements.'
},
{
'question': 'What keyword exits a loop immediately?',
'options': ['break', 'continue', 'exit', 'stop'],
'answer': 1,
'explanation': 'The break statement exits a loop immediately.'
},
{
'question': 'What keyword skips to the next iteration?',
'options': ['break', 'continue', 'skip', 'next'],
'answer': 2,
'explanation': 'The continue statement skips to the next loop iteration.'
},
{
'question': 'Which keyword is used for iteration loops?',
'options': ['while', 'for', 'repeat', 'loop'],
'answer': 2,
'explanation': 'The for keyword is used for iterating over sequences.'
},
{
'question': 'What keyword starts a loop based on a condition?',
'options': ['while', 'for', 'if', 'until'],
'answer': 1,
'explanation': 'The while loop repeats while a condition is true.'
},
{
'question': 'Which keyword handles alternative conditions?',
'options': ['else', 'otherwise', 'alt', 'switch'],
'answer': 1,
'explanation': 'The else keyword handles alternative conditions.'
},
{
'question': 'What keyword handles additional conditions?',
'options': ['elif', 'else if', 'elseif', 'if else'],
'answer': 1,
'explanation': 'The elif keyword checks additional conditions.'
},
{
'question': 'Which statement is a placeholder that does nothing?',
'options': ['null', 'pass', 'skip', 'ignore'],
'answer': 2,
'explanation': 'The pass statement is a placeholder that does nothing.'
},
{
'question': 'Can you use else with for loops?',
'options': ['No', 'Yes, executes when loop finishes', 'Yes, executes when loop breaks', 'Only with while'],
'answer': 2,
'explanation': 'Yes, else with for executes when the loop finishes normally (not broken).'
},
{
'question': 'What is the indentation requirement in Python?',
'options': ['Optional', '4 spaces minimum', 'Consistent indentation required', 'Any spaces work'],
'answer': 3,
'explanation': 'Python requires consistent indentation for code blocks.'
},
{
'question': 'How do you write a multi-way conditional?',
'options': ['if-else', 'if-elif-else', 'switch-case', 'multiple-if'],
'answer': 2,
'explanation': 'Use if-elif-else chains for multi-way conditionals.'
}
]
elif chapter_num == 4:
questions = [
{
'question': 'Which keyword defines a function?',
'options': ['func', 'define', 'def', 'function'],
'answer': 3,
'explanation': 'The def keyword is used to define functions.'
},
{
'question': 'What are *args used for?',
'options': ['Keyword arguments', 'Variable positional arguments', 'Default arguments', 'Named arguments'],
'answer': 2,
'explanation': '*args collects variable positional arguments into a tuple.'
},
{
'question': 'What are **kwargs used for?',
'options': ['Positional arguments', 'Variable keyword arguments', 'Required arguments', 'Default arguments'],
'answer': 2,
'explanation': '**kwargs collects variable keyword arguments into a dictionary.'
},
{
'question': 'What keyword creates anonymous functions?',
'options': ['lambda', 'anonymous', 'fn', 'func'],
'answer': 1,
'explanation': 'The lambda keyword creates anonymous (unnamed) functions.'
},
{
'question': 'Which function applies a function to all items?',
'options': ['map()', 'apply()', 'do()', 'run()'],
'answer': 1,
'explanation': 'map() applies a function to each item in an iterable.'
},
{
'question': 'Which function filters items based on a condition?',
'options': ['filter()', 'select()', 'where()', 'extract()'],
'answer': 1,
'explanation': 'filter() constructs an iterator from items where the function returns true.'
},
{
'question': 'What does the LEGB rule refer to?',
'options': ['Loop structures', 'Variable scope', 'Function arguments', 'Module imports'],
'answer': 2,
'explanation': 'LEGB rules the order of variable scope: Local, Enclosing, Global, Built-in.'
},
{
'question': 'Where are local variables defined?',
'options': ['Inside functions', 'Outside functions', 'In classes', 'In modules'],
'answer': 1,
'explanation': 'Local variables are defined inside functions.'
},
{
'question': 'What is the purpose of a function?',
'options': ['To repeat code', 'To organize reusable code', 'To define variables', 'To import modules'],
'answer': 2,
'explanation': 'Functions organize code into reusable, named blocks.'
},
{
'question': 'How do you return a value from a function?',
'options': ['print()', 'return', 'export', 'yield'],
'answer': 2,
'explanation': 'The return statement sends a value back from a function.'
},
{
'question': 'What happens if a function has no return statement?',
'options': ['Errors', 'Returns None', 'Returns 0', 'Returns False'],
'answer': 2,
'explanation': 'Functions without return statements return None.'
}
]
elif chapter_num == 5:
questions = [
{
'question': 'What keyword defines a class?',
'options': ['class', 'define', 'object', 'struct'],
'answer': 1,
'explanation': 'The class keyword is used to define classes.'
},
{
'question': 'What is the constructor method in Python classes?',
'options': ['__init__', '__construct__', '__start__', '__build__'],
'answer': 1,
'explanation': '__init__ is the constructor method called when creating objects.'
},
{
'question': 'What are methods ending with __ called?',
'options': ['Private methods', 'Dunder methods', 'Static methods', 'Class methods'],
'answer': 2,
'explanation': 'Methods with double underscores are called dunder or magic methods.'
},
{
'question': 'What does inheritance allow?',
'options': ['Multiple classes', 'Class reuse and extension', 'Function overloading', 'Variable types'],
'answer': 2,
'explanation': 'Inheritance allows creating new classes that reuse and extend existing classes.'