-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpython-mastery-guide.html
More file actions
3020 lines (2504 loc) · 88.4 KB
/
python-mastery-guide.html
File metadata and controls
3020 lines (2504 loc) · 88.4 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Python Programming — Basic to Advanced</title>
<link href="https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;500&family=Syne:wght@400;500;600;700&display=swap" rel="stylesheet">
<style>
*{box-sizing:border-box;margin:0;padding:0}
body{background:#0f1117;color:#ffffff;font-family:'Syne',sans-serif;min-height:100vh}
/* ── TOP BAR ── */
.topbar{background:#161b27;border-bottom:1px solid #2a3348;padding:.65rem 1rem;display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:.5rem;position:sticky;top:0;z-index:300}
.logo{font-size:.95rem;font-weight:700;color:#3b82f6}
.logo span{color:#9ca3af;font-weight:400;font-size:.78rem}
.topbar-right{display:flex;gap:.4rem;align-items:center;flex-wrap:wrap}
.srch{background:#1e2535;border:1px solid #2a3348;border-radius:8px;padding:.38rem .75rem;color:#ffffff;font-family:'Syne',sans-serif;font-size:.8rem;width:200px;outline:none}
.srch:focus{border-color:#3b82f6;background:#252d40}
.srch::placeholder{color:#6b7280}
.fbtn{background:#1e2535;border:1px solid #2a3348;border-radius:8px;padding:.36rem .65rem;color:#9ca3af;font-size:.7rem;cursor:pointer;font-family:'Syne',sans-serif;transition:all .15s;white-space:nowrap}
.fbtn:hover,.fbtn.on{background:#252d40;color:#3b82f6;border-color:#3b82f655}
.mob-toggle{display:none;background:#3b82f6;border:none;border-radius:8px;padding:.38rem .75rem;color:#000;font-size:.75rem;font-weight:700;cursor:pointer;font-family:'Syne',sans-serif;gap:.35rem;align-items:center;white-space:nowrap}
/* ── DESKTOP LAYOUT ── */
.layout{display:flex;height:calc(100vh - 50px)}
.sidebar{width:280px;min-width:280px;background:#161b27;border-right:1px solid #2a3348;overflow-y:auto;height:100%;position:sticky;top:50px}
.sb-inner{padding:.4rem .35rem}
.main{flex:1;overflow-y:auto}
.wrap{padding:1.25rem 1.5rem 2rem;max-width:920px}
/* ── MOBILE OVERLAY ── */
.mob-overlay{display:none;position:fixed;inset:0;background:#0f1117;z-index:400;flex-direction:column}
.mob-overlay.open{display:flex}
.mob-header{background:#161b27;border-bottom:1px solid #2a3348;padding:.65rem 1rem;display:flex;align-items:center;justify-content:space-between;gap:.5rem}
.mob-header-title{font-size:.9rem;font-weight:700;color:#ffffff}
.mob-close{background:#1e2535;border:1px solid #2a3348;border-radius:8px;padding:.35rem .7rem;color:#9ca3af;font-size:.75rem;cursor:pointer;font-family:'Syne',sans-serif}
.mob-search{padding:.6rem .75rem;background:#161b27;border-bottom:1px solid #2a3348}
.mob-search input{width:100%;background:#1e2535;border:1px solid #2a3348;border-radius:8px;padding:.4rem .75rem;color:#ffffff;font-family:'Syne',sans-serif;font-size:.82rem;outline:none}
.mob-search input:focus{border-color:#3b82f6}
.mob-list{flex:1;overflow-y:auto;padding:.4rem .5rem}
.mob-filters{padding:.4rem .75rem .5rem;background:#161b27;display:flex;gap:.4rem;flex-wrap:wrap}
/* ── QUESTION ITEMS ── */
.qi{display:flex;align-items:flex-start;gap:.45rem;padding:.52rem .6rem;border-radius:7px;cursor:pointer;border:1px solid transparent;transition:all .12s;margin-bottom:2px}
.qi:hover{background:#1e2535;border-color:#2a3348}
.qi.active{background:#1e2535;border-left:3px solid #3b82f6;border-color:#3b82f633}
.qi.hidden{display:none}
.qn{min-width:20px;font-size:.67rem;font-weight:700;color:#4b5563;margin-top:2px;font-family:'JetBrains Mono',monospace;flex-shrink:0}
.qi.active .qn{color:#3b82f6}
.qt{font-size:.75rem;color:#ffffff;line-height:1.4;flex:1}
.qi.active .qt{color:#ffffff}
.fdot{width:5px;height:5px;border-radius:50%;margin-top:5px;flex-shrink:0}
/* ── WELCOME ── */
.welcome{text-align:center;padding:3.5rem 1rem}
.welcome h2{font-size:1.35rem;font-weight:700;color:#ffffff;margin-bottom:.6rem}
.welcome p{font-size:.84rem;color:#ffffff;line-height:1.75}
.wgrid{display:grid;grid-template-columns:repeat(3,1fr);gap:.65rem;margin-top:1.5rem;text-align:left}
.wcard{background:#161b27;border:1px solid #2a3348;border-radius:8px;padding:.75rem}
.wcard h4{font-size:.72rem;font-weight:700;color:#3b82f6;margin-bottom:.3rem}
.wcard p{font-size:.72rem;color:#ffffff;line-height:1.5}
/* ── QUESTION CONTENT ── */
.prog-strip{background:#1e2535;border-radius:4px;height:3px;margin-bottom:1rem;overflow:hidden}
.prog-fill{height:100%;background:linear-gradient(90deg,#3b82f6,#06b6d4);border-radius:4px;transition:width .4s}
.qhead{display:flex;align-items:flex-start;gap:.65rem;margin-bottom:.85rem;flex-wrap:wrap}
.qnum{background:#3b82f6;color:#fff;font-size:.67rem;font-weight:700;padding:3px 8px;border-radius:10px;font-family:'JetBrains Mono',monospace;margin-top:3px;flex-shrink:0}
.qtitle{font-size:1.05rem;font-weight:700;color:#ffffff;line-height:1.35;flex:1}
.badges{display:flex;flex-wrap:wrap;gap:.3rem;margin-bottom:.8rem;align-items:center}
.fbadge{font-size:.66rem;padding:2px 7px;border-radius:10px;border:1px solid;font-weight:600;color:#ffffff}
.def-section{background:#1e2535;border-left:3px solid #3b82f6;border-radius:0 8px 8px 0;padding:.75rem 1rem;font-size:.83rem;line-height:1.8;color:#ffffff;margin-bottom:1.1rem}
.def-section strong{color:#3b82f6}
.slabel{font-size:.65rem;font-weight:700;letter-spacing:.12em;color:#6b7280;text-transform:uppercase;margin:1.1rem 0 .5rem;padding-left:2px}
.dbox{margin-bottom:1.1rem;border:1px solid #2a3348;border-radius:10px;overflow:hidden;background:#161b27}
.rgrid{display:grid;grid-template-columns:1fr 1fr;gap:.65rem;margin-bottom:1.1rem}
.rcard{background:#161b27;border:1px solid #2a3348;border-radius:8px;padding:.7rem}
.rcard h4{font-size:.65rem;font-weight:700;color:#06b6d4;text-transform:uppercase;letter-spacing:.08em;margin-bottom:.4rem}
.rcard li{font-size:.76rem;color:#ffffff;list-style:none;padding:2px 0 2px 13px;position:relative;line-height:1.55}
.rcard li::before{content:'→';position:absolute;left:0;color:#3b82f6;font-size:.6rem;top:4px}
.code-block{background:#161b27;border:1px solid #2a3348;border-radius:8px;padding:.8rem;margin-bottom:1.1rem;overflow-x:auto}
.code-block code{font-family:'JetBrains Mono',monospace;font-size:.75rem;color:#ffffff;line-height:1.6;display:block;white-space:pre}
.keyword{color:#ec4899}
.string{color:#34d399}
.comment{color:#6b7280}
.function{color:#60a5fa}
.number{color:#fbbf24}
.expl-box{background:#1a1f2e;border:1px solid #2a3348;border-radius:8px;padding:.75rem;margin-bottom:1.1rem;font-size:.78rem;color:#ffffff;line-height:1.7}
.expl-box strong{color:#3b82f6}
.navrow{display:flex;gap:.5rem;margin-top:1.4rem;padding-top:1rem;border-top:1px solid #2a3348}
.nbtn{background:#1e2535;border:1px solid #2a3348;border-radius:8px;padding:.5rem .8rem;color:#9ca3af;font-size:.74rem;cursor:pointer;font-family:'Syne',sans-serif;transition:all .15s;flex:1;text-align:center;line-height:1.45;color:#ffffff}
.nbtn:hover{background:#252d40;color:#ffffff;border-color:#3b82f6}
.nbtn.off{opacity:.25;pointer-events:none}
/* ── CATEGORY BADGES ── */
.badge-basic{background:#065f46;border-color:#10b981}
.badge-intermediate{background:#1e3a8a;border-color:#3b82f6}
.badge-advanced{background:#5b21b6;border-color:#a78bfa}
/* ── MOBILE OVERRIDES ── */
@media(max-width:768px){
.topbar{padding:.5rem .75rem}
.logo{font-size:.85rem}
.srch{display:none} /* Hide desktop search */
.fbtn:not(.mob-toggle){display:none} /* Hide desktop filters */
.layout{display:block;height:auto}
.sidebar{display:none} /* Hide desktop sidebar */
.main{width:100%}
.wrap{padding:1rem .75rem 2rem}
.mob-toggle{display:flex}
.mob-overlay{display:none;position:fixed;inset:0;background:#0f1117;z-index:400;flex-direction:column}
.mob-overlay.open{display:flex}
.qtitle{font-size:.95rem}
.rgrid{grid-template-columns:1fr}
.wgrid{grid-template-columns:1fr}
.code-block code{font-size:.7rem}
}
</style>
</head>
<body>
<div class="topbar">
<div class="logo">Python <span>Basic → Advanced</span></div>
<div class="topbar-right">
<input type="text" class="srch" id="searchbox" placeholder="Search topics...">
<button class="fbtn" onclick="toggleFilter('all')" id="filter-all">All</button>
<button class="fbtn" onclick="toggleFilter('basic')" id="filter-basic">Basic</button>
<button class="fbtn" onclick="toggleFilter('intermediate')" id="filter-inter">Intermediate</button>
<button class="fbtn" onclick="toggleFilter('advanced')" id="filter-adv">Advanced</button>
<button class="mob-toggle" onclick="toggleMobOverlay()">☰ Menu</button>
</div>
</div>
<!-- MOBILE OVERLAY -->
<div class="mob-overlay" id="moboverlay">
<div class="mob-header">
<div class="mob-header-title">Python Topics</div>
<button class="mob-close" onclick="toggleMobOverlay()">✕</button>
</div>
<div style="padding: .5rem .75rem; background: #161b27; border-bottom: 1px solid #2a3348;">
<a href="index.html" style="color: #9ca3af; text-decoration: none; font-size: .75rem; display: flex; align-items: center; gap: .4rem;">
<span>←</span> Back to Mastery Hub
</a>
</div>
<div class="mob-search">
<input type="text" id="searchbox-mob" placeholder="Search topics..." onkeyup="filterQuestions()">
</div>
<div class="mob-list" id="moblist"></div>
</div>
<!-- DESKTOP LAYOUT -->
<div class="layout">
<div class="sidebar"><div class="sb-inner" id="deskqlist"></div></div>
<div class="main">
<div class="wrap" id="content"></div>
</div>
</div>
<script>
const topics = [
{id:1,title:"Variables & Data Types",cat:"basic",level:"Fundamentals"},
{id:2,title:"Strings & String Methods",cat:"basic",level:"Fundamentals"},
{id:3,title:"Lists, Tuples & Sets",cat:"basic",level:"Fundamentals"},
{id:4,title:"Dictionaries",cat:"basic",level:"Collections"},
{id:5,title:"Control Flow (if/else)",cat:"basic",level:"Fundamentals"},
{id:6,title:"Loops (for/while)",cat:"basic",level:"Fundamentals"},
{id:7,title:"Functions & Parameters",cat:"basic",level:"Fundamentals"},
{id:8,title:"List Comprehensions",cat:"intermediate",level:"Advanced Syntax"},
{id:9,title:"Lambda Functions",cat:"intermediate",level:"Functional"},
{id:10,title:"Exception Handling (try/except)",cat:"basic",level:"Error Handling"},
{id:11,title:"Classes & Objects (OOP)",cat:"intermediate",level:"OOP Basics"},
{id:12,title:"Inheritance & Polymorphism",cat:"intermediate",level:"OOP"},
{id:13,title:"Decorators",cat:"intermediate",level:"Advanced"},
{id:14,title:"Generators & yield",cat:"intermediate",level:"Advanced"},
{id:15,title:"Context Managers (with statement)",cat:"intermediate",level:"Resource Management"},
{id:16,title:"Module & Packages",cat:"basic",level:"Organization"},
{id:17,title:"File I/O & Working with Files",cat:"intermediate",level:"I/O"},
{id:18,title:"Regular Expressions (regex)",cat:"intermediate",level:"Text Processing"},
{id:19,title:"Higher-Order Functions",cat:"intermediate",level:"Functional"},
{id:20,title:"map, filter, reduce",cat:"intermediate",level:"Functional"},
{id:21,title:"Iterators",cat:"intermediate",level:"Advanced"},
{id:22,title:"Metaclasses",cat:"advanced",level:"Advanced OOP"},
{id:23,title:"Descriptors & Properties",cat:"advanced",level:"Advanced OOP"},
{id:24,title:"Abstract Base Classes (ABC)",cat:"advanced",level:"Design Patterns"},
{id:25,title:"Async/Await & asyncio",cat:"advanced",level:"Concurrency"},
{id:26,title:"Threading & Multiprocessing",cat:"advanced",level:"Concurrency"},
{id:27,title:"Type Hints & Type Checking",cat:"intermediate",level:"Code Quality"},
{id:28,title:"Closures & Nonlocal",cat:"intermediate",level:"Advanced Scoping"},
{id:29,title:"Slots & Memory Optimization",cat:"advanced",level:"Optimization"},
{id:30,title:"Monkey Patching",cat:"advanced",level:"Advanced Techniques"},
];
const content = {
1:{
def:"Variables are containers for storing data values. Python is dynamically typed, meaning you don't need to declare the type - it's inferred from the value.",
examples:[
{title:"Creating Variables",code:`name = "Alice"
age = 25
price = 19.99
is_active = True
empty = None
# Variables can be reassigned
age = 26
print(name, age, price, is_active, empty)
# Output: Alice 26 19.99 True None`},
{title:"Data Types",code:`# int - integers
count = 42
negative = -10
# float - decimal numbers
temperature = 98.6
# str - text
message = "Hello Python"
# bool - True or False
flag = True
# NoneType - absence of value
result = None
print(type(count)) # <class 'int'>
print(type(temperature)) # <class 'float'>
print(type(message)) # <class 'str'>
print(type(flag)) # <class 'bool'>`},
{title:"Type Conversion",code:`# Convert between types
num_str = "123"
num_int = int(num_str) # 123
num_float = float(num_str) # 123.0
text = str(100) # "100"
binary = bin(10) # "0b1010"
hexadecimal = hex(255) # "0xff"
print(num_int + 5) # 128
print(text + " apples") # 100 apples`}
],
explanations:[
"Variables store references to objects, not the actual data.",
"Python uses dynamic typing - types can change at runtime.",
"The type() function shows the data type of any variable.",
"Converting between types allows flexible data manipulation.",
"None is used to represent absence of a value (like null in other languages)."
]
},
2:{
def:"Strings are sequences of characters enclosed in quotes. Python provides powerful string methods for manipulation, formatting, and processing text.",
examples:[
{title:"String Basics",code:`# String creation
single = 'Hello'
double = "World"
triple = '''Multi-line
string'''
# String concatenation
greeting = single + " " + double
print(greeting) # Hello World
# String repetition
repeated = "Ha" * 3 # "HaHaHa"
# String length
print(len("Python")) # 6`},
{title:"String Methods",code:`text = "Python Programming"
# Case conversion
print(text.upper()) # PYTHON PROGRAMMING
print(text.lower()) # python programming
print(text.capitalize()) # Python programming
# Search methods
print(text.find("Pro")) # 7
print(text.count("o")) # 2
print("Python" in text) # True
# Replace
new_text = text.replace("Python", "Java")
print(new_text) # Java Programming`},
{title:"String Formatting",code:`# f-strings (Python 3.6+)
name = "Alice"
age = 25
print(f"{name} is {age} years old")
# format() method
print("Hello, {}!".format("Bob"))
# Multiple values
x, y = 10, 20
print(f"x={x}, y={y}, sum={x+y}")
# Format specifiers
pi = 3.14159
print(f"Pi: {pi:.2f}") # Pi: 3.14
print(f"Percent: {0.85:.1%}") # Percent: 85.0%`}
],
explanations:[
"Strings are immutable - operations return new strings.",
"String slicing: text[start:end:step] extracts substrings.",
"Methods like strip(), split(), join() are commonly used.",
"F-strings provide clean, readable string interpolation.",
"Raw strings (r'...') preserve backslashes (useful for regex, paths)."
]
},
3:{
def:"Lists are ordered, mutable collections. Tuples are ordered, immutable collections. Sets are unordered collections of unique items. Each has different use cases.",
examples:[
{title:"Lists",code:`# Creating lists
fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", 3.14, True]
# Accessing elements (0-indexed)
print(fruits[0]) # apple
print(fruits[-1]) # cherry (last item)
# Slicing
print(numbers[1:4]) # [2, 3, 4]
print(numbers[::2]) # [1, 3, 5] (every 2nd)
# List operations
fruits.append("date")
fruits.insert(1, "blueberry")
fruits.extend(["elderberry", "fig"])
fruits.remove("apple")
popped = fruits.pop() # removes last item
print(fruits)`},
{title:"Tuples",code:`# Tuples are immutable
coordinates = (10, 20)
rgb = (255, 0, 0)
# Accessing elements
print(coordinates[0]) # 10
# Unpacking
x, y = coordinates
r, g, b = rgb
# Immutable - can't modify
# coordinates[0] = 15 # Error!
# Tuple operations
combined = coordinates + (30,)
print(combined) # (10, 20, 30)
print(coordinates * 2) # (10, 20, 10, 20)
# Named tuples
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(3, 4)
print(p.x, p.y) # 3 4`},
{title:"Sets",code:`# Sets contain unique items, unordered
colors = {"red", "green", "blue"}
numbers = {1, 2, 3, 2, 1} # {1, 2, 3}
# Adding items
colors.add("yellow")
# Set operations
set_a = {1, 2, 3}
set_b = {2, 3, 4}
union = set_a | set_b # {1, 2, 3, 4}
intersection = set_a & set_b # {2, 3}
difference = set_a - set_b # {1}
print(f"Union: {union}")
print(f"Intersection: {intersection}")
# Check membership
print(2 in set_a) # True`}
],
explanations:[
"Lists are mutable - elements can be changed after creation.",
"Tuples are immutable - often used for fixed collections of data.",
"Sets are automatically deduplicated - useful for uniqueness checks.",
"Negative indexing: -1 refers to last element, -2 to second-last, etc.",
"List methods like append(), extend(), remove() modify in-place."
]
},
4:{
def:"Dictionaries are unordered collections of key-value pairs. Keys must be unique and immutable (strings, numbers, tuples). Dictionaries are mutable and provide O(1) lookup.",
examples:[
{title:"Dictionary Basics",code:`# Creating dictionaries
person = {
"name": "Alice",
"age": 25,
"city": "New York",
"skills": ["Python", "JavaScript"]
}
# Accessing values
print(person["name"]) # Alice
print(person.get("age")) # 25
print(person.get("email", "N/A")) # N/A (default)
# Adding/updating items
person["email"] = "alice@example.com"
person["age"] = 26
# Deleting items
del person["city"]
removed = person.pop("email")`},
{title:"Dictionary Methods",code:`data = {"a": 1, "b": 2, "c": 3}
# Get keys, values, items
print(data.keys()) # dict_keys(['a', 'b', 'c'])
print(data.values()) # dict_values([1, 2, 3])
print(data.items()) # dict_items([('a', 1), ('b', 2)])
# Iteration
for key in data:
print(f"{key}: {data[key]}")
for key, value in data.items():
print(f"{key} = {value}")
# Update dictionary
data.update({"d": 4, "e": 5})
print(data) # {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}`},
{title:"Nested Dictionaries",code:`student = {
"name": "Bob",
"grades": {
"math": 95,
"english": 88,
"science": 92
},
"courses": ["Math", "English", "Science"]
}
# Accessing nested data
print(student["grades"]["math"]) # 95
print(student["courses"][0]) # Math
# Dict comprehension
squares = {x: x**2 for x in range(5)}
# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}`}
],
explanations:[
"Dictionaries use hash tables for fast key lookup - O(1) average case.",
"Keys must be hashable (immutable): strings, numbers, tuples, etc.",
"Use get() with a default value to safely access potentially missing keys.",
"Dictionary comprehensions create dictionaries from expressions.",
"Items can be any type: lists, dicts, functions, etc."
]
},
5:{
def:"Control flow statements (if, elif, else) allow you to execute different code blocks based on conditions. They're fundamental to conditional logic.",
examples:[
{title:"If/Else Statements",code:`age = 18
name = "Alice"
# Simple if
if age >= 18:
print("You are an adult")
# if/else
if age >= 18:
print("Adult")
else:
print("Minor")
# if/elif/else
if age < 13:
print("Child")
elif age < 18:
print("Teenager")
else:
print("Adult")`},
{title:"Comparison Operators",code:`x = 10
y = 20
# Equality
print(x == y) # False
print(x != y) # True
# Comparison
print(x < y) # True
print(x <= y) # True
print(x > y) # False
print(x >= y) # False
# Identity
a = [1, 2, 3]
b = [1, 2, 3]
c = a
print(a == b) # True (same value)
print(a is b) # False (different objects)
print(a is c) # True (same object)`},
{title:"Logical Operators",code:`age = 25
income = 50000
# and - both conditions must be True
if age >= 18 and income > 30000:
print("Eligible for loan")
# or - at least one must be True
if age < 18 or income < 20000:
print("Need co-signer")
# not - negation
active = False
if not active:
print("Account inactive")
# Complex conditions
if (age >= 21 and income > 40000) or age < 18:
print("Special category")`}
],
explanations:[
"Conditions evaluate to boolean: True or False.",
"Python uses indentation to define code blocks.",
"Truth values: 0, None, empty collections are falsy; others are truthy.",
"Use is for object identity, == for value equality.",
"Logical operators short-circuit: 'and' stops at first False, 'or' at first True."
]
},
6:{
def:"Loops (for, while) repeat code blocks multiple times. for loops iterate over sequences; while loops repeat until a condition is false.",
examples:[
{title:"For Loops",code:`# Iterating over a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# Iterating with index
for i, fruit in enumerate(fruits):
print(f"{i}: {fruit}")
# Range
for i in range(5):
print(i) # 0, 1, 2, 3, 4
# Range with start, stop, step
for i in range(1, 10, 2):
print(i) # 1, 3, 5, 7, 9
# Nested loops
for i in range(3):
for j in range(2):
print(f"({i}, {j})")`},
{title:"While Loops",code:`# Simple while loop
count = 0
while count < 5:
print(count)
count += 1
# While with break
while True:
user_input = input("Enter 'quit' to exit: ")
if user_input == "quit":
break
print(f"You entered: {user_input}")
# While with continue
n = 0
while n < 10:
n += 1
if n % 2 == 0:
continue # skip even numbers
print(n) # 1, 3, 5, 7, 9`},
{title:"Loop Control",code:`# break - exit loop
for i in range(10):
if i == 5:
break
print(i) # 0, 1, 2, 3, 4
# continue - skip iteration
for i in range(5):
if i == 2:
continue
print(i) # 0, 1, 3, 4
# else clause (runs if loop completes)
for i in range(3):
print(i)
else:
print("Loop completed") # This runs
# else with break (doesn't run if break occurs)
for i in range(3):
if i == 1:
break
else:
print("This won't print")`}
],
explanations:[
"for loops iterate over any iterable: lists, tuples, strings, dictionaries, etc.",
"enumerate() provides both index and value in a for loop.",
"break exits the loop completely; continue skips to next iteration.",
"range(n) creates numbers 0 to n-1; range(a,b,c) for start, stop, step.",
"The else clause executes if loop finishes normally (not via break)."
]
},
7:{
def:"Functions are reusable blocks of code that accept parameters and return values. They promote code reuse, organization, and maintainability.",
examples:[
{title:"Function Basics",code:`# Simple function
def greet():
print("Hello!")
greet() # Hello!
# Function with parameters
def add(a, b):
return a + b
result = add(5, 3)
print(result) # 8
# Multiple parameters
def describe(name, age, city="Unknown"):
return f"{name}, {age} years old, from {city}"
print(describe("Alice", 25, "NYC"))
print(describe("Bob", 30)) # Uses default`},
{title:"Parameter Types",code:`# Positional arguments
def power(base, exponent):
return base ** exponent
print(power(2, 3)) # 8
# Keyword arguments
print(power(exponent=3, base=2)) # 8
# Default arguments
def greet(name="Guest"):
return f"Hello, {name}!"
print(greet()) # Hello, Guest!
print(greet("Alice")) # Hello, Alice!
# *args (variable positional arguments)
def sum_all(*args):
return sum(args)
print(sum_all(1, 2, 3, 4, 5)) # 15
# **kwargs (variable keyword arguments)
def print_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
print_info(name="Alice", age=25, city="NYC")`},
{title:"Return Values & Documentation",code:`# Multiple return values
def min_max(numbers):
return min(numbers), max(numbers)
minimum, maximum = min_max([3, 1, 4, 1, 5, 9])
print(f"Min: {minimum}, Max: {maximum}")
# Docstrings
def calculate_area(radius):
"""
Calculate the area of a circle.
Args:
radius: The radius of the circle
Returns:
The area of the circle
"""
import math
return math.pi * radius ** 2
print(calculate_area(5))
print(calculate_area.__doc__) # Access docstring`}
],
explanations:[
"Parameters are placeholders; arguments are actual values passed.",
"*args collects extra positional arguments into a tuple.",
"**kwargs collects keyword arguments into a dictionary.",
"Functions can return multiple values as a tuple.",
"Docstrings document functions - use triple quotes and follow PEP 257."
]
},
8:{
def:"List comprehensions provide a concise way to create new lists by applying an operation to each item in an existing list. They're faster and more readable than loops.",
examples:[
{title:"Basic List Comprehension",code:`# Traditional approach
squares_old = []
for x in range(5):
squares_old.append(x ** 2)
# List comprehension
squares = [x ** 2 for x in range(5)]
print(squares) # [0, 1, 4, 9, 16]
# More complex example
words = ["hello", "world", "python"]
lengths = [len(word) for word in words]
print(lengths) # [5, 5, 6]
# String transformation
sentence = "hello world"
uppercase = [char.upper() for char in sentence]
print(''.join(uppercase)) # HELLO WORLD`},
{title:"Comprehension with Conditions",code:`# Filter even numbers
numbers = range(10)
evens = [x for x in numbers if x % 2 == 0]
print(evens) # [0, 2, 4, 6, 8]
# Multiple conditions
results = [x for x in range(10) if x > 3 if x < 8]
print(results) # [4, 5, 6, 7]
# Nested comprehension (cartesian product)
pairs = [(x, y) for x in range(3) for y in range(2)]
print(pairs)
# [(0, 0), (0, 1), (1, 0), (1, 1), (2, 0), (2, 1)]
# With transformation
sentences = ["hello world", "python rocks"]
words = [word for sentence in sentences for word in sentence.split()]
print(words) # ['hello', 'world', 'python', 'rocks']`},
{title:"Dictionary & Set Comprehensions",code:`# Dictionary comprehension
numbers = [1, 2, 3, 4, 5]
squares_dict = {x: x**2 for x in numbers}
print(squares_dict) # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
# From existing dict
dict_lower = {'a': 1, 'b': 2, 'c': 3}
dict_upper = {k.upper(): v for k, v in dict_lower.items()}
print(dict_upper) # {'A': 1, 'B': 2, 'C': 3}
# Set comprehension
numbers = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
unique_squares = {x**2 for x in numbers}
print(unique_squares) # {1, 4, 9, 16}`}
],
explanations:[
"List comprehensions are 2-3 times faster than equivalent for loops.",
"Syntax: [expression for item in iterable if condition].",
"Can include multiple for clauses and multiple if clauses.",
"Dictionary and set comprehensions follow similar patterns.",
"Nested comprehensions are powerful but can reduce readability if overused."
]
},
9:{
def:"Lambda functions are anonymous, inline functions defined with the lambda keyword. They're useful for short, simple operations passed to higher-order functions.",
examples:[
{title:"Lambda Basics",code:`# Simple lambda
square = lambda x: x ** 2
print(square(5)) # 25
# Lambda with multiple parameters
add = lambda x, y: x + y
print(add(3, 4)) # 7
# Lambda with default arguments
greet = lambda name="Guest": f"Hello, {name}!"
print(greet()) # Hello, Guest!
print(greet("Alice")) # Hello, Alice!
# Lambda in list
operations = [
lambda x: x + 1,
lambda x: x * 2,
lambda x: x ** 2
]
for op in operations:
print(op(5)) # 6, 10, 25`},
{title:"Lambda with map()",code:`numbers = [1, 2, 3, 4, 5]
# Multiply each by 2
doubled = list(map(lambda x: x * 2, numbers))
print(doubled) # [2, 4, 6, 8, 10]
# Convert to strings
strings = list(map(lambda x: str(x), numbers))
print(strings) # ['1', '2', '3', '4', '5']
# Nested structures
pairs = [(1, 2), (3, 4), (5, 6)]
sums = list(map(lambda p: p[0] + p[1], pairs))
print(sums) # [3, 7, 11]`},
{title:"Lambda with sort()",code:`# Sort list of tuples by second element
students = [
("Alice", 85),
("Bob", 92),
("Charlie", 78),
("David", 88)
]
sorted_by_score = sorted(students, key=lambda s: s[1])
print(sorted_by_score)
# [('Charlie', 78), ('Alice', 85), ('David', 88), ('Bob', 92)]
# Reverse sort
sorted_reverse = sorted(students, key=lambda s: s[1], reverse=True)
# Sort by name length
sorted_by_name_len = sorted(students, key=lambda s: len(s[0]))`}
],
explanations:[
"Lambda syntax: lambda arguments: expression (returns expression value).",
"Lambdas are best for simple, single-expression functions.",
"Can't include statements (if, for, try) in lambdas - use def instead.",
"Lambdas are often used with map(), filter(), sorted(), and custom functions.",
"Avoid overuse - readability matters more than brevity."
]
},
10:{
def:"Exception handling allows you to gracefully handle errors without crashing your program. Use try/except/finally blocks to catch and handle exceptions.",
examples:[
{title:"Try/Except Basics",code:`# Catching a specific exception
try:
x = int("hello") # ValueError
except ValueError:
print("Invalid number format!")
# Catching multiple exceptions
try:
result = 10 / 0 # ZeroDivisionError
except (ValueError, ZeroDivisionError) as e:
print(f"An error occurred: {e}")
# Catching all exceptions (use cautiously!)
try:
risky_operation()
except Exception as e:
print(f"Error: {e}")
# Exception object
try:
x = [1, 2, 3][5]
except IndexError as e:
print(f"Index error: {e}")
print(f"Error type: {type(e).__name__}")`},
{title:"Multiple Except Blocks",code:`try:
user_input = input("Enter age: ")
age = int(user_input)
year_born = 2024 - age
except ValueError:
print("Age must be a number!")
except KeyboardInterrupt:
print("Input cancelled by user")
except Exception as e:
print(f"Unexpected error: {e}")
else:
# Runs if no exception occurred
print(f"You were born around {year_born}")
finally:
# Always runs, even if exception occurred
print("Thank you for using this program!")`},
{title:"Custom Exceptions & Raising",code:`# Define custom exception
class InsufficientFundsError(Exception):
pass
# Raising exceptions
def withdraw(balance, amount):
if amount > balance:
raise InsufficientFundsError("Not enough funds!")
return balance - amount
try:
balance = 100
new_balance = withdraw(balance, 150)
except InsufficientFundsError as e:
print(f"Transaction failed: {e}")
# Re-raising exceptions
try:
try:
x = 1 / 0
except ZeroDivisionError:
print("Caught, now re-raising...")
raise # re-raises the same exception
except ZeroDivisionError:
print("Caught again!")`}
],
explanations:[
"Common exceptions: ValueError, TypeError, IndexError, KeyError, ZeroDivisionError.",
"Use specific exceptions, not bare except clauses, for better error handling.",
"The else block executes only if no exception occurred.",
"The finally block always executes - useful for cleanup (closing files, etc).",
"Create custom exceptions by inheriting from Exception class."
]
},
11:{
def:"Classes are blueprints for creating objects. Object-oriented programming (OOP) uses classes to structure data and behavior together into organized units.",
examples:[
{title:"Class Basics",code:`# Define a class
class Dog:
# Class variable (shared by all instances)
species = "Canis familiaris"
# Constructor
def __init__(self, name, age):
# Instance variables
self.name = name
self.age = age
# Method
def bark(self):
return f"{self.name} says Woof!"
def get_age(self):
return f"{self.name} is {self.age} years old"
# Create instances
dog1 = Dog("Buddy", 3)
dog2 = Dog("Max", 5)
print(dog1.name) # Buddy
print(dog1.bark()) # Buddy says Woof!
print(dog1.get_age()) # Buddy is 3 years old`},
{title:"Special Methods (Dunder Methods)",code:`class Person:
def __init__(self, name, age):
self.name = name
self.age = age
# String representation (for debugging)
def __repr__(self):
return f"Person({self.name}, {self.age})"
# String representation (for users)
def __str__(self):
return f"{self.name}, age {self.age}"
# Equality comparison
def __eq__(self, other):
return self.age == other.age
# Less than comparison
def __lt__(self, other):
return self.age < other.age
# Addition operator
def __add__(self, years):
return Person(self.name, self.age + years)
p1 = Person("Alice", 25)
print(str(p1)) # Alice, age 25
print(repr(p1)) # Person(Alice, 25)
p2 = Person("Bob", 25)
print(p1 == p2) # True (same age)
p3 = p1 + 5 # Creates new Person with age 30`},
{title:"Properties & Getters/Setters",code:`class Temperature:
def __init__(self, celsius):
self._celsius = celsius # private variable
# Property (acts like an attribute)
@property
def celsius(self):
return self._celsius
@property
def fahrenheit(self):
return (self._celsius * 9/5) + 32
# Setter
@celsius.setter
def celsius(self, value):
if value < -273.15:
raise ValueError("Temperature too low!")
self._celsius = value
temp = Temperature(0)
print(temp.celsius) # 0
print(temp.fahrenheit) # 32.0
temp.celsius = 100
print(temp.fahrenheit) # 212.0`}
],
explanations:[
"__init__ is the constructor - called when creating a new instance.",
"self refers to the instance; always the first parameter in methods.",
"Instance variables (self.x) are unique to each instance.",
"Class variables are shared across all instances.",
"Special methods (__method__) override built-in behavior and operators."
]
},
12:{
def:"Inheritance allows classes to inherit properties and methods from parent classes. Polymorphism allows objects to be treated as instances of their parent class.",
examples:[
{title:"Inheritance",code:`# Parent class
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return f"{self.name} makes a sound"
def move(self):
return "Moving..."
# Child class inherits from Animal
class Dog(Animal):
# Override method
def speak(self):
return f"{self.name} barks: Woof!"