-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlearn.html
More file actions
1659 lines (1555 loc) · 166 KB
/
Copy pathlearn.html
File metadata and controls
1659 lines (1555 loc) · 166 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" dir="ltr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="robots" content="index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1">
<meta name="theme-color" content="#0d1117" media="(prefers-color-scheme: dark)">
<meta name="theme-color" content="#f5f5f5" media="(prefers-color-scheme: light)">
<link rel="icon" href="/logo.png" type="image/png" sizes="32x32">
<link rel="icon" href="/logo.png" type="image/png" sizes="96x96">
<link rel="apple-touch-icon" href="/logo.png" sizes="180x180">
<link rel="shortcut icon" href="/logo.png" type="image/png">
<meta name="description" content="Learn Python online free with JometCode's 28 interactive lessons — from Hello World to async, decorators, regex, and context managers. Use the free online Python compiler to write and run real code in your browser. No signup, no install. Learn by doing.">
<meta name="keywords" content="learn Python online free, Python course for beginners, interactive Python tutorial, learn Python coding, Python from scratch, Python coding practice, free online Python compiler, Python for beginners to advanced, JometCode Python, Python programming course online, learn to code Python, Python lessons with examples, online Python compiler with lessons, free Python IDE, online Python course free, Python for absolute beginners, step by step Python, Python crash course, Python fundamentals, variables loops functions Python, Python strings formatting, Python lists and loops, Python conditions if else, Python dictionaries sets, Python file I/O, Python error handling try except, Python lambda map filter, Python classes OOP, Python decorators explained, Python generators yield, Python modules imports, Python JSON handling, Python CSV tutorial, Python best practices, Python comments documentation, Python type conversion, Python input function, Python boolean operators, Python arithmetic operators, Python string methods, Python tuple vs list, Python sets tutorial, Python programming fundamentals
<meta property="og:title" content="JometCode — Learn Python Online Free | 28 Interactive Python Lessons & Compiler">
<meta property="og:description" content="Learn Python online free with JometCode's 28 interactive lessons. Write and run real Python code in the browser compiler. No signup, no install. Start coding now.">
<meta property="og:type" content="website">
<meta property="og:site_name" content="JometCode">
<meta property="og:url" content="https://majedql29-spec.github.io/JometCode/learn.html">
<meta property="og:image" content="https://majedql29-spec.github.io/JometCode/logo.png">
<meta property="og:image:width" content="512">
<meta property="og:image:height" content="512">
<meta property="og:locale" content="en_US">
<meta name="application-name" content="JometCode">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:title" content="JometCode — Learn Python Online Free | 28 Free Interactive Lessons & Compiler">
<meta name="twitter:description" content="Learn Python online free with JometCode's 28 interactive lessons. Write and run real Python code in the browser. No signup, no install.">
<meta name="twitter:image" content="https://majedql29-spec.github.io/JometCode/logo.png">
<meta name="author" content="JometCode">
<meta name="referrer" content="strict-origin-when-cross-origin">
<link rel="canonical" href="https://majedql29-spec.github.io/JometCode/learn.html">
<link rel="sitemap" href="https://majedql29-spec.github.io/JometCode/sitemap.xml" type="application/xml">
<link rel="stylesheet" href="/design.css">
<title>Learn Python Online Free — 28 Interactive Lessons & Online Python Compiler | JometCode</title>
<script type="application/ld+json">
[
{
"@context": "https://schema.org",
"@type": "BreadcrumbList",
"itemListElement": [{
"@type": "ListItem",
"position": 1,
"name": "Home",
"item": "https://majedql29-spec.github.io/JometCode"
},{
"@type": "ListItem",
"position": 2,
"name": "Learn Python",
"item": "https://majedql29-spec.github.io/JometCode/learn.html"
}]
},
{
"@context": "https://schema.org",
"@type": "Course",
"name": "Learn Python Online Free — 28 Interactive Lessons",
"description": "Learn Python online free with JometCode's 28 interactive lessons — from Hello World to async, decorators, regex, and context managers. Use the free online Python compiler to write and run real code in your browser, no setup needed.",
"url": "https://majedql29-spec.github.io/JometCode/learn.html",
"provider": {
"@type": "Organization",
"name": "JometCode",
"url": "https://majedql29-spec.github.io/JometCode",
"logo": "https://majedql29-spec.github.io/JometCode/logo.png"
},
"educationalLevel": "Beginner to Advanced",
"numberOfLessons": 28,
"teaches": [
"Python syntax and basics",
"Variables, data types, type conversion",
"Strings, string methods, formatting",
"Lists, tuples, sets, dictionaries",
"Control flow, conditionals, loops",
"Functions, lambda, map, filter",
"List comprehensions",
"Error handling with try/except",
"File handling",
"Working with JSON",
"Object-oriented programming",
"Modules and imports",
"Decorators",
"Generators and yield",
"Regular expressions (regex)",
"Working with dates and time",
"CSV file handling",
"Async programming (asyncio)",
"Context managers",
"Basic operators (arithmetic, comparison, logical)",
"Comments and documentation best practices",
"User input and formatted output",
"Type conversion and casting"
],
"datePublished": "2026-06-15",
"dateModified": "2026-07-01",
"audience": {
"@type": "Audience",
"audienceType": "Python beginners and intermediate programmers"
},
"learningResourceType": "Interactive lesson",
"isPartOf": {
"@id": "https://majedql29-spec.github.io/JometCode",
"@type": "WebSite",
"name": "JometCode",
"url": "https://majedql29-spec.github.io/JometCode"
}
},
{
"@context": "https://schema.org",
"@type": "WebPage",
"@id": "https://majedql29-spec.github.io/JometCode/learn.html",
"name": "Learn Python Online Free — Interactive Course",
"description": "Learn Python online free with JometCode's 28 interactive lessons. Use the free online Python compiler to write and run real code directly in your browser — from Hello World to advanced topics like async, decorators, and context managers.",
"url": "https://majedql29-spec.github.io/JometCode/learn.html",
"isPartOf": { "@id": "https://majedql29-spec.github.io/JometCode" }
},
{
"@context": "https://schema.org",
"@type": "LearningResource",
"name": "Master Python Programming — Interactive Course",
"description": "Interactive Python lessons with runnable code examples using the free online Python compiler — master Python at your own pace",
"educationalLevel": ["Beginner", "Intermediate", "Advanced"],
"timeRequired": "PT8H",
"typicalAgeRange": "14-99",
"inLanguage": "en-US",
"datePublished": "2026-06-15",
"dateModified": "2026-06-29"
}
]
</script>
<style>
*, *::before, *::after { margin: 0; padding: 0; box-sizing: border-box; }
body {
font-family: var(--font);
background: var(--bg-primary); color: var(--text-primary); display: flex; flex-direction: column; height: 100vh;
overflow: hidden;
}
a { text-decoration: none; color: inherit; }
/* ===== HEADER ===== */
header {
display: flex; align-items: center; justify-content: space-between;
padding: 0 24px; height: 56px; background: var(--bg-secondary); border-bottom: 1px solid var(--border); flex-shrink: 0;
position: relative; z-index: 10;
}
.header-left { display: flex; align-items: center; gap: 12px; }
.header-left .logo-link { display: flex; align-items: center; gap: 10px; color: inherit; }
.header-left .logo-link img { width: 26px; height: 26px; border-radius: 6px; }
.header-left .logo-link span { font-size: 17px; font-weight: 700; letter-spacing: -0.3px; color: var(--text-primary); }
.header-right { display: flex; align-items: center; gap: 8px; }
.btn-back {
background: transparent; color: #8b949e; border: 1px solid #30363d; font-weight: 500;
padding: 6px 14px; border-radius: 20px; font-size: 12px; cursor: pointer; transition: all 0.2s;
display: inline-flex; align-items: center; gap: 5px; font-family: inherit;
}
.btn-back:hover { border-color: #d9d9d9; color: #d9d9d9; background: rgba(217,217,217,0.05); }
body.light-mode .btn-back { color: #656d76; border-color: #d0d7de; }
body.light-mode .btn-back:hover { border-color: #222222; color: #222222; }
#themeToggle {
background: transparent; border: 1px solid #30363d; border-radius: 20px; padding: 6px 12px;
cursor: pointer; font-size: 14px; color: #8b949e; transition: all 0.2s;
}
#themeToggle:hover { border-color: #e6edf3; color: #e6edf3; }
body.light-mode #themeToggle { border-color: #d0d7de; color: #656d76; }
body.light-mode #themeToggle:hover { border-color: #1e1e1e; color: #1e1e1e; }
/* ===== LEARN PANEL ===== */
.learn-panel { display: flex; flex: 1; overflow: hidden; }
/* ===== SIDEBAR ===== */
.learn-sidebar {
width: 290px; flex: 0 0 auto; background: var(--bg-primary); border-right: 1px solid var(--border);
overflow-y: auto; padding: 16px 0 24px; display: flex; flex-direction: column;
}
.sidebar-header { padding: 0 20px 16px; border-bottom: 1px solid var(--border); margin-bottom: 8px; }
.sidebar-header h1 { font-size: 13px; color: var(--text-primary); font-weight: 600; margin-bottom: 10px; }
.progress-bar-wrap { height: 4px; background: var(--border); border-radius: 4px; overflow: hidden; margin-bottom: 8px; }
.progress-bar-fill { height: 100%; background: linear-gradient(90deg, var(--accent), var(--accent-hover)); border-radius: 4px; transition: width 0.5s ease; }
.progress-text { font-size: 11px; color: var(--text-muted); display: flex; justify-content: space-between; }
.progress-text span:last-child { color: var(--accent); font-weight: 500; }
.sidebar-section { margin-top: 4px; }
.sidebar-section-title {
font-size: 10px; color: #484f58; text-transform: uppercase; letter-spacing: 1.2px;
padding: 10px 20px 6px; font-weight: 600;
}
body.light-mode .sidebar-section-title { color: #888; }
/* ===== DONATE IN SIDEBAR ===== */
.sidebar-donate {
margin: 20px 16px 8px; padding: 16px; border-radius: 12px;
background: linear-gradient(135deg, rgba(245,158,11,0.06), rgba(217,217,217,0.04));
border: 1px solid rgba(245,158,11,0.12);
text-align: center;
}
body.light-mode .sidebar-donate { background: linear-gradient(135deg, rgba(245,158,11,0.03), rgba(217,217,217,0.02)); border-color: rgba(245,158,11,0.1); }
.sidebar-donate .sd-heart { font-size: 24px; margin-bottom: 6px; }
.sidebar-donate .sd-text { font-size: 11px; color: #8b949e; margin-bottom: 10px; line-height: 1.4; }
body.light-mode .sidebar-donate .sd-text { color: #888; }
.sidebar-donate .sd-btn {
background: transparent; border: 1px solid rgba(245,158,11,0.3); color: #d9d9d9;
padding: 6px 20px; border-radius: 20px; font-size: 12px; font-weight: 600;
cursor: pointer; transition: all 0.2s; font-family: inherit;
}
.sidebar-donate .sd-btn:hover { background: rgba(245,158,11,0.1); border-color: #d9d9d9; }
/* ===== DONATE OVERLAY (learn page) ===== */
#donateOverlay {
position: fixed; inset: 0; z-index: 999999;
background: rgba(0,0,0,0.6); backdrop-filter: blur(6px);
display: none; align-items: center; justify-content: center; padding: 20px;
}
#donateOverlay.open { display: flex; }
.donate-box {
width: 100%; max-width: 380px; background: var(--bg-card);
border: 1px solid var(--border); border-radius: var(--radius-xl); padding: 32px 24px 24px;
text-align: center; box-shadow: var(--shadow-lg);
animation: dFade 0.3s ease; position: relative;
}
@keyframes dFade { from { opacity: 0; transform: translateY(20px); } to { opacity: 1; transform: translateY(0); } }
.donate-x { position: absolute; top: 12px; right: 16px; background: none; border: none; color: #8b949e; font-size: 18px; cursor: pointer; }
.donate-x:hover { color: #e6edf3; }
.donate-h { font-size: 32px; margin-bottom: 8px; }
.donate-cards { display: flex; flex-direction: column; gap: 10px; }
.d-card { background: #0d1117; border: 1px solid #21262d; border-radius: 10px; padding: 12px; text-align: left; }
.d-label { font-size: 11px; color: #8b949e; margin-bottom: 4px; }
.d-addr { font-size: 11px; color: #e6edf3; word-break: break-all; font-family: monospace; margin-bottom: 6px; }
.d-copy { background: #21262d; border: 1px solid #30363d; border-radius: 6px; color: #e6edf3; padding: 4px 12px; font-size: 11px; cursor: pointer; }
.d-copy:hover { border-color: #d9d9d9; }
body.light-mode #donateOverlay { background: rgba(0,0,0,0.3); }
body.light-mode .donate-box { background: #fff; border-color: #d0d7de; }
body.light-mode .donate-x { color: #888; }
body.light-mode .d-card { background: #f6f8fa; border-color: #e0e0e0; }
body.light-mode .d-addr { color: #1e1e1e; }
body.light-mode .d-copy { background: #e9ecef; border-color: #d0d7de; color: #1e1e1e; }
.learn-lesson {
padding: 9px 20px 9px 20px; cursor: pointer; color: var(--text-secondary); font-size: 13px;
transition: all 0.18s ease; border-left: 3px solid transparent;
display: flex; align-items: center; gap: 10px; position: relative;
}
.learn-lesson:hover { background: var(--bg-hover); color: var(--text-primary); }
.learn-lesson.active {
background: var(--bg-hover); border-left-color: var(--accent); color: var(--text-primary); font-weight: 500;
}
.lesson-status { width: 18px; height: 18px; flex-shrink: 0; display: flex; align-items: center; justify-content: center; }
.lesson-status .dot { width: 8px; height: 8px; border-radius: 50%; background: var(--border); transition: all 0.3s; }
.learn-lesson.active .lesson-status .dot { background: var(--accent); box-shadow: 0 0 8px var(--accent-glow); }
.learn-lesson.completed .lesson-status .dot { background: var(--accent-hover); }
.learn-lesson.completed .lesson-status .dot::after { content: '\2713'; color: #fff; font-size: 11px; display: flex; align-items: center; justify-content: center; width: 100%; height: 100%; }
.lesson-label { flex: 1; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.lesson-badge {
font-size: 9px; padding: 2px 7px; border-radius: 10px; font-weight: 500;
background: var(--accent-dim); color: var(--accent); flex-shrink: 0;
}
.lesson-badge.int { background: rgba(88,166,255,0.1); color: #58a6ff; }
.lesson-badge.adv { background: rgba(210,153,34,0.1); color: #d29922; }
/* ===== CONTENT ===== */
.learn-content {
flex: 1; overflow-y: auto; background: var(--bg-secondary); position: relative;
}
.reading-progress {
position: sticky; top: 0; height: 3px; background: var(--border); z-index: 5;
}
.reading-progress-fill { height: 100%; width: 0%; background: linear-gradient(90deg, var(--accent), var(--accent-hover)); transition: width 0.1s linear; }
.learn-body {
padding: 40px 56px 48px; max-width: 800px; margin: 0 auto; animation: fadeIn 0.3s ease;
}
@keyframes fadeIn { from { opacity: 0; transform: translateY(8px); } to { opacity: 1; transform: translateY(0); } }
.lesson-header { margin-bottom: 28px; }
.lesson-number { font-size: 12px; color: var(--text-muted); font-weight: 500; margin-bottom: 4px; }
.lesson-title { font-size: 26px; font-weight: 700; color: var(--text-primary); letter-spacing: -0.5px; line-height: 1.3; margin-bottom: 12px; }
.lesson-meta { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }
.lesson-meta .badge {
font-size: 11px; padding: 3px 10px; border-radius: 20px; font-weight: 500;
display: inline-flex; align-items: center; gap: 4px;
}
.lesson-meta .badge.beginner { background: var(--accent-dim); color: var(--accent); }
.lesson-meta .badge.intermediate { background: rgba(88,166,255,0.1); color: #58a6ff; }
.lesson-meta .badge.advanced { background: rgba(210,153,34,0.1); color: #d29922; }
.lesson-meta .time { font-size: 12px; color: var(--text-secondary); }
.lesson-body { font-size: 15px; line-height: 1.85; color: var(--text-primary); }
.lesson-body p { margin-bottom: 18px; }
.lesson-body ul, .lesson-body ol { margin: 0 0 18px 0; padding-left: 24px; line-height: 2; }
body.light-mode .lesson-body ul, body.light-mode .lesson-body ol { color: #333; }
.lesson-body li { margin-bottom: 4px; }
.lesson-body strong { color: #e6edf3; }
body.light-mode .lesson-body strong { color: #1e1e1e; }
.lesson-body code {
background: rgba(217,217,217,0.08); padding: 2px 6px; border-radius: 4px;
font-family: 'Consolas','Courier New',monospace; font-size: 13px; color: #d9d9d9;
}
body.light-mode .lesson-body code { background: rgba(34,34,34,0.06); color: #222222; }
.lesson-body .tip {
background: rgba(217,217,217,0.05); border: 1px solid rgba(217,217,217,0.12);
border-radius: 12px; padding: 16px 20px; margin-bottom: 24px; font-size: 14px; line-height: 1.7;
display: flex; align-items: flex-start; gap: 10px;
}
.lesson-body .tip::before { content: '\1F4A1'; font-size: 16px; flex-shrink: 0; margin-top: 1px; }
.lesson-body .tip strong { color: #d9d9d9; }
body.light-mode .lesson-body .tip { background: rgba(34,34,34,0.03); border-color: rgba(34,34,34,0.1); }
body.light-mode .lesson-body .tip strong { color: #222222; }
/* ===== CODE BLOCK ===== */
.code-wrap {
margin: 24px 0; border-radius: var(--radius-lg); overflow: hidden;
border: 1px solid var(--border); background: var(--bg-primary);
}
.code-header {
display: flex; align-items: center; justify-content: space-between;
padding: 8px 16px; background: var(--bg-secondary); border-bottom: 1px solid var(--border);
}
.code-lang { font-size: 11px; color: var(--text-muted); font-weight: 500; }
.btn-copy {
background: transparent; border: 1px solid #30363d; color: #8b949e; font-size: 11px;
padding: 3px 10px; border-radius: 6px; cursor: pointer; font-family: inherit;
transition: all 0.2s; position: relative;
}
.btn-copy:hover { border-color: #d9d9d9; color: #d9d9d9; background: rgba(217,217,217,0.05); }
body.light-mode .btn-copy { border-color: #d0d7de; color: #656d76; }
body.light-mode .btn-copy:hover { border-color: #222222; color: #222222; }
.btn-copy.copied { border-color: #222222; color: #222222; background: rgba(234,88,12,0.1); }
.code-block {
padding: 20px; font-family: 'Consolas','Courier New',monospace; font-size: 14px; line-height: 1.65;
color: #e6edf3; overflow-x: auto; white-space: pre;
}
body.light-mode .code-block { color: #1e1e1e; }
.btn-run {
background: linear-gradient(135deg, #222222, #222222); color: #fff; border: none;
padding: 10px 24px; border-radius: 24px; font-size: 14px; font-weight: 600; cursor: pointer;
transition: all 0.25s; font-family: inherit; display: inline-flex; align-items: center; gap: 8px;
margin-top: 8px;
}
.btn-run:hover { transform: translateY(-2px); box-shadow: 0 6px 16px rgba(34,34,34,0.35); }
.btn-run:active { transform: translateY(0); }
.btn-run:disabled { opacity: 0.5; cursor: not-allowed; transform: none; }
/* ===== SCROLLBAR ===== */
::-webkit-scrollbar { width: 6px; height: 6px; }
::-webkit-scrollbar-track { background: transparent; }
::-webkit-scrollbar-thumb { background: #30363d; border-radius: 10px; }
::-webkit-scrollbar-thumb:hover { background: #484f58; }
body.light-mode ::-webkit-scrollbar-thumb { background: #d0d7de; }
body.light-mode ::-webkit-scrollbar-thumb:hover { background: #bbb; }
.learn-sidebar { scrollbar-width: thin; scrollbar-color: #30363d transparent; }
body.light-mode .learn-sidebar { scrollbar-color: #d0d7de transparent; }
.learn-content { scrollbar-width: thin; scrollbar-color: #30363d transparent; }
body.light-mode .learn-content { scrollbar-color: #d0d7de transparent; }
/* ===== NAVIGATION ===== */
.lesson-nav {
display: flex; justify-content: space-between; align-items: center;
margin-top: 40px; padding-top: 24px; border-top: 1px solid var(--border); gap: 12px;
}
.lesson-nav .nav-btn {
background: transparent; border: 1px solid var(--border); color: var(--text-secondary);
padding: 8px 18px; border-radius: 20px; font-size: 12px; font-weight: 500; cursor: pointer;
font-family: inherit; transition: all 0.2s; display: inline-flex; align-items: center; gap: 6px;
}
.lesson-nav .nav-btn:hover { border-color: var(--accent); color: var(--accent); background: var(--accent-dim); }
.lesson-nav .nav-btn:disabled { opacity: 0.3; cursor: default; }
.lesson-nav .nav-btn:disabled:hover { border-color: #30363d; color: #8b949e; background: transparent; }
body.light-mode .lesson-nav .nav-btn { border-color: #d0d7de; color: #656d76; }
body.light-mode .lesson-nav .nav-btn:hover { border-color: #222222; color: #222222; }
body.light-mode .lesson-nav .nav-btn:disabled:hover { border-color: #d0d7de; color: #656d76; background: transparent; }
.nav-center { font-size: 11px; color: #484f58; }
body.light-mode .nav-center { color: #888; }
/* ===== KBD HINT ===== */
.kbd-hint {
position: fixed; bottom: 20px; right: 20px; z-index: 100;
background: #161b22; border: 1px solid #21262d; border-radius: 10px;
padding: 10px 14px; font-size: 11px; color: #484f58; display: flex; align-items: center; gap: 12px;
opacity: 0; transition: opacity 0.5s; pointer-events: none;
}
.kbd-hint.show { opacity: 1; }
body.light-mode .kbd-hint { background: #f6f8fa; border-color: #e0e0e0; color: #888; }
.kbd-hint kbd {
background: #21262d; border: 1px solid #30363d; border-radius: 4px; padding: 2px 6px;
font-size: 10px; color: #8b949e; font-family: inherit;
}
body.light-mode .kbd-hint kbd { background: #e8eaed; border-color: #d0d7de; color: #656d76; }
/* ===== RESPONSIVE ===== */
@media (max-width: 768px) {
.learn-panel { flex-direction: column; }
.learn-sidebar { width: 100%; max-height: 45vh; border-right: none; border-bottom: 1px solid #21262d; padding: 12px 0; }
body.light-mode .learn-sidebar { border-bottom-color: #e0e0e0; }
.learn-body { padding: 24px 20px 32px; }
.lesson-title { font-size: 20px; }
.lesson-body { font-size: 14px; }
header { padding: 0 16px; height: 48px; }
.header-left .logo-link span { font-size: 15px; }
.header-left .logo-link img { width: 22px; height: 22px; }
.btn-back { font-size: 11px; padding: 4px 10px; }
.lesson-nav { flex-wrap: wrap; justify-content: center; }
.kbd-hint { display: none; }
}
@media (max-width: 480px) {
.learn-sidebar { max-height: 35vh; }
.learn-body { padding: 16px; }
.code-block { font-size: 12px; padding: 14px; }
}
</style>
<script defer src="https://cloud.umami.is/script.js" data-website-id="e580f92e-6fd0-405b-bce3-f8d667558732"></script>
</head>
<body>
<h1 style="position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);border:0">Learn Python Online Free — Interactive Python Course with 28 Lessons & Online Compiler</h1>
<header>
<div class="header-left">
<a href="/" class="logo-link">
<img src="logo.png" alt="JometCode Python IDE"><span>JometCode</span>
</a>
</div>
<div class="header-right">
<a href="/" class="btn-back">← Back to Editor</a>
<button id="themeToggle" title="Toggle theme">☾</button>
</div>
</header>
<div class="learn-panel">
<div class="learn-sidebar" id="learnSidebar"></div>
<div class="learn-content" id="learnContent">
<div class="reading-progress"><div class="reading-progress-fill" id="readingProgress"></div></div>
<div class="learn-body" id="learnBody"></div>
</div>
</div>
<div class="kbd-hint" id="kbdHint"><span>Navigate lessons:</span> <kbd>←</kbd> <kbd>→</kbd></div>
<script>
// ===== LESSONS DATA =====
const LESSONS = [
{
title: "Hello, World!", level: "beginner", mins: 5,
code: `print("Hello, World!")`,
content: `
<p>Welcome to Python! The first program every programmer writes prints <code>"Hello, World!"</code> to the screen. Python makes this incredibly simple — just one line of code.</p>
<p>The <code>print()</code> function is built into Python and is one of the most frequently used functions you will ever use. It outputs whatever you put between the parentheses to the console. You can print text strings, numbers stored in variables, or the result of an expression. For example, <code>print(2 + 3)</code> will display <code>5</code>.</p>
<p>Strings can use single quotes <code>'...'</code> or double quotes <code>"..."</code> — Python treats them identically. The important rule is to pick one style and stay consistent within a single project. You can also use triple quotes <code>'''...'''</code> or <code>"""..."""</code> for multi-line strings that span several lines of text.</p>
<p>Notice that Python does not use semicolons at the end of lines, and it does not use curly braces to mark blocks of code. Instead, Python relies on indentation (spaces or tabs) to define structure. This makes Python code exceptionally clean and readable compared to many other languages.</p>
<p>Throughout this course, you will write and run real Python code directly in your browser. No installations, no configuration, no cost — everything runs safely on our servers and the results appear instantly. You can experiment freely without worrying about breaking anything.</p>
<p><strong>A quick look at the editor:</strong> On the left side is the code editor where you type Python code. Above it, you will find buttons to run your code and open it in the full JometCode IDE. Below the code area is the lesson explanation. The output of your code appears after you click run.</p>
<div class="tip"><strong>Try it:</strong> Change the message from "Hello, World!" to something personal like "Hello from [your name]!" and run it. Then try printing a number: <code>print(2024)</code> or an expression: <code>print(10 * 5)</code>. Experiment freely!</div>
`
},
{
title: "Variables & Data Types", level: "beginner", mins: 8,
code: `name = "JometCode"
age = 2
pi = 3.14
is_fun = True
print(f"Welcome to {name}, age {age}, pi = {pi}, is it fun? {is_fun}")`,
content: `
<p>Variables are named containers that store data in your program's memory. Think of them as labeled boxes — you put a value inside, give it a descriptive name, and later retrieve that value by using the name. In Python, you create a variable simply by assigning a value with the <code>=</code> sign. No type declaration is needed — Python infers the type automatically from the value you assign.</p>
<p>Python's fundamental data types form the building blocks of every program:</p>
<ul>
<li><strong>int</strong> — whole numbers: <code>42</code>, <code>-7</code>, <code>0</code>, <code>1_000_000</code> (underscores can separate digits for readability)</li>
<li><strong>float</strong> — decimal numbers: <code>3.14</code>, <code>-0.5</code>, <code>2.0</code>, <code>1.5e10</code> (scientific notation)</li>
<li><strong>str</strong> — text strings: <code>"hello"</code>, <code>'Python'</code>, <code>"42"</code> (even digits inside quotes become text)</li>
<li><strong>bool</strong> — logical values: <code>True</code> or <code>False</code> (note the capital letters — Python is case-sensitive)</li>
</ul>
<p>Python is <strong>dynamically typed</strong>, which means a variable can change type during execution. A variable that starts as an integer can later hold a string without any special syntax. This flexibility makes Python fast to write, but it also means you need to be mindful of what type a variable holds at any given moment. Use the built-in <code>type()</code> function to inspect the type: <code>type(42)</code> returns <code><class 'int'></code>.</p>
<p>You can also assign the same value to multiple variables in one line: <code>x = y = z = 0</code>. Or swap two variables without a temporary variable: <code>a, b = b, a</code> — Python handles this gracefully using tuple unpacking.</p>
<p><strong>Common mistake to avoid:</strong> Confusing <code>=</code> (assignment) with <code>==</code> (comparison). Writing <code>if x = 5</code> will cause a syntax error. Always use double equals when checking equality.</p>
<div class="tip"><strong>Naming rules:</strong> Variable names must start with a letter or underscore, contain only letters, digits, and underscores, and are case-sensitive (<code>score</code> and <code>Score</code> are different). Descriptive names like <code>user_age</code> or <code>total_price</code> make your code much easier to read than short names like <code>x</code> or <code>y</code>.</div>
`
},
{
title: "Strings & Formatting", level: "beginner", mins: 7,
code: `name = "JometCode"
lang = "Python"
# f-strings (Python 3.6+)
print(f"{name} is a free online {lang} IDE")
# Methods
print(lang.upper())
print(lang.lower())
print(len(lang))`,
content: `
<p>Strings are sequences of characters — letters, digits, spaces, symbols, and even emojis. They are one of the most common data types in Python, used everywhere from user interfaces to data processing. You can create a string by wrapping characters in matching quotes: single, double, or triple for multi-line strings.</p>
<p>The best way to embed values inside strings is with <strong>f-strings</strong> (available since Python 3.6). Prefix the string with <code>f</code> and insert variables directly using curly braces: <code>f"Hello, {name}! You are {age} years old."</code>. You can even put expressions inside the braces: <code>f"Next year you will be {age + 1}"</code> or call methods: <code>f"Uppercase: {name.upper()}"</code>. F-strings are the modern, recommended approach — they are faster, cleaner, and more readable than older alternatives.</p>
<p>Before f-strings, developers used <strong>concatenation</strong> with the <code>+</code> operator (<code>"Hello " + name</code>) or the <code>.format()</code> method (<code>"Hello {}".format(name)</code>). Both work, but f-strings are superior in every way and are the standard in modern Python code.</p>
<p>Strings also offer a rich collection of built-in <strong>methods</strong> for text manipulation:</p>
<ul>
<li><code>.upper()</code> — converts the entire string to uppercase</li>
<li><code>.lower()</code> — converts the entire string to lowercase</li>
<li><code>.strip()</code> — removes leading and trailing whitespace (spaces, tabs, newlines)</li>
<li><code>.startswith()</code> and <code>.endswith()</code> — check how the string begins or ends</li>
<li><code>.count()</code> — counts how many times a substring appears</li>
</ul>
<p>The built-in <code>len()</code> function returns the number of characters in a string, including spaces and punctuation. Remember that strings are <strong>immutable</strong> — methods like <code>.upper()</code> do not modify the original string; they return a new one. You must assign the result back to a variable if you want to keep the change.</p>
<p><strong>Common mistake:</strong> Trying to modify a character directly with <code>text[0] = "H"</code> will raise a <code>TypeError</code>. Strings do not support item assignment. Instead, create a new string using slicing or <code>.replace()</code>.</p>
<div class="tip"><strong>Try it:</strong> Add <code>.strip()</code> before <code>.upper()</code> in the code to see method chaining in action: <code>text.strip().upper()</code>. Then try <code>text.count("o")</code> to count letter occurrences.</div>
`
},
{
title: "Lists & Loops", level: "beginner", mins: 10,
code: `fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
print()
# Range loop
for i in range(5):
print(i, end=" ")`,
content: `
<p>A <strong>list</strong> is an ordered collection of items that can hold any data type — numbers, strings, booleans, or even other lists. You create a list with square brackets: <code>fruits = ["apple", "banana", "cherry"]</code>. Lists are one of the most versatile and frequently used data structures in Python.</p>
<p>Access individual items by their <strong>index</strong>. Python uses zero-based indexing, meaning the first item is at position <code>0</code>, not <code>1</code>: <code>fruits[0]</code> returns <code>"apple"</code>, <code>fruits[1]</code> returns <code>"banana"</code>. Negative indices count from the end of the list: <code>fruits[-1]</code> is the last item (<code>"cherry"</code>), <code>fruits[-2]</code> is the second-to-last. You can also use <strong>slicing</strong> to get a sublist: <code>fruits[1:3]</code> returns items at positions 1 and 2 (the end index is exclusive).</p>
<p>To iterate over a list, use a <strong>for loop</strong>. Python's for loop is a "for-each" style — the loop variable takes each value in the collection automatically, one at a time:</p>
<p><code>for fruit in fruits:<br> print(fruit)</code></p>
<p>This is more intuitive and less error-prone than traditional index-based loops found in languages like C or Java. If you need the index as you iterate, use <code>enumerate()</code>: <code>for i, fruit in enumerate(fruits):</code>.</p>
<p>The built-in <code>range(n)</code> function generates a sequence of numbers from 0 to n-1. You will often see it in combination with for loops: <code>for i in range(5): print(i)</code> prints 0 through 4. You can also specify a start and step: <code>range(2, 10, 2)</code> generates 2, 4, 6, 8.</p>
<p><strong>Key list operations:</strong></p>
<ul>
<li><code>.append(item)</code> — adds an item to the end</li>
<li><code>.insert(index, item)</code> — inserts at a specific position</li>
<li><code>.remove(item)</code> — removes the first occurrence of a value</li>
<li><code>.pop(index)</code> — removes and returns an item at a given index</li>
<li><code>.sort()</code> — sorts the list in place</li>
<li><code>len(list)</code> — returns the number of elements</li>
</ul>
<p>Lists are <strong>mutable</strong>, which means you can change, add, and remove elements after creation. This is different from tuples, which are fixed once created. Understanding when to use lists versus tuples is an important skill in Python programming.</p>
<div class="tip"><strong>Try it:</strong> After the loop, add <code>fruits.append("date")</code> and then loop again to see how lists grow dynamically. Then try <code>print(len(fruits))</code> to see the updated count.</div>
`
},
{
title: "Conditions & If/Else", level: "beginner", mins: 8,
code: `age = 18
if age >= 18:
print("You can vote!")
elif age >= 16:
print("Almost there!")
else:
print("Too young")
# Ternary
status = "Adult" if age >= 18 else "Minor"
print(status)`,
content: `
<p>Conditional statements let your program make decisions and execute different code paths based on certain conditions. They are the foundation of all logic in programming — without them, every program would run the same sequence of instructions every time, regardless of input or state.</p>
<p>Use <strong><code>if</code></strong> to check a primary condition, <strong><code>elif</code></strong> (short for "else if") to check additional conditions when the previous ones were false, and <strong><code>else</code></strong> as a catch-all fallback when no condition is met. The condition must evaluate to a boolean value — either <code>True</code> or <code>False</code>. Python treats certain values as "falsy": <code>0</code>, <code>None</code>, empty strings, empty lists — all evaluate to <code>False</code> in a boolean context.</p>
<p>Python uses <strong>indentation</strong> (typically 4 spaces) to define which statements belong to each branch. This is not a style suggestion — it is a required part of Python's syntax. Unlike C, Java, or JavaScript which use curly braces, Python's indentation-based structure makes code visually consistent and readable. Every line indented under an <code>if</code> runs when the condition is true. When the indentation returns to the previous level, the conditional block ends.</p>
<p>You can chain multiple conditions using <strong>logical operators</strong>:</p>
<ul>
<li><code>and</code> — both conditions must be true: <code>if age >= 18 and has_id:</code></li>
<li><code>or</code> — at least one condition must be true: <code>if is_admin or is_owner:</code></li>
<li><code>not</code> — inverts a condition: <code>if not logged_in:</code></li>
</ul>
<p>Python also offers a concise <strong>ternary operator</strong> (also called a conditional expression) for simple if/else assignments in a single line: <code>status = "Adult" if age >= 18 else "Minor"</code>. This is useful for quick conditional assignments but should be avoided for complex logic where readability would suffer.</p>
<p><strong>Common mistake to avoid:</strong> Using a single <code>=</code> (assignment) instead of <code>==</code> (equality comparison) inside a condition. Writing <code>if x = 5</code> will cause a <code>SyntaxError</code>. Always use <code>==</code> to compare values.</p>
<p><strong>Best practice:</strong> For checking if a value is <code>None</code>, use <code>is None</code> instead of <code>== None</code>. The <code>is</code> operator checks identity, which is the correct way to compare to <code>None</code>.</p>
<div class="tip"><strong>Try it:</strong> Change <code>age</code> to 16 and see how the output changes because the <code>elif</code> branch runs instead. Then try setting <code>age = 10</code> to trigger the <code>else</code> branch. Add a new <code>elif</code> condition of your own.</div>
`
},
{
title: "Functions", level: "beginner", mins: 10,
code: `def greet(name):
return f"Hello, {name}!"
def add(a, b):
return a + b
print(greet("JometCode"))
print(add(5, 3))`,
content: `
<p>Functions are reusable blocks of code that perform a specific task. They are the primary mechanism for organizing code, avoiding repetition (following the DRY principle — Don't Repeat Yourself), and making programs easier to read, test, and maintain. Think of a function as a mini-program within your program: it takes inputs, does work, and optionally produces an output.</p>
<p>Define a function with the <strong><code>def</code></strong> keyword, followed by the function name, parentheses that may contain parameters, and a colon. The function body is indented by one level (typically 4 spaces):</p>
<p><code>def greet(name):<br> """Return a personalized greeting."""<br> return f"Hello, {name}!"</code></p>
<p>Functions can accept <strong>parameters</strong> (also called arguments) that serve as inputs. They can <strong>return</strong> a value using the <code>return</code> keyword. The <code>return</code> statement immediately exits the function and sends the specified value back to the caller. If a function does not have a <code>return</code> statement, it implicitly returns <code>None</code> (Python's null value).</p>
<p>Once defined, you <strong>call</strong> a function by its name followed by parentheses containing any required arguments: <code>message = greet("JometCode")</code>. The returned value can be stored in a variable, printed, or used in an expression.</p>
<p><strong>Parameter features to know:</strong></p>
<ul>
<li><strong>Default parameters:</strong> You can assign default values: <code>def greet(name, greeting="Hello"):</code> — if the caller omits <code>greeting</code>, it defaults to <code>"Hello"</code></li>
<li><strong>Keyword arguments:</strong> Call functions by naming arguments: <code>greet(name="JometCode", greeting="Hi")</code> — order doesn't matter with keyword arguments</li>
<li><strong>Variable-length arguments:</strong> Use <code>*args</code> for any number of positional arguments and <code>**kwargs</code> for any number of keyword arguments</li>
</ul>
<p><strong>Best practices for writing good functions:</strong></p>
<ul>
<li>Give functions descriptive names that explain what they do — <code>calculate_average()</code> is better than <code>calc()</code></li>
<li>Each function should do exactly one thing and do it well (Single Responsibility Principle)</li>
<li>Keep functions short — if a function exceeds 20-30 lines, consider breaking it into smaller functions</li>
<li>Add a <strong>docstring</strong> (triple-quoted string) right after the definition to document what the function does</li>
</ul>
<p><strong>Common mistake:</strong> Forgetting to call the function (missing parentheses). Writing <code>greet</code> without parentheses returns the function object itself, not the result. Always use <code>greet("name")</code> with parentheses to actually execute the function.</p>
<div class="tip"><strong>Try it:</strong> Add a third function that takes three parameters and returns the average. Then call it and print the result. Experiment with default parameter values.</div>
`
},
{
title: "Basic Operators", level: "beginner", mins: 7,
code: `a = 10
b = 3
print("Addition:", a + b)
print("Subtraction:", a - b)
print("Multiplication:", a * b)
print("Division:", a / b)
print("Floor Div:", a // b)
print("Modulus:", a % b)
print("Power:", a ** b)
print("Is a > b?", a > b)
print("Is a == b?", a == b)`,
content: `
<p>Python supports a full set of mathematical and logical operators for working with numbers, making it an excellent language for everything from simple arithmetic to complex scientific computing. Python follows the standard order of operations (PEMDAS: Parentheses, Exponents, Multiplication/Division, Addition/Subtraction).</p>
<p><strong>Arithmetic operators:</strong></p>
<ul>
<li><code>+</code> addition and string concatenation</li>
<li><code>-</code> subtraction</li>
<li><code>*</code> multiplication and string repetition (<code>"Hi" * 3</code> gives <code>"HiHiHi"</code>)</li>
<li><code>/</code> division — always returns a <code>float</code>, even when dividing two integers (<code>6 / 3</code> returns <code>2.0</code>)</li>
<li><code>//</code> floor division — divides and rounds down to the nearest integer</li>
<li><code>%</code> modulus — returns the remainder of division, useful for checking even/odd numbers or cycling through ranges</li>
<li><code>**</code> exponentiation — raises a number to a power (<code>2 ** 3</code> returns <code>8</code>)</li>
</ul>
<p><strong>Comparison operators</strong> compare two values and return a boolean result:</p>
<ul>
<li><code>==</code> — equal to. Note the double equals — a single <code>=</code> is for assignment</li>
<li><code>!=</code> — not equal to</li>
<li><code>></code> — greater than</li>
<li><code><</code> — less than</li>
<li><code>>=</code> — greater than or equal</li>
<li><code><=</code> — less than or equal</li>
</ul>
<p><strong>Logical operators</strong> combine multiple boolean expressions:</p>
<ul>
<li><code>and</code> — true only if both sides are true</li>
<li><code>or</code> — true if at least one side is true</li>
<li><code>not</code> — inverts the boolean value</li>
</ul>
<p>Python also supports <strong>augmented assignment operators</strong> that combine an operation with assignment: <code>+=</code>, <code>-=</code>, <code>*=</code>, <code>/=</code>, etc. For example, <code>x += 5</code> is shorthand for <code>x = x + 5</code>. These operators are common in loops and accumulators.</p>
<p><strong>Important detail about <code>//</code>:</strong> Floor division always rounds down to the nearest integer. For positive numbers (<code>10 // 3 = 3</code>) this matches integer division. But for negative numbers, it rounds away from zero: <code>-10 // 3</code> gives <code>-4</code>, not <code>-3</code>. The <code>%</code> operator follows the same sign convention, so <code>-10 % 3</code> gives <code>2</code>. This behavior is mathematically consistent but can surprise newcomers.</p>
<p><strong>Quick tip:</strong> Use <code>% 2 == 0</code> to check if a number is even, and <code>% 2 == 1</code> for odd. The modulus operator is also useful for constraining values to a range, like wrapping around a circular buffer or creating repeating patterns.</p>
<div class="tip"><strong>Try it:</strong> Add a line using <code>%</code> to check if <code>a</code> is even: <code>print("a is even?", a % 2 == 0)</code>. Then experiment with <code>+=</code> by adding <code>a += 5</code> and printing <code>a</code> again.</div>
`
},
{
title: "String Methods", level: "beginner", mins: 8,
code: `text = " hello, PYTHON world! "
print("strip:", text.strip())
print("lower:", text.lower())
print("upper:", text.upper())
print("title:", text.title())
print("replace:", text.replace("world", "JometCode"))
words = text.strip().split(" ")
print("words:", words)
print("joined:", "-".join(words))`,
content: `
<p>Python strings come with a rich set of built-in methods that make text manipulation easy, readable, and efficient. Mastering these methods will save you countless lines of code and make your text processing significantly more elegant.</p>
<p><strong>Cleaning and trimming methods:</strong> <code>.strip()</code> removes whitespace (spaces, tabs, newlines) from both ends of a string. Use <code>.lstrip()</code> to remove only from the left side and <code>.rstrip()</code> to remove only from the right. These are essential when processing user input or reading data from files, where extra whitespace is common.</p>
<p><strong>Case conversion methods:</strong> <code>.lower()</code> converts the entire string to lowercase — extremely useful for case-insensitive comparisons. <code>.upper()</code> converts to uppercase. <code>.title()</code> capitalizes the first letter of every word. <code>.capitalize()</code> capitalizes only the very first character and lowercases everything else. And <code>.swapcase()</code> swaps uppercase to lowercase and vice versa.</p>
<p><strong>Splitting and joining — two of the most useful string operations:</strong></p>
<ul>
<li><code>.split()</code> breaks a string into a list of substrings. By default, it splits on any whitespace and discards empty strings. You can specify a separator: <code>"a,b,c".split(",")</code> returns <code>["a", "b", "c"]</code>. There is also <code>.rsplit()</code> which splits from the right.</li>
<li><code>.join()</code> is the inverse — it takes a list of strings and joins them into a single string with the separator. This is called on the separator string: <code>", ".join(["apple", "banana", "cherry"])</code> produces <code>"apple, banana, cherry"</code>. Notice that <code>.join()</code> is called on the separator, not on the list — this is a common point of confusion for beginners.</li>
</ul>
<p><strong>Searching and validation methods:</strong> <code>.find(substring)</code> returns the index of the first occurrence of a substring, or <code>-1</code> if not found. <code>.index()</code> is similar but raises a <code>ValueError</code> if not found. <code>.startswith(prefix)</code> and <code>.endswith(suffix)</code> return booleans and are very useful for conditional checks. <code>.count(substring)</code> returns the number of non-overlapping occurrences.</p>
<p><strong>Replacing and translating:</strong> <code>.replace(old, new)</code> replaces all occurrences of a substring with another. You can also pass an optional third argument to limit the number of replacements: <code>.replace("a", "o", 2)</code> replaces only the first two occurrences.</p>
<p>It is critical to remember that strings are <strong>immutable</strong>. None of these methods modify the original string — they all return a brand new string. If you want to keep the result, you must assign it to a variable: <code>cleaned = text.strip().lower()</code>.</p>
<p><strong>Method chaining:</strong> Because each method returns a new string, you can chain them together: <code>" Hello World ".strip().upper().replace("WORLD", "Python")</code> produces <code>"HELLO PYTHON"</code>. This is a powerful technique that lets you perform multiple transformations in a single line.</p>
<p><strong>Common mistake:</strong> Forgetting that strings are immutable. Writing <code>text.strip()</code> without assigning the result does nothing visible — the original string remains unchanged. Always capture the return value.</p>
<div class="tip"><strong>Try it:</strong> Add <code>text.startswith("hello")</code> and <code>text.find("world")</code> to the code. Then try chaining three or more methods together and observe the result.</div>
`
},
{
title: "Type Conversion", level: "beginner", mins: 6,
code: `# Implicit conversion
x = 5
y = 2.5
print(x + y)
# Explicit conversion
num_str = "42"
num_int = int(num_str)
num_float = float(num_str)
print(num_int + 8)
print(num_float + 0.5)
# To string
age = 25
print("I am " + str(age) + " years old")`,
content: `
<p>Type conversion is the process of changing a value from one data type to another. Python supports both <strong>implicit</strong> (automatic) and <strong>explicit</strong> (manual) conversion. Understanding how and when conversion happens is essential for writing correct and predictable code.</p>
<p><strong>Implicit conversion</strong> happens automatically when Python knows the conversion is safe and will not lose data. For example, when you add an <code>int</code> and a <code>float</code>, Python automatically converts the <code>int</code> to a <code>float</code> before performing the addition. This is because floats can represent all integer values, but integers cannot represent fractional values — converting in the direction of greater precision avoids data loss. The same applies when dividing integers with <code>/</code>: the result is always a <code>float</code>.</p>
<p><strong>Explicit conversion</strong> (also called <strong>casting</strong>) is when you manually convert a value using built-in functions. This is necessary when Python cannot infer the correct type or when you need to enforce a specific type:</p>
<ul>
<li><code>int(value)</code> — converts to an integer. Works with floats (truncates the decimal part) and numeric strings. For floats, it truncates toward zero: <code>int(3.9)</code> gives <code>3</code>, <code>int(-2.7)</code> gives <code>-2</code>.</li>
<li><code>float(value)</code> — converts to a float. Works with integers and numeric strings: <code>float("3.14")</code> gives <code>3.14</code>.</li>
<li><code>str(value)</code> — converts any value to its string representation. Essential for concatenating non-string values with strings.</li>
<li><code>bool(value)</code> — converts any value to a boolean. Values that convert to <code>False</code>: <code>0</code>, <code>0.0</code>, <code>""</code> (empty string), <code>[]</code> (empty list), <code>{}</code> (empty dict), <code>None</code>. Everything else is <code>True</code>.</li>
<li><code>list()</code>, <code>tuple()</code>, <code>set()</code> — convert between collection types: <code>list("hello")</code> gives <code>["h", "e", "l", "l", "o"]</code>.</li>
</ul>
<p><strong>Practical example:</strong> When you use <code>input()</code> in Python, the result is always a <strong>string</strong>. If you ask for a number and then try to do math, you must explicitly convert: <code>age = int(input("Enter your age: "))</code>. Forgetting to convert is one of the most common beginner mistakes. Always convert user input to the appropriate type before using it in calculations.</p>
<p><strong>Common mistake:</strong> Trying to convert a non-numeric string like <code>int("abc")</code> will raise a <code>ValueError</code>. Always validate your data before converting, or wrap the conversion in a try/except block to handle invalid input gracefully.</p>
<div class="tip"><strong>Try it:</strong> What happens when you convert <code>int(7.999)</code>? It gives <code>7</code>. Try converting a boolean: <code>int(True)</code> gives <code>1</code>, <code>int(False)</code> gives <code>0</code>. Then try <code>bool(0)</code> and <code>bool(42)</code> to see which values are truthy.</div>
`
},
{
title: "Sets & Tuples", level: "beginner", mins: 9,
code: `# Tuple (immutable)
point = (3, 4)
print("x:", point[0], "y:", point[1])
# Set (unique, unordered)
fruits = {"apple", "banana", "cherry", "apple"}
print("Set:", fruits)
# Set operations
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
print("Union:", a | b)
print("Intersection:", a & b)
print("Difference:", a - b)`,
content: `
<p>Beyond lists, Python offers two more essential collection types: <strong>tuples</strong> and <strong>sets</strong>. Each has specific use cases that make them invaluable in different situations. Choosing the right collection type is a key skill in writing idiomatic Python.</p>
<p><strong>Tuples</strong> are ordered sequences just like lists, but with one critical difference — they are <strong>immutable</strong>. Once created, a tuple cannot be changed: you cannot add, remove, or replace elements. This immutability makes tuples useful for data that should remain constant throughout your program, such as geographic coordinates <code>(latitude, longitude)</code>, RGB color values <code>(255, 128, 0)</code>, or configuration settings that must not be accidentally modified. Tuples are created with parentheses: <code>point = (3, 4)</code>. You access elements by index just like lists: <code>point[0]</code> gives <code>3</code>. You can also <strong>unpack</strong> a tuple into individual variables: <code>x, y = point</code> assigns <code>3</code> to <code>x</code> and <code>4</code> to <code>y</code>. This unpacking feature is used extensively in Python for clean, readable code.</p>
<p>Tuples are also <strong>hashable</strong> (if all their elements are hashable), which means they can be used as dictionary keys — something lists cannot do. For example, you can use a tuple as a key in a dictionary to store values by coordinates: <code>locations[(lat, lon)] = "Home"</code>.</p>
<p><strong>Sets</strong> are unordered collections of <strong>unique</strong> elements. The most important feature of a set is that duplicates are automatically removed. Sets are created with curly braces: <code>fruits = {"apple", "banana", "cherry", "apple"}</code> — the second <code>"apple"</code> is silently ignored. Because sets are unordered, you cannot access elements by index. However, this lack of ordering gives sets super-fast membership testing: checking if an element is in a set (<code>"apple" in fruits</code>) is much faster than checking a list, especially for large collections.</p>
<p><strong>Set operations — mathematically powerful:</strong></p>
<ul>
<li><strong>Union</strong> (<code>|</code>) — combines elements from both sets, removing duplicates: <code>{1, 2} | {2, 3}</code> gives <code>{1, 2, 3}</code></li>
<li><strong>Intersection</strong> (<code>&</code>) — elements present in both sets: <code>{1, 2, 3} & {2, 3, 4}</code> gives <code>{2, 3}</code></li>
<li><strong>Difference</strong> (<code>-</code>) — elements in the first set but not in the second: <code>{1, 2, 3} - {2, 3}</code> gives <code>{1}</code></li>
<li><strong>Symmetric difference</strong> (<code>^</code>) — elements in either set but not both: <code>{1, 2} ^ {2, 3}</code> gives <code>{1, 3}</code></li>
</ul>
<p><strong>Practical analogy:</strong> Think of a tuple as a sealed envelope (you can see what's inside but cannot change it), a set as a bag of unique marbles (no duplicates, fast to search), and a list as a shelf of books (ordered, you can rearrange and add more).</p>
<p><strong>Common mistake:</strong> Creating an empty set with <code>{}</code> actually creates an empty dictionary. To create an empty set, use <code>set()</code>. And remember that tuples with a single element need a trailing comma: <code>(1,)</code>, not just <code>(1)</code> which is just a number in parentheses.</p>
<div class="tip"><strong>Try it:</strong> Add <code>"apple" in fruits</code> to check membership, and print the result. Then try the symmetric difference operator <code>^</code> between sets <code>a</code> and <code>b</code>. Finally, try using a tuple as a dictionary key: <code>coords = {(0, 0): "origin", (1, 0): "right"}</code> and access <code>coords[(0, 0)]</code>.</div>
`
},
{
title: "Dictionaries", level: "intermediate", mins: 8,
code: `user = {
"name": "JometCode",
"age": 2,
"language": "Python"
}
print(user["name"])
user["version"] = "1.0"
for key, val in user.items():
print(f"{key}: {val}")`,
content: `
<p>Dictionaries store data as <strong>key-value pairs</strong>, making them one of Python's most versatile data structures. Each key is unique and maps to a value. Think of a real dictionary — you look up a word (key) and instantly get its definition (value). In code: <code>user = {"name": "Alice", "age": 30}</code>. Keys must be immutable types (strings, numbers, tuples), while values can be any type — lists, other dictionaries, functions, or even <code>None</code>.</p>
<p><strong>Essential dict methods:</strong></p>
<ul>
<li><code>.get(key, default)</code> — safely access a key without raising <code>KeyError</code>. Returns <code>default</code> (or <code>None</code>) if the key is missing: <code>user.get("email", "no email")</code>. This is the idiomatic way to handle optional keys.</li>
<li><code>.keys()</code> — returns a view of all keys. Useful for iteration or membership checks: <code>"name" in user.keys()</code>.</li>
<li><code>.values()</code> — returns a view of all values. Great for aggregation: <code>sum(scores.values())</code>.</li>
<li><code>.items()</code> — returns key-value pairs for unpacking in loops: <code>for k, v in user.items():</code>.</li>
<li><code>.setdefault(key, default)</code> — returns the value if the key exists, otherwise inserts the default and returns it. Perfect for building nested structures.</li>
<li><code>.update(other_dict)</code> — merges another dictionary into this one, overwriting existing keys.</li>
<li><code>.pop(key, default)</code> — removes a key and returns its value (or default if missing).</li>
</ul>
<p><strong>Nested dictionaries</strong> are dictionaries inside dictionaries — a common pattern for representing structured data like JSON API responses:</p>
<p><code>users = {<br> "alice": {"age": 30, "city": "NYC"},<br> "bob": {"age": 25, "city": "London"}<br>}<br>print(users["alice"]["city"]) # NYC</code></p>
<p>Access nested values safely by chaining <code>.get()</code>: <code>users.get("alice", {}).get("city")</code>. For deeply nested data, consider using <code>collections.defaultdict</code> or the <code>dict</code> approach with <code>setdefault</code>.</p>
<p><strong>Dict comprehensions</strong> offer a concise way to build dictionaries: <code>squares = {x: x**2 for x in range(5)}</code> produces <code>{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}</code>. Add conditions: <code>{x: x**2 for x in range(10) if x % 2 == 0}</code>. You can also transform keys and values: <code>{k.lower(): v for k, v in data.items()}</code>.</p>
<p><strong>When to use dict vs list:</strong> Use dictionaries when you need to look up values by a meaningful key (like a name or ID). Use lists when the order of items matters or when you need to store a simple sequence. Dictionaries excel at membership testing (<code>key in dict</code> is O(1) on average) and representing structured records. Lists excel at ordered iteration and sequential access.</p>
<p><strong>Common mistakes:</strong> Using <code>dict[key]</code> without checking if the key exists (raises <code>KeyError</code>). Always prefer <code>.get()</code> for optional keys. Another mistake is modifying a dictionary while iterating over it — create a copy with <code>.copy()</code> or iterate over <code>list(dict.keys())</code> instead. Also beware that <code>{}</code> creates an empty dict, not an empty set (use <code>set()</code> for that).</p>
<p><strong>Best practices:</strong> Use descriptive key names (strings or meaningful constants). Prefer <code>.get()</code> over direct indexing for optional keys. Use <code>.items()</code> for iteration to avoid looking up values by key. For counting or grouping, use <code>collections.Counter</code> or <code>defaultdict</code> instead of manual dict logic. Since Python 3.7, dictionaries preserve insertion order — rely on this for predictable iteration.</p>
<p><strong>Real-world use case:</strong> Dictionaries are the backbone of JSON data processing. When you call a REST API, the response is almost always parsed into nested dictionaries. Configuration files, user profiles, cached data, and database records are all naturally modeled as dictionaries. They are also used internally by Python for namespaces, class attributes, and instance data.</p>
<div class="tip"><strong>Try it:</strong> Add a nested dictionary with <code>user["address"] = {"city": "Paris", "zip": "75001"}</code> then print <code>user["address"]["city"]</code>. Then try a dict comprehension: <code>{k: v.upper() if isinstance(v, str) else v for k, v in user.items()}</code>. Finally, use <code>.get()</code> with a default to safely access a missing key.</div>
`
},
{
title: "List Comprehensions", level: "intermediate", mins: 10,
code: `nums = [1, 2, 3, 4, 5]
squares = [n**2 for n in nums]
evens = [n for n in nums if n % 2 == 0]
print("Squares:", squares)
print("Evens:", evens)`,
content: `
<p>List comprehensions provide a concise, expressive way to create lists based on existing iterables. They are a hallmark of Pythonic code — more readable, often faster, and less error-prone than traditional for loops. The basic syntax: <code>[expression for item in iterable]</code>. For example, <code>[x**2 for x in range(5)]</code> produces <code>[0, 1, 4, 9, 16]</code>.</p>
<p>Add an <strong>optional condition</strong> to filter items: <code>[expression for item in iterable if condition]</code>. Only items where the condition is <code>True</code> are included: <code>[n for n in range(20) if n % 3 == 0]</code> gives <code>[0, 3, 6, 9, 12, 15, 18]</code>. You can also use <code>if-else</code> expressions in the value part (before the <code>for</code>): <code>["even" if n % 2 == 0 else "odd" for n in range(5)]</code>.</p>
<p><strong>Nested comprehensions</strong> (comprehensions within comprehensions) handle multi-level data. To flatten a 2D list: <code>[item for row in matrix for item in row]</code> — this reads left-to-right as nested for loops, with the outer loop first. You can also create a 2D grid: <code>[[i * j for j in range(4)] for i in range(3)]</code>. Be careful: deeply nested comprehensions quickly become hard to read. A good rule is to avoid going more than two levels deep — beyond that, use regular nested for loops.</p>
<p><strong>Dict comprehensions</strong> and <strong>set comprehensions</strong> follow the same pattern but produce different collection types:</p>
<ul>
<li>Dict: <code>{key: value for item in iterable}</code> — e.g., <code>{x: chr(65 + x) for x in range(5)}</code> produces <code>{0: 'A', 1: 'B', 2: 'C', 3: 'D', 4: 'E'}</code></li>
<li>Set: <code>{expression for item in iterable}</code> — e.g., <code>{len(word) for word in ["hello", "world", "hi"]}</code> produces <code>{2, 5}</code></li>
<li>Generator (parentheses): <code>(expression for item in iterable)</code> — lazy evaluation, memory efficient (more on this in the Generators lesson)</li>
</ul>
<p><strong>Performance benefits:</strong> List comprehensions are typically 15-30% faster than equivalent for loops because they avoid the overhead of repeatedly calling <code>.append()</code> and use Python's optimized internal iteration. For simple transformations, they are also faster than <code>map()</code> with a lambda. However, for extremely large datasets, generator expressions are more memory-efficient since they produce items on demand.</p>
<p><strong>Readability guidelines:</strong> Use comprehensions when the logic is simple enough to fit on one or two lines. If you need to break it across multiple lines or include complex logic, a regular for loop is clearer. Avoid side effects inside comprehensions (like <code>print()</code> calls) — they are meant for building collections, not for executing statements. The Zen of Python says "Flat is better than nested" — prefer simple comprehensions over deeply nested ones.</p>
<p><strong>Real-world use cases:</strong> Transforming API response data (<code>[item["name"] for item in api_data]</code>), filtering logs (<code>[line for line in log_lines if "ERROR" in line]</code>), converting between data formats (<code>{user["id"]: user["name"] for user in users}</code>), and data cleaning (<code>[float(x) for x in raw_values if x.strip()]</code>).</p>
<p><strong>Common mistakes:</strong> Forgetting that the condition goes after the <code>for</code>, not before. Confusing nested comprehension order (the outer loop comes first — think "for row in matrix, for item in row"). Using comprehensions for their side effects instead of their result. Creating a list comprehension when a generator expression would use less memory.</p>
<div class="tip"><strong>Try it:</strong> Write a dict comprehension that maps each word in a list to its length: <code>{word: len(word) for word in ["apple", "banana", "cherry"]}</code>. Then write a nested comprehension to flatten <code>[[1,2], [3,4], [5,6]]</code>. Finally, use a set comprehension to find all unique vowels in a sentence.</div>
`
},
{
title: "Error Handling", level: "intermediate", mins: 7,
code: `try:
n = int(input("Enter a number: "))
print(10 / n)
except ValueError:
print("That's not a number!")
except ZeroDivisionError:
print("Can't divide by zero!")
else:
print("No errors!")
finally:
print("Done")`,
content: `
<p>Errors happen — users enter invalid input, files are missing, networks fail, data is corrupted. Instead of letting your program crash with an ugly traceback, you can <strong>handle exceptions</strong> gracefully using try/except blocks. Python's exception handling is both powerful and flexible, allowing you to respond to errors in fine-grained ways.</p>
<p><strong>The complete try/except/else/finally pattern:</strong></p>
<ul>
<li><strong>try</strong> — wrap code that might raise an exception here. If an error occurs, the rest of the try block is skipped immediately.</li>
<li><strong>except SomeError</strong> — catches a specific exception type. You can have multiple except blocks for different error types. Use <code>except Exception as e:</code> to capture the exception object and inspect its message (<code>str(e)</code>). A bare <code>except:</code> catches everything, including <code>SystemExit</code> and <code>KeyboardInterrupt</code> — avoid it or use <code>except Exception:</code> instead.</li>
<li><strong>else</strong> — runs only if no exception occurred in the try block. This is where you put "success path" code. It's better than putting it in the try block because it won't accidentally catch exceptions from unrelated code.</li>
<li><strong>finally</strong> — always runs, whether an exception happened or not. Ideal for cleanup: closing files, releasing locks, closing network connections, restoring state.</li>
</ul>
<p><strong>Exception hierarchy:</strong> Python exceptions are organized in a class hierarchy. <code>BaseException</code> is the root (don't catch this). <code>Exception</code> is the base for all built-in, non-system exceptions. Common subclasses include <code>ValueError</code> (wrong value), <code>TypeError</code> (wrong type), <code>IndexError</code> (list index out of range), <code>KeyError</code> (missing dict key), <code>FileNotFoundError</code> (missing file), <code>ZeroDivisionError</code> (division by zero), <code>AttributeError</code> (missing attribute), and <code>ImportError</code> (missing module). You can catch a parent type to handle a family of related exceptions: <code>except (ValueError, TypeError):</code>.</p>
<p><strong>Raising exceptions</strong> — sometimes you need to signal an error yourself: <code>raise ValueError("Invalid input")</code>. You can also re-raise the current exception inside an except block with bare <code>raise</code> (preserving the original traceback). Create <strong>custom exceptions</strong> by inheriting from <code>Exception</code>:</p>
<p><code>class InsufficientFundsError(Exception):<br> """Raised when account balance is too low."""<br> pass</code></p>
<p>Then raise and catch it like any built-in exception. Custom exceptions make your code's error handling more expressive and domain-specific.</p>
<p><strong>Common mistakes:</strong> Catching too broadly (<code>except:</code> or <code>except Exception:</code> when you only expect one type) — this can hide bugs. Not ordering except blocks from most-specific to least-specific (Python checks them in order, so a generic handler before a specific one will catch everything). Using exceptions for normal control flow — they should be for exceptional situations, not regular program logic. Swallowing exceptions silently with <code>except: pass</code> — at minimum log the error.</p>
<p><strong>Best practices:</strong> Catch only exceptions you can actually handle. Let unexpected exceptions propagate to the top level where they can be logged or shown to the user. Be as specific as possible about which exceptions you catch. Use <code>else</code> for success-path code to separate it from error-prone code in the try block. Use <code>finally</code> for cleanup that must happen regardless of success or failure. When raising exceptions, provide informative messages that help with debugging.</p>
<p><strong>Real-world use case:</strong> When processing user uploaded files, you might wrap the entire process: <code>try: data = parse_file(path)</code> — catching <code>FileNotFoundError</code> (file missing), <code>PermissionError</code> (no access), <code>json.JSONDecodeError</code> (malformed content), and <code>UnicodeDecodeError</code> (wrong encoding) — each with a different user-friendly error message, plus a <code>finally</code> block to clean up temporary files.</p>
<div class="tip"><strong>Try it:</strong> Add an <code>else</code> block to the code that prints a success confirmation. Add a <code>finally</code> that prints "Operation complete". Then create a custom exception class and raise it conditionally. Finally, try catching multiple exception types with a tuple: <code>except (ValueError, ZeroDivisionError) as e:</code>.</div>
`
},
{
title: "File Handling", level: "intermediate", mins: 8,
code: `with open("example.txt", "w") as f:
f.write("Hello from JometCode!")
with open("example.txt", "r") as f:
content = f.read()
print(content)`,
content: `
<p>Working with files is a fundamental task in programming. Python's <code>open()</code> function, combined with the <code>with</code> statement, makes file handling safe, simple, and reliable. The <code>with</code> statement creates a <strong>context manager</strong> that automatically closes the file when the block ends — even if an exception occurs. This is much safer than manually calling <code>.close()</code>, which can be skipped if an error happens before it.</p>
<p><strong>File modes determine how you interact with a file:</strong></p>
<ul>
<li><code>"r"</code> — read (default). The file must exist. Raises <code>FileNotFoundError</code> if missing.</li>
<li><code>"w"</code> — write. Creates a new file or overwrites an existing one (truncates to zero length).</li>
<li><code>"a"</code> — append. Adds content to the end of the file. Creates the file if it doesn't exist. Perfect for logs.</li>
<li><code>"x"</code> — exclusive creation. Creates a new file but raises <code>FileExistsError</code> if it already exists. Safe for preventing accidental overwrites.</li>
<li><code>"r+"</code> — read and write. Opens without truncating. The file must exist.</li>
</ul>
<p>Adding <code>b</code> to any mode (e.g., <code>"rb"</code>, <code>"wb"</code>) opens the file in <strong>binary mode</strong> for non-text files like images, audio files, or compiled data. In binary mode, data is read and written as <code>bytes</code> objects rather than strings. Adding <code>t</code> (e.g., <code>"rt"</code>) explicitly opens in text mode (the default).</p>
<p><strong>Reading from files:</strong> Beyond <code>.read()</code> which returns the entire content as one string, you can:</p>
<ul>
<li><code>.readline()</code> — reads one line at a time (including the trailing newline). Memory-efficient for large files.</li>
<li><code>.readlines()</code> — returns a list of all lines. Convenient but loads everything into memory.</li>
<li>Iterate directly: <code>for line in file:</code> — the most memory-efficient approach for large files, reading one line at a time without loading the entire file.</li>
</ul>
<p><strong>Writing:</strong> <code>.write(text)</code> writes a string. <code>.writelines(lines)</code> writes a list of strings without adding newlines — you must include them yourself. For appending, use mode <code>"a"</code>: <code>with open("log.txt", "a") as f: f.write("New entry\\n")</code>.</p>
<p><strong>File paths:</strong> Use raw strings or double backslashes on Windows to avoid escape sequences: <code>r"C:\\Users\\name\\file.txt"</code> or <code>"C:/Users/name/file.txt"</code> (forward slashes work on Windows too). The <code>os.path</code> module provides path manipulation utilities: <code>os.path.join("folder", "subfolder", "file.txt")</code> builds the correct path for your OS. Modern Python prefers <code>pathlib</code>: <code>from pathlib import Path; path = Path("folder") / "subfolder" / "file.txt"</code> — this is cleaner, cross-platform, and provides convenient methods like <code>.read_text()</code>, <code>.write_text()</code>, <code>.exists()</code>, <code>.suffix</code>, and <code>.stem</code>.</p>
<p><strong>Encoding:</strong> Files store bytes; encoding determines how bytes map to characters. Always specify the encoding when reading/writing text files: <code>open("file.txt", "r", encoding="utf-8")</code>. UTF-8 is the modern standard and supports every Unicode character. Omitting encoding can lead to <code>UnicodeDecodeError</code> on systems with different default encodings (like Windows, which may use cp1252).</p>
<p><strong>Common mistakes:</strong> Forgetting to close a file (solved by <code>with</code>). Not specifying encoding — leads to cross-platform bugs. Using <code>.read()</code> on a file that's too large to fit in memory — use line-by-line iteration instead. Forgetting that <code>"w"</code> overwrites existing content without warning — use <code>"x"</code> mode or check <code>os.path.exists()</code> first. Not handling <code>FileNotFoundError</code> when opening files for reading.</p>
<p><strong>Best practices:</strong> Always use <code>with open(...) as f:</code> — never call <code>.close()</code> manually. Always specify <code>encoding="utf-8"</code> for text files. Use <code>pathlib.Path</code> for modern, clean path handling. Process large files line-by-line rather than reading the entire file at once. Wrap file operations in try/except to handle <code>FileNotFoundError</code>, <code>PermissionError</code>, and <code>IOError</code>.</p>
<p><strong>Real-world use case:</strong> Processing a 2GB server log file: <code>with open("server.log", "r", encoding="utf-8") as f: for line in f: if "ERROR" in line: error_count += 1</code> — this processes the file line-by-line, using minimal memory regardless of file size. For writing: an application that logs user activity to <code>activity.log</code> in append mode, creating a new log file each day with the date as the filename using pathlib.</p>
<div class="tip"><strong>Try it:</strong> Change the code to read the file line by line using a for loop. Then try append mode <code>"a"</code> to add a second line and read the file again. Finally, use <code>pathlib.Path</code> to read the file: <code>from pathlib import Path; print(Path("example.txt").read_text())</code>.</div>
`
},
{
title: "Lambda Functions", level: "intermediate", mins: 7,
code: `# Lambda = anonymous function
square = lambda x: x ** 2
print(square(5))
add = lambda a, b: a + b
print(add(3, 7))
# Use with sorted
points = [(1, 5), (3, 2), (2, 8)]
points.sort(key=lambda p: p[1])
print("Sorted by y:", points)`,
content: `
<p>A <strong>lambda</strong> is a small, anonymous function defined with the <code>lambda</code> keyword. Unlike regular functions defined with <code>def</code>, lambdas are written in a single expression, have no name, and cannot contain statements or annotations. Syntax: <code>lambda arguments: expression</code>. The expression is evaluated and returned automatically — no <code>return</code> keyword needed: <code>lambda x, y: x + y</code> creates a function that adds two numbers.</p>
<p>Lambdas shine when you need a simple, throwaway function, especially as an argument to higher-order functions:</p>
<ul>
<li><strong>sorted() with a custom key:</strong> <code>students.sort(key=lambda s: s["grade"])</code> — sort a list of dicts by the "grade" field. Also works with <code>max()</code> and <code>min()</code>: <code>max(points, key=lambda p: p[1])</code> finds the tuple with the largest y-coordinate.</li>
<li><strong>map():</strong> <code>list(map(lambda x: x * 1.15, prices))</code> — apply a 15% tax to each price.</li>
<li><strong>filter():</strong> <code>list(filter(lambda x: len(x) > 5, words))</code> — keep only words longer than 5 characters.</li>
</ul>
<p><strong>When NOT to use lambda:</strong> If the logic requires statements (if/elif/else chains, loops, try/except, variable assignments), you cannot use lambda — use <code>def</code>. If the function is used in multiple places, define it once with <code>def</code> to avoid repetition. If the lambda expression is too long to read comfortably on one line, use <code>def</code>. As a rule of thumb: if you need more than a single expression or the expression is longer than ~80 characters, write a regular function.</p>
<p><strong>Lambda vs def comparison:</strong> Both create function objects that can be called the same way. <code>def</code> functions have a name (helpful in tracebacks), support docstrings, annotations, and multiple statements. Lambdas are limited to a single expression and have no name or docstring — if they raise an error, the traceback shows <code><lambda></code> which is less helpful for debugging. Performance-wise, they are identical — choice is purely about readability and capability.</p>
<p><strong>Common mistakes:</strong> Trying to use statements inside a lambda — <code>lambda x: return x + 1</code> is a <code>SyntaxError</code>. Using a lambda when <code>functools.partial</code> or a regular function would be clearer. Assigning a lambda to a variable (<code>add = lambda x, y: x + y</code>) is poor style — if you're going to name it, use <code>def</code> instead. That's what <code>def</code> is for.</p>
<p><strong>Best practices:</strong> Use lambdas only for simple, single-use operations. Prefer list comprehensions over <code>map()</code> with lambdas for readability. Use <code>key=</code> arguments in <code>sorted()</code>, <code>max()</code>, <code>min()</code> — these are the most common and idiomatic use cases. If the lambda body is complex, refactor it into a named function with a descriptive name.</p>
<p><strong>Real-world use case:</strong> Sorting a list of product objects by price descending: <code>products.sort(key=lambda p: p["price"], reverse=True)</code>. Finding the employee with the highest salary: <code>best = max(employees, key=lambda e: e.salary)</code>. Grouping data with <code>itertools.groupby</code>: <code>for city, group in groupby(people, key=lambda p: p["city"]):</code>.</p>
<div class="tip"><strong>Try it:</strong> Use <code>max()</code> with a lambda to find the longest word in a list: <code>words = ["cat", "elephant", "dog"]; print(max(words, key=lambda w: len(w)))</code>. Then use <code>sorted()</code> with a lambda that sorts by the last character of each word. Finally, compare the readability of a lambda vs a <code>def</code> for a multi-step key function.</div>
`
},
{
title: "Working with JSON", level: "intermediate", mins: 8,
code: `import json
person = {
"name": "Alice",
"age": 30,
"skills": ["Python", "Data Analysis"]
}
json_str = json.dumps(person, indent=2)
print(json_str)
parsed = json.loads(json_str)
print("Name:", parsed["name"])`,
content: `
<p>JSON (JavaScript Object Notation) is the universal data interchange format for web APIs, configuration files, and data storage. Python's built-in <code>json</code> module makes reading, writing, and transforming JSON effortless. Understanding JSON is essential for almost any modern Python application that communicates over the internet.</p>
<p><strong>Core functions — strings vs files:</strong></p>
<ul>
<li><code>json.dumps()</code> — converts a Python object to a JSON <strong>string</strong>. Use <code>indent</code> for pretty-printing: <code>json.dumps(data, indent=2, sort_keys=True)</code>. Control encoding with <code>ensure_ascii=False</code> to preserve non-ASCII characters like emojis. The <code>default</code> parameter specifies a function for objects that aren't natively serializable (like <code>datetime</code> or <code>Decimal</code>).</li>
<li><code>json.loads()</code> — parses a JSON <strong>string</strong> back into a Python object. Returns a dict for JSON objects, list for JSON arrays, etc.</li>
<li><code>json.dump(obj, file)</code> — writes directly to a file object. No <code>s</code> suffix: <code>with open("data.json", "w") as f: json.dump(data, f, indent=2)</code>.</li>
<li><code>json.load(file)</code> — reads directly from a file object: <code>with open("data.json") as f: data = json.load(f)</code>.</li>
</ul>
<p><strong>JSON to Python type mapping:</strong></p>
<ul>
<li>JSON object <code>{}</code> → Python <code>dict</code></li>
<li>JSON array <code>[]</code> → Python <code>list</code></li>
<li>JSON string → Python <code>str</code></li>
<li>JSON number → Python <code>int</code> or <code>float</code></li>
<li>JSON boolean <code>true/false</code> → Python <code>True/False</code> (note capitalization)</li>
<li>JSON null → Python <code>None</code></li>
</ul>
<p><strong>Handling nested JSON:</strong> Real-world JSON often has multiple levels of nesting. Access nested data by chaining keys and indices: <code>data["users"][0]["address"]["city"]</code>. For safety, use <code>.get()</code> at each level: <code>data.get("users", [{}])[0].get("address", {}).get("city")</code>. For extremely deep nesting, consider using <code>jsonpath-ng</code> library or flatten the structure with recursive helper functions.</p>
<p><strong>Error handling with JSON:</strong> Always wrap JSON parsing in try/except because the input might be malformed: <code>try: data = json.loads(raw_text); except json.JSONDecodeError as e: print(f"Invalid JSON: {e}")</code>. <code>json.JSONDecodeError</code> provides <code>.msg</code>, <code>.doc</code>, <code>.pos</code>, <code>.lineno</code>, and <code>.colno</code> for detailed error reporting. Also handle <code>TypeError</code> when serializing objects that aren't JSON-serializable (like datetime objects — use the <code>default</code> parameter with a custom converter).</p>
<p><strong>Common mistakes:</strong> Forgetting that JSON uses <code>true</code>/<code>false</code>/<code>null</code> (lowercase) while Python uses <code>True</code>/<code>False</code>/<code>None</code> — the <code>json</code> module handles this conversion automatically. Trying to serialize non-serializable types (datetimes, Decimals, custom objects) — provide a <code>default</code> converter. Using single quotes in JSON strings — JSON requires double quotes. Trailing commas in JSON objects or arrays — JSON does not allow them.</p>
<p><strong>Best practices:</strong> Always specify <code>indent=2</code> for human-readable output. Use <code>ensure_ascii=False</code> to preserve Unicode characters. Validate JSON before processing by catching <code>JSONDecodeError</code>. For large JSON files, consider streaming parsers like <code>ijson</code>. Use <code>sort_keys=True</code> for consistent, diff-friendly output in version-controlled config files.</p>
<p><strong>Real-world use case:</strong> Fetching data from a public API: <code>import urllib.request; response = urllib.request.urlopen("https://api.github.com/users/python"); data = json.loads(response.read()); print(data["login"], data["public_repos"])</code>. Or storing application configuration: read a <code>config.json</code> with <code>json.load()</code> and access settings like database credentials or feature flags.</p>
<div class="tip"><strong>Try it:</strong> Add <code>ensure_ascii=False</code> to the <code>dumps</code> call and include a Unicode string like "café". Then try serializing a nested structure and use <code>.get()</code> to safely access a deeply nested key. Finally, wrap the <code>loads</code> call in try/except and pass intentionally invalid JSON to see the error message.</div>
`
},
{
title: "Map & Filter", level: "intermediate", mins: 7,
code: `nums = [1, 2, 3, 4, 5, 6]
squares = list(map(lambda x: x**2, nums))
print("Squares:", squares)
evens = list(filter(lambda x: x % 2 == 0, nums))
print("Evens:", evens)
# Same with list comprehensions
print("Squares LC:", [x**2 for x in nums])
print("Evens LC:", [x for x in nums if x % 2 == 0])`,
content: `
<p><code>map()</code> and <code>filter()</code> are built-in functions from Python's <strong>functional programming</strong> toolkit. <code>map(function, iterable)</code> applies the given function to every item and returns a lazy iterator of results. <code>filter(function, iterable)</code> keeps only items for which the function returns <code>True</code>. Both return <strong>lazy iterators</strong> — they process items on demand rather than creating entire result lists in memory. Wrap them with <code>list()</code> to materialize results: <code>list(map(str.upper, names))</code>.</p>
<p><strong>List comprehensions vs map/filter:</strong> In modern Python, list comprehensions are generally preferred because they are more readable and Pythonic:</p>
<p><code>list(map(lambda x: x*2, nums))</code> vs <code>[x*2 for x in nums]</code></p>
<p><code>list(filter(lambda x: x > 0, nums))</code> vs <code>[x for x in nums if x > 0]</code></p>
<p>Comprehensions win on readability because the intent (<em>transform each item</em> or <em>select items by condition</em>) is immediately visible. However, map/filter can be more memory-efficient when combined with other lazy operations, and they shine when you already have a named function (avoiding lambda): <code>list(map(str.strip, lines))</code> vs <code>[s.strip() for s in lines]</code>. When using an existing built-in or imported function, <code>map</code> can be cleaner.</p>
<p><strong>Generator expressions vs map/filter:</strong> Generator expressions <code>(x*2 for x in nums)</code> are the lazy equivalent of list comprehensions and compete directly with map/filter. Generator expressions are more readable than map/filter with lambdas and can express both mapping and filtering simultaneously: <code>(x*2 for x in nums if x > 0)</code>. The equivalent with map and filter requires nesting: <code>map(lambda x: x*2, filter(lambda x: x > 0, nums))</code>. Generator expressions win here for readability. Use map/filter over generator expressions when you already have a named function to apply.</p>
<p><strong>Combining map and filter:</strong> You can chain them to perform both operations. First filter, then map: <code>result = list(map(lambda x: x**2, filter(lambda x: x % 2 == 0, nums)))</code>. This reads "filter even numbers, then square them." The operations are applied lazily — each item passes through filter, and if accepted, through map. For readability, consider breaking this into multiple lines or using a list comprehension with a condition instead.</p>
<p><strong>functools.reduce:</strong> For more advanced functional operations, <code>functools.reduce()</code> repeatedly applies a function to accumulate a single result: <code>from functools import reduce; total = reduce(lambda a, b: a + b, nums)</code> sums all numbers (same as <code>sum(nums)</code>). Reduce is powerful for operations like computing factorials, finding products, or building dictionaries from lists. However, Python has specialized functions for common reduce operations: <code>sum()</code>, <code>any()</code>, <code>all()</code>, <code>max()</code>, <code>min()</code>. Only use reduce when no dedicated function exists.</p>
<p><strong>When to use each:</strong> Use list comprehensions for simple transformations and filters (90% of cases). Use map with existing named functions (no lambda) for clean functional-style code. Use filter when you have a predicate function that already exists. Use generator expressions when dealing with very large datasets to save memory. Use reduce only for operations that genuinely accumulate a single result and have no built-in alternative. Avoid using map/filter with lambdas when a comprehension reads better — which is most of the time.</p>
<p><strong>Common mistakes:</strong> Forgetting to wrap map/filter with <code>list()</code> to get a list — they return iterators, not lists. Using map with a lambda that has side effects (like <code>print</code>) — a for loop is clearer. Nesting map and filter too deeply — two nested calls are the maximum before readability suffers badly. Using reduce for simple operations that have built-in functions.</p>
<p><strong>Real-world use case:</strong> Processing log file lines: <code>cleaned = list(map(str.strip, raw_lines)); errors = list(filter(lambda l: "[ERROR]" in l, cleaned))</code>. Or numeric processing: calculating total sales with tax from a list of items: <code>prices_with_tax = list(map(lambda p: p * 1.08, filter(lambda p: p > 0, raw_prices)))</code>.</p>
<div class="tip"><strong>Try it:</strong> Chain map and filter to transform a list of numbers: first filter to keep only odds, then map to cube them. Then rewrite the same operation as a list comprehension and compare readability. Finally, use <code>functools.reduce</code> to find the maximum value in a list without using <code>max()</code>.</div>
`
},
{
title: "Classes & OOP", level: "advanced", mins: 12,
code: `class Dog:
def __init__(self, name):
self.name = name
def bark(self):
return f"{self.name} says woof!"
my_dog = Dog("Rex")
print(my_dog.bark())`,
content: `
<p><strong>Object-Oriented Programming (OOP)</strong> organizes code into <strong>classes</strong> (blueprints) and <strong>objects</strong> (instances). Instead of writing functions that operate on separate data structures, you bundle data and behavior together. A <code>Dog</code> class defines what all dogs have in common; <code>my_dog = Dog("Rex")</code> creates a specific dog object. Python supports full OOP with a clean, intuitive syntax.</p>
<p><strong>The __init__ method and self:</strong> The <code>__init__</code> constructor runs automatically when you create an object. The <code>self</code> parameter refers to the current instance and is used to access attributes and methods. It is automatic — Python passes it for you when calling methods: <code>my_dog.bark()</code> becomes <code>Dog.bark(my_dog)</code> internally.</p>
<p><strong>Inheritance and super():</strong> Inheritance lets you create specialized classes from general ones. A subclass inherits all methods and attributes from its parent class and can override or extend them:</p>
<p><code>class Animal:<br> def __init__(self, name):<br> self.name = name<br> def speak(self):<br> raise NotImplementedError<br><br>class Dog(Animal):<br> def speak(self):<br> return f"{self.name} says Woof!"</code></p>
<p>Use <code>super()</code> to call the parent class's methods: <code>class Cat(Animal):<br> def __init__(self, name, toy):<br> super().__init__(name) # Call parent constructor<br> self.toy = toy</code>. This avoids duplicating parent initialization code and is especially important in multiple inheritance scenarios to ensure MRO (Method Resolution Order) is handled correctly.</p>
<p><strong>@classmethod vs @staticmethod:</strong> Both are decorators for methods that don't operate on instances, but they differ:</p>
<ul>
<li><strong>@classmethod</strong> receives the class (<code>cls</code>) as the first argument. It can access and modify class-level attributes and is used for factory methods: <code>@classmethod def from_birth_year(cls, name, year): return cls(name, datetime.now().year - year)</code>.</li>
<li><strong>@staticmethod</strong> receives neither <code>self</code> nor <code>cls</code> — it's just a regular function placed inside a class for logical grouping. It cannot modify class or instance state: <code>@staticmethod def is_adult(age): return age >= 18</code>.</li>
</ul>
<p><strong>The @property decorator:</strong> Allows you to define methods that can be accessed like attributes, with optional computed values, validation, and controlled access:</p>
<p><code>class Circle:<br> def __init__(self, radius):<br> self._radius = radius<br> @property<br> def area(self):<br> return 3.14 * self._radius ** 2<br> @property<br> def radius(self):<br> return self._radius<br> @radius.setter<br> def radius(self, value):<br> if value < 0:<br> raise ValueError("Radius cannot be negative")<br> self._radius = value</code></p>
<p>Usage: <code>c = Circle(5); print(c.area); c.radius = 10; print(c.area)</code>. The <code>area</code> is computed on demand, and <code>radius</code> has validation — all accessed like simple attributes.</p>
<p><strong>Dunder methods (special methods):</strong> Double-underscore methods let your objects interoperate with Python's built-in operations. Key ones include: <code>__str__</code> (called by <code>print()</code>), <code>__repr__</code> (developer-friendly representation), <code>__len__</code> (called by <code>len()</code>), <code>__eq__</code> (<code>==</code>), <code>__lt__</code> (<code><</code>), <code>__getitem__</code> (<code>obj[key]</code>), <code>__add__</code> (<code>+</code>), <code>__bool__</code> (truthiness). Implementing these makes your classes feel like built-in types.</p>
<p><strong>Encapsulation and name mangling:</strong> Python uses conventions rather than strict access control. A single underscore prefix (<code>_hidden</code>) means "internal use" (convention, not enforced). Double underscore prefix (<code>__private</code>) triggers name mangling to <code>_ClassName__private</code>, making accidental access harder — useful for avoiding name conflicts in inheritance hierarchies.</p>
<p><strong>Common mistakes:</strong> Forgetting <code>self</code> as the first parameter of instance methods — causes <code>TypeError</code>. Accessing <code>__init__</code> directly instead of letting Python call it automatically. Using <code>@staticmethod</code> when <code>@classmethod</code> is needed (or vice versa). Not calling <code>super().__init__()</code> in subclasses, leaving parent attributes uninitialized. Using bare <code>except:</code> inside class methods — catches system-exit signals too.</p>
<p><strong>Best practices:</strong> Use properties instead of getter/setter methods — they're more Pythonic. Favor composition over inheritance ("has-a" is often better than "is-a"). Keep classes focused on a single responsibility. Document public methods with docstrings. Use <code>__repr__</code> to provide useful debugging information. Use <code>__slots__</code> to save memory when creating many instances of a class.</p>
<p><strong>Real-world use case:</strong> Modeling a banking system: <code>Account</code> base class with <code>checking_account</code> and <code>SavingsAccount</code> subclasses. The base class handles common logic (balance, owner, account number), while subclasses implement specific rules (withdrawal fees, interest rates). <code>@property</code> provides computed balance, <code>@classmethod</code> creates accounts from CSV data, and dunder methods enable sorting by balance or comparing accounts.</p>
<div class="tip"><strong>Try it:</strong> Add a <code>__str__</code> method to the Dog class that returns a friendly description. Then create a subclass <code>Puppy(Dog)</code> with a modified <code>bark()</code> that includes a cute suffix. Add a <code>@property</code> that returns the dog's age in human years. Finally, try <code>super()</code> to extend the parent's <code>__init__</code>.</div>
`
},
{
title: "Modules & Imports", level: "advanced", mins: 8,
code: `import math
from random import randint
print(f"Pi: {math.pi}")
print(f"Random 1-10: {randint(1, 10)}")`,
content: `
<p>Python's standard library is vast — hundreds of modules covering mathematics, networking, file I/O, data processing, web development, and more. The <strong>import</strong> statement is how you access this power and organize your own code into reusable units. Understanding import styles and module structure is essential for writing maintainable Python projects at any scale.</p>
<p><strong>Import styles and when to use each:</strong></p>