Repository navigation
Expand file tree
/
Copy pathHCO-PythonTutor.py
More file actions
2260 lines (1966 loc) Β· 79.4 KB
/
Copy pathHCO-PythonTutor.py
File metadata and controls
2260 lines (1966 loc) Β· 79.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
import ast
import getpass
import json
import os
import subprocess
import sys
import time
from datetime import date, timedelta
from pathlib import Path
import requests
# ============================================================
# HCO PYTHONTUTOR
# Interactive Python Learning Companion for Termux & Linux
# Code by Azhar (A-Z-H-A-R) β’ HCO Team
# ============================================================
API_URL = "https://openrouter.ai/api/v1/chat/completions"
MODEL = "openrouter/free"
YOUTUBE_URL = "https://youtube.com/@hackers_colony_tech"
RESET = "\033[0m"
BOLD = "\033[1m"
RED = "\033[1;31m"
GREEN = "\033[1;32m"
YELLOW = "\033[1;33m"
BLUE = "\033[1;34m"
MAGENTA = "\033[1;35m"
CYAN = "\033[1;36m"
WHITE = "\033[1;37m"
DATA_DIR = Path.home() / ".hco_pythontutor"
PROGRESS_FILE = DATA_DIR / "progress.json"
# ============================================================
# CURRICULUM
# Each lesson has explanation, examples, 10 exercises and
# a challenge. Exercises are checked by running the student's
# code plus lightweight task-specific checks where possible.
# ============================================================
LESSONS = [
{
"title": "Python & print()",
"level": "Beginner",
"goal": "Learn what Python is and write your first programs.",
"concepts": [
("Python", "Python is a programming language. You write instructions and the Python interpreter executes them."),
("print()", "print() displays information on the screen."),
("Parentheses", "The parentheses pass information into a function."),
("Strings", 'Text is a string. Strings are commonly written inside quotes such as "Hello".'),
("Numbers", "Numbers such as 10 can be written without quotes."),
("Quotes", 'print("Azhar") prints text. print(Azhar) tries to use Azhar as a variable.'),
("Interactive prompts", "The >>> and ... prompts are displayed by the tutor. You do not type them."),
("END", "HCO PythonTutor uses END alone on a new line to finish a multi-line code submission."),
],
"example": 'print("Hello, Hackers Colony!")',
"exercises": [
'Print "Hello".',
'Print your name.',
'Print "I am learning Python."',
'Print two different messages on two lines.',
'Print the number 100.',
'Print your name and your favorite technology.',
'Print "Python" three times using three print() statements.',
'Print a sentence containing spaces.',
'Print both text and a number using separate print() statements.',
'Create a tiny program that prints your name, city, and "I am learning Python."',
],
"challenge": 'Build a 3-line introduction program that prints your name, your city, and why you are learning Python.',
"hints": [
'Use print("Hello").',
'Put text inside quotes.',
'Use one print() statement for each line.',
],
},
{
"title": "Variables",
"level": "Beginner",
"goal": "Store values in variables and use them later.",
"concepts": [
("Variable", "A variable is a name that refers to a value."),
("Assignment", "The = operator assigns a value to a variable."),
("Variable names", "Use clear names such as name, age, city, or score."),
("Reusing values", "After assignment, use the variable name to access its value."),
("Updating values", "A variable can be assigned a new value later."),
("Naming rules", "Names cannot contain spaces and cannot start with a number."),
],
"example": 'name = "Azhar"\ncity = "Kolkata"\nprint(name)\nprint(city)',
"exercises": [
'Create a variable called name and print it.',
'Create a variable called city and print it.',
'Create an age variable and print it.',
'Create a score variable with 100 and print it.',
'Create two variables and print both.',
'Change the value of a variable and print the new value.',
'Create name and city variables and print a sentence using them.',
'Create length and width variables and print their product.',
'Create a counter variable and increase it by 1.',
'Create a profile using at least four variables and print them.',
],
"challenge": "Build a small profile program using variables for name, age, city, and skill.",
"hints": [
'Assignment looks like: name = "Azhar".',
'Use print(variable) to display a stored value.',
'Remember that = assigns a value; == compares values.',
],
},
{
"title": "Data Types",
"level": "Beginner",
"goal": "Understand strings, integers, floats, booleans and type().",
"concepts": [
("String", 'Text such as "Python" is a string.'),
("Integer", "A whole number such as 20 is an integer."),
("Float", "A decimal number such as 3.14 is a float."),
("Boolean", "True and False are boolean values."),
("type()", "type(value) tells you the data type of a value."),
("Type conversion", "int(), float(), and str() convert compatible values."),
],
"example": 'name = "Azhar"\nage = 20\nheight = 5.9\nactive = True\nprint(type(name))\nprint(type(age))\nprint(type(height))\nprint(type(active))',
"exercises": [
'Create a string and print its type.',
'Create an integer and print its type.',
'Create a float and print its type.',
'Create a boolean and print its type.',
'Print the types of four different values.',
'Convert "25" into an integer and print it.',
'Convert 10 into a float and print it.',
'Convert 123 into a string and print it.',
'Create a small data record using different types.',
'Print a value and its type together using separate print() calls.',
],
"challenge": "Create a student profile using at least one string, integer, float, and boolean.",
"hints": [
"Use type(value).",
'Remember: "25" is text, while 25 is an integer.',
"Use int(), float(), or str() when conversion is needed.",
],
},
{
"title": "Input",
"level": "Beginner",
"goal": "Receive information from the user and convert input when needed.",
"concepts": [
("input()", "input() waits for the user to type a response."),
("Return value", "input() returns the entered value as a string."),
("Prompt text", 'input("Your name: ") displays a prompt.'),
("Storing input", "Assign input() to a variable."),
("Integer input", "Use int(input(...)) when a whole number is required."),
("Float input", "Use float(input(...)) when a decimal number is required."),
],
"example": 'name = input("Your name: ")\nprint("Hello", name)',
"exercises": [
"Ask the user for their name and print it.",
"Ask for a city and print it.",
"Ask for a favorite programming language and print it.",
"Ask for age and convert it to an integer.",
"Ask for two numbers and print their sum.",
"Ask for name and city and print both.",
"Ask for a number and print its square.",
"Ask for a year and calculate the next year.",
"Ask for a price and quantity and calculate the total.",
"Build an interactive introduction program using three inputs.",
],
"challenge": "Build a simple interactive profile program that asks for name, city, age, and favorite skill.",
"hints": [
'Start with: name = input("Your name: ")',
"Remember that input() returns text.",
"Use int() for whole-number calculations.",
],
},
{
"title": "Operators",
"level": "Beginner",
"goal": "Use arithmetic, comparison and logical operators.",
"concepts": [
("Arithmetic", "Use +, -, *, /, //, %, and ** for calculations."),
("Comparison", "Use ==, !=, >, <, >=, and <= to compare values."),
("Logical", "Use and, or, and not to combine conditions."),
("Assignment", "Use = to assign a value."),
("Equality", "Use == to compare two values."),
("Modulo", "% gives the remainder of a division."),
],
"example": 'a = 10\nb = 3\nprint(a + b)\nprint(a * b)\nprint(a > b)\nprint(a == b)\nprint(a % b)',
"exercises": [
"Add two numbers.",
"Subtract two numbers.",
"Multiply two numbers.",
"Divide two numbers.",
"Find the remainder of two numbers.",
"Calculate a number raised to a power.",
"Compare two numbers using >.",
"Compare two values using ==.",
"Use and with two boolean conditions.",
"Build a mini calculator for two numbers.",
],
"challenge": "Build a two-number calculator supporting +, -, *, and /.",
"hints": [
"Use + for addition.",
"Use == for comparison.",
"Use % when you need a remainder.",
],
},
{
"title": "Conditions",
"level": "Beginner",
"goal": "Make decisions with if, elif, else and indentation.",
"concepts": [
("if", "if runs a block when its condition is True."),
("else", "else runs when the previous condition is False."),
("elif", "elif checks another condition."),
("Colon", "A colon starts the indented block after if, elif, or else."),
("Indentation", "Indented lines belong to the current block."),
("Comparison", "Conditions commonly use comparison operators."),
],
"example": 'age = 18\nif age >= 18:\n print("Adult")\nelse:\n print("Minor")',
"exercises": [
"Print Adult when age is 18 or above.",
"Check whether a number is positive.",
"Check whether a number is negative or zero.",
"Check whether two numbers are equal.",
"Print Pass when score is 40 or above.",
"Create an if/else login message using a stored username.",
"Use elif for three score ranges.",
"Check whether a number is even or odd.",
"Use two conditions with and.",
"Build a simple age-category program.",
],
"challenge": "Build a grade checker that prints a different message for several score ranges.",
"hints": [
"Start a condition with if.",
"Remember the colon after the condition.",
"The code inside the block must be indented.",
],
},
{
"title": "for Loops",
"level": "Beginner",
"goal": "Repeat code using for and range().",
"concepts": [
("Loop", "A loop repeats code."),
("for", "A for loop iterates over values."),
("range()", "range() produces a sequence of integers."),
("Loop variable", "The variable after for receives each value."),
("Indentation", "The indented block is repeated."),
],
"example": 'for i in range(1, 6):\n print(i)',
"exercises": [
"Print numbers 1 through 5.",
"Print numbers 0 through 4.",
"Print the word Python five times.",
"Print even numbers from 2 to 10.",
"Print odd numbers from 1 to 9.",
"Calculate the sum of numbers 1 through 10.",
"Loop through a list of three names.",
"Print a multiplication table.",
"Count down from 10 to 1.",
"Build a small number-report program using a loop.",
],
"challenge": "Build a multiplication table generator for a number chosen by the user.",
"hints": [
"Use range().",
"Put repeated code inside the indented loop body.",
"Use a loop variable such as i.",
],
},
{
"title": "while Loops",
"level": "Beginner",
"goal": "Repeat code while a condition remains true.",
"concepts": [
("while", "while repeats a block while its condition is True."),
("Counter", "A counter can control how many times a loop runs."),
("Update", "Change the loop variable so the loop can eventually stop."),
("Infinite loop", "A condition that never becomes false can create an infinite loop."),
],
"example": 'count = 0\nwhile count < 3:\n print(count)\n count += 1',
"exercises": [
"Print 0, 1, and 2 with while.",
"Count from 1 to 5.",
"Count down from 5 to 1.",
"Print a word three times.",
"Calculate a running total.",
"Ask for a password until the correct value is entered.",
"Stop when the user enters quit.",
"Create a simple menu loop.",
"Use a counter to limit attempts.",
"Build a number guessing loop.",
],
"challenge": "Build a small menu that keeps running until the user chooses Exit.",
"hints": [
"Start with a variable before the loop.",
"Update that variable inside the loop.",
"Make sure there is a clear exit condition.",
],
},
{
"title": "Lists",
"level": "Beginner",
"goal": "Store and manipulate ordered collections.",
"concepts": [
("List", "A list stores multiple ordered values."),
("Square brackets", "Lists are written with square brackets."),
("Index", "Python list indexes start at 0."),
("append()", "append() adds an item to the end."),
("remove()", "remove() removes a matching value."),
("len()", "len() returns the number of items."),
],
"example": 'skills = ["Python", "Linux", "AI"]\nprint(skills[0])\nskills.append("Git")\nprint(skills)',
"exercises": [
"Create a list of three names.",
"Print the first item.",
"Print the second item.",
"Append a new item.",
"Remove an item.",
"Print the length of a list.",
"Loop through a list.",
"Create a list of numbers and calculate a sum.",
"Sort a list of numbers.",
"Build a simple shopping-list program.",
],
"challenge": "Build a command-line shopping list with add, view, and remove operations.",
"hints": [
"The first item has index 0.",
"Use append() to add an item.",
"Use len() to count items.",
],
},
{
"title": "Tuples & Sets",
"level": "Beginner",
"goal": "Understand immutable sequences and unique collections.",
"concepts": [
("Tuple", "A tuple is an ordered collection that is normally immutable."),
("Tuple syntax", "Tuples are commonly written with parentheses."),
("Set", "A set stores unique values."),
("Duplicate removal", "Sets automatically remove duplicate values."),
("Membership", "Use in to test whether a value exists in a collection."),
],
"example": 'items = {1, 2, 2, 3}\nprint(items)\ncolors = ("red", "green", "blue")\nprint(colors[0])',
"exercises": [
"Create a tuple of three colors.",
"Print the first tuple item.",
"Create a set with duplicate numbers.",
"Print the set.",
"Add an item to a set.",
"Remove an item from a set.",
"Check membership with in.",
"Find the length of a set.",
"Convert a list into a set.",
"Build a unique-skills collector.",
],
"challenge": "Build a small program that accepts several skills and displays only unique skills.",
"hints": [
"Sets use curly braces or set().",
"Tuples are commonly written with parentheses.",
"Use in for membership checks.",
],
},
{
"title": "Dictionaries",
"level": "Beginner",
"goal": "Store information using key-value pairs.",
"concepts": [
("Dictionary", "A dictionary stores key-value pairs."),
("Key", "A key identifies a value."),
("Value", "A value is the data stored under a key."),
("Access", "Use dictionary[key] to access a value."),
("Update", "Assign to an existing key to update its value."),
("get()", "get() can safely retrieve a value when a key may be missing."),
],
"example": 'user = {"name": "Azhar", "level": "beginner"}\nprint(user["name"])\nuser["level"] = "intermediate"\nprint(user)',
"exercises": [
"Create a dictionary with name and age.",
"Print the name.",
"Add a city key.",
"Update the age.",
"Use get() to read a key.",
"Loop through dictionary keys.",
"Loop through key-value pairs.",
"Create a dictionary of three scores.",
"Calculate a total from dictionary values.",
"Build a small contact record.",
],
"challenge": "Build a simple contact-book program using a dictionary.",
"hints": [
'Use syntax like {"name": "Azhar"}.',
"Access values with dictionary[key].",
"Use items() when looping over key-value pairs.",
],
},
{
"title": "Functions",
"level": "Beginner",
"goal": "Create reusable blocks of code.",
"concepts": [
("def", "def starts a function definition."),
("Function name", "Choose a clear name describing the function's job."),
("Parameter", "A parameter is a named input to a function."),
("Call", "Use function_name() to call a function."),
("return", "return sends a value back to the caller."),
],
"example": 'def greet(name):\n return "Hello " + name\n\nprint(greet("Azhar"))',
"exercises": [
"Create a function that prints Hello.",
"Create greet(name).",
"Create add(a, b).",
"Create a function that squares a number.",
"Create a function that checks even/odd.",
"Create a function with a default parameter.",
"Return a string from a function.",
"Call the same function three times.",
"Create two helper functions.",
"Build a mini calculator using functions.",
],
"challenge": "Build a calculator where each operation is implemented as a separate function.",
"hints": [
"Start with def function_name(...):",
"Indent the function body.",
"Use return when the caller needs a result.",
],
},
{
"title": "Function Arguments & Scope",
"level": "Intermediate",
"goal": "Understand arguments, defaults, *args, **kwargs and scope.",
"concepts": [
("Positional arguments", "Arguments can be passed by position."),
("Keyword arguments", "Arguments can be passed by parameter name."),
("Defaults", "Parameters can have default values."),
("*args", "*args collects extra positional arguments."),
("**kwargs", "**kwargs collects extra keyword arguments."),
("Scope", "Scope determines where a variable can be accessed."),
],
"example": 'def add(a, b=0):\n return a + b\n\nprint(add(5, 7))\nprint(add(5))',
"exercises": [
"Create a function with two positional arguments.",
"Call a function using keyword arguments.",
"Create a function with a default value.",
"Create a function using *args.",
"Create a function using **kwargs.",
"Write a function that returns the largest argument.",
"Demonstrate a local variable.",
"Write a function that calls another function.",
"Create a configurable greeting function.",
"Build a reusable utility module in one file.",
],
"challenge": "Build a flexible report function that accepts a title, multiple values, and optional settings.",
"hints": [
"Default parameters look like name=value.",
"*args is a tuple inside the function.",
"**kwargs is a dictionary inside the function.",
],
},
{
"title": "Modules",
"level": "Intermediate",
"goal": "Organize code and use Python modules.",
"concepts": [
("Module", "A module is a Python file containing reusable code."),
("import", "import loads a module."),
("from", "from can import selected names."),
("Standard library", "Python includes many useful modules."),
("Your modules", "You can create your own .py files and import them."),
],
"example": 'import math\nprint(math.sqrt(25))',
"exercises": [
"Import math.",
"Use math.sqrt().",
"Import random.",
"Generate a random integer.",
"Import pathlib.",
"List files with pathlib.",
"Import a specific function from a module.",
"Create a helper module.",
"Import your helper module.",
"Build a two-file mini project.",
],
"challenge": "Create a two-file Python project with a main program and a reusable utility module.",
"hints": [
"Use import module_name.",
"Your custom module can be another .py file in the same directory.",
"Keep reusable functions in the helper module.",
],
},
{
"title": "File Handling",
"level": "Intermediate",
"goal": "Read, write and safely manage files.",
"concepts": [
("open()", "open() creates a file object."),
("Modes", "Common modes include r for read, w for write, and a for append."),
("with", "with manages the file resource and closes it automatically."),
("read()", "read() returns file contents."),
("write()", "write() writes text to a file."),
("Path", "pathlib.Path provides a convenient modern path API."),
],
"example": 'with open("demo.txt", "w") as f:\n f.write("Hello Python")\n\nwith open("demo.txt", "r") as f:\n print(f.read())',
"exercises": [
"Write text to a file.",
"Read the file.",
"Append another line.",
"Count lines in a file.",
"Count words in a file.",
"Check whether a file exists.",
"List files in the current directory.",
"Read a file line by line.",
"Copy text from one file to another.",
"Build a simple notes file program.",
],
"challenge": "Build a local notes manager that can add and view notes in a text file.",
"hints": [
'Use with open("file.txt", "w") as f:',
"Use append mode a when you want to add data.",
"pathlib.Path can check whether files exist.",
],
},
{
"title": "Exceptions",
"level": "Intermediate",
"goal": "Handle expected errors with try, except, else and finally.",
"concepts": [
("Exception", "An exception is an error raised while a program runs."),
("try", "Put code that may raise an expected exception inside try."),
("except", "Handle a specific exception in except."),
("else", "else runs when the try block succeeds."),
("finally", "finally runs whether an exception occurred or not."),
("raise", "raise lets your code deliberately signal an error."),
],
"example": 'try:\n number = int("hello")\nexcept ValueError:\n print("Please enter a number.")',
"exercises": [
"Catch ValueError from int().",
"Catch ZeroDivisionError.",
"Handle invalid user input.",
"Use else with try/except.",
"Use finally.",
"Raise ValueError for invalid data.",
"Create a safe integer input function.",
"Handle a missing file.",
"Handle multiple expected exceptions.",
"Build a robust calculator.",
],
"challenge": "Build an input validator that keeps asking until valid numeric input is received.",
"hints": [
"Catch the specific exception you expect.",
"Do not use bare except when a specific exception is appropriate.",
"Use a loop when the user should retry.",
],
},
{
"title": "Comprehensions",
"level": "Intermediate",
"goal": "Create collections concisely while keeping code readable.",
"concepts": [
("List comprehension", "Build a list from an iterable using a compact expression."),
("Condition", "A comprehension can include a filtering condition."),
("Set comprehension", "The same idea can create sets."),
("Dictionary comprehension", "Comprehensions can create dictionaries."),
("Readability", "Shorter code is not always clearer; prefer readable expressions."),
],
"example": 'squares = [x * x for x in range(6)]\nprint(squares)\nevens = [x for x in range(10) if x % 2 == 0]\nprint(evens)',
"exercises": [
"Create squares from 0 to 5.",
"Create even numbers from 0 to 10.",
"Convert words to uppercase.",
"Filter words longer than four characters.",
"Create a set of unique lengths.",
"Create a dictionary of numbers and squares.",
"Flatten a small nested list.",
"Strip whitespace from words.",
"Combine a filter and transformation.",
"Rewrite a simple loop as a comprehension.",
],
"challenge": "Build a data-cleaning script that filters and transforms a list of user-provided words.",
"hints": [
"Start with [expression for item in iterable].",
"Add if condition for filtering.",
"Keep complex logic in normal loops or helper functions.",
],
},
{
"title": "OOP Basics",
"level": "Intermediate",
"goal": "Understand classes, objects, attributes and methods.",
"concepts": [
("Class", "A class is a blueprint for creating objects."),
("Object", "An object is an instance of a class."),
("__init__", "__init__ commonly initializes object attributes."),
("self", "self refers to the current object instance."),
("Method", "A method is a function defined inside a class."),
("Attribute", "An attribute is data stored on an object."),
],
"example": 'class User:\n def __init__(self, name):\n self.name = name\n\n def greet(self):\n return "Hello " + self.name\n\nu = User("Azhar")\nprint(u.greet())',
"exercises": [
"Create a simple class.",
"Create an object from it.",
"Add an attribute.",
"Add a method.",
"Use __init__.",
"Create two objects with different data.",
"Create a counter class.",
"Create a simple BankAccount class.",
"Add validation to a method.",
"Build a small class-based program.",
],
"challenge": "Build a BankAccount class with deposit, withdraw, and balance behavior.",
"hints": [
"Start with class ClassName:.",
"Use self inside instance methods.",
"Initialize attributes inside __init__.",
],
},
{
"title": "Inheritance",
"level": "Intermediate",
"goal": "Reuse and extend behavior between classes.",
"concepts": [
("Inheritance", "A child class can inherit behavior from a parent class."),
("Parent", "The base class provides reusable behavior."),
("Child", "The derived class can add or override behavior."),
("super()", "super() can call behavior from the parent class."),
("Override", "A child method can replace a parent implementation."),
],
"example": 'class Animal:\n def speak(self):\n print("sound")\n\nclass Dog(Animal):\n def speak(self):\n print("woof")\n\nDog().speak()',
"exercises": [
"Create a parent class.",
"Create a child class.",
"Inherit a method.",
"Override a method.",
"Use super().",
"Add a child-specific attribute.",
"Create two child classes.",
"Use polymorphic method calls.",
"Build a simple vehicle hierarchy.",
"Refactor duplicated behavior with inheritance.",
],
"challenge": "Create a base Vehicle class and two specialized child classes with different behavior.",
"hints": [
"Use class Child(Parent):.",
"Call super() when parent initialization or behavior is needed.",
"Override only when the child really needs different behavior.",
],
},
{
"title": "Virtual Environments",
"level": "Intermediate",
"goal": "Isolate project dependencies.",
"concepts": [
("Why venv?", "Virtual environments keep project packages separate."),
("Create", "python3 -m venv .venv creates a virtual environment."),
("Activate", "Activation changes the shell environment to use the environment."),
("Packages", "Install project-specific packages inside the environment."),
("Requirements", "requirements.txt records dependencies for reproducible setup."),
],
"example": "python3 -m venv .venv",
"exercises": [
"Create a .venv environment.",
"Inspect the environment directory.",
"Activate a virtual environment on Linux/Termux.",
"Check the Python version.",
"Install a small package.",
"List installed packages.",
"Create a requirements.txt file.",
"Install from requirements.txt.",
"Deactivate the environment.",
"Explain why isolation is useful for a project.",
],
"challenge": "Create a clean Python project environment and document its setup commands.",
"hints": [
"Create with: python3 -m venv .venv",
"Activation commands depend on your shell.",
"requirements.txt can be installed with pip install -r requirements.txt.",
],
},
{
"title": "JSON & APIs",
"level": "Intermediate",
"goal": "Work with structured data and HTTP APIs.",
"concepts": [
("JSON", "JSON is a common text format for structured data."),
("json.dumps", "Converts a Python object to JSON text."),
("json.loads", "Converts JSON text to a Python object."),
("API", "An API is an interface for software-to-software communication."),
("HTTP", "HTTP is commonly used to send requests to web APIs."),
("Status codes", "HTTP status codes communicate request results."),
],
"example": 'import json\n\ndata = {"name": "Azhar", "active": True}\ntext = json.dumps(data)\nprint(text)\nprint(json.loads(text)["name"])',
"exercises": [
"Create a dictionary and convert it to JSON.",
"Convert JSON text back to Python.",
"Read a value from decoded JSON.",
"Create a JSON list.",
"Write JSON to a file.",
"Read JSON from a file.",
"Inspect an HTTP response status code.",
"Send a request to a public API you are authorized to use.",
"Handle API errors.",
"Build a small JSON-backed data tool.",
],
"challenge": "Build a small program that reads JSON data, validates it, and displays selected fields.",
"hints": [
"Use json.dumps() for Python β JSON text.",
"Use json.loads() for JSON text β Python.",
"Always handle network errors when making HTTP requests.",
],
},
{
"title": "Testing",
"level": "Intermediate",
"goal": "Verify program behavior with tests and assertions.",
"concepts": [
("Test", "A test checks whether software behaves as expected."),
("assert", "assert verifies that a condition is true."),
("Test cases", "Different inputs should cover normal and edge cases."),
("Regression", "Tests help detect when a change breaks existing behavior."),
("pytest", "pytest is a popular external Python testing framework."),
],
"example": 'def add(a, b):\n return a + b\n\nassert add(2, 3) == 5\nprint("Test passed")',
"exercises": [
"Test an addition function.",
"Test a subtraction function.",
"Test a string function.",
"Test an even/odd function.",
"Test an edge case.",
"Write multiple assertions.",
"Create a test function.",
"Test invalid input behavior.",
"Separate application code from tests.",
"Run a small test suite.",
],
"challenge": "Create a utility module and a test file containing at least five meaningful tests.",
"hints": [
"Use assert expected == actual.",
"Include normal and edge cases.",
"Keep tests focused on observable behavior.",
],
},
{
"title": "Debugging",
"level": "Intermediate",
"goal": "Develop a systematic process for finding and fixing bugs.",
"concepts": [
("Read traceback", "A traceback shows where an exception occurred."),
("Reproduce", "Reproduce the bug consistently before changing code."),
("Inspect", "Inspect variables and assumptions."),
("Small changes", "Change one thing at a time and retest."),
("Logging", "Logging can provide useful runtime information."),
],
"example": 'numbers = [1, 2, 3]\nprint(numbers[1])',
"exercises": [
"Fix a NameError.",
"Fix an IndexError.",
"Fix a TypeError.",
"Fix an indentation error.",
"Fix a wrong variable value.",
"Use print() to inspect state.",
"Read a traceback and identify its line.",
"Add logging to a small program.",
"Create and fix a bug intentionally.",
"Write a short debugging checklist.",
],
"challenge": "Debug a deliberately broken mini-program and explain each fix.",
"hints": [
"Start with the exception type.",
"Check the line named in the traceback.",
"Reproduce the smallest version of the problem.",
],
},
{
"title": "Automation",
"level": "Intermediate",
"goal": "Automate safe and useful local tasks.",
"concepts": [
("Automation", "Automation uses code to perform repetitive work."),
("Pathlib", "pathlib provides tools for filesystem paths."),
("Subprocess", "subprocess can run external programs; use it carefully."),
("Arguments", "Pass command arguments as a list rather than unsafe shell strings when possible."),
("Safety", "Test automation before allowing it to modify important files."),
],
"example": 'from pathlib import Path\n\nfor path in Path(".").iterdir():\n print(path.name)',
"exercises": [
"List files in the current directory.",
"Find files with a specific extension.",
"Count files in a directory.",
"Create a directory.",
"Create a text report.",
"Rename a test file safely.",
"Copy a file.",
"Use subprocess for a harmless local command.",
"Add a dry-run option.",
"Build a file-organizing utility for a test directory.",
],
"challenge": "Build a safe file organizer that operates only inside a chosen test directory.",
"hints": [
"Use pathlib.Path.",
"Test with dummy files first.",
"A dry-run mode can show what would happen without changing files.",
],
},
{
"title": "SQLite",
"level": "Advanced",
"goal": "Store structured data locally with SQLite.",
"concepts": [
("Database", "A database stores structured information."),
("Table", "A table contains rows and columns."),
("Connection", "sqlite3.connect() opens a database connection."),
("SQL", "SQL statements create and manipulate database data."),
("Parameterized queries", "Use placeholders instead of concatenating user input into SQL."),
("Commit", "Changes normally need to be committed when using a file-backed database."),
],
"example": 'import sqlite3\n\ncon = sqlite3.connect(":memory:")\ncon.execute("CREATE TABLE users(name TEXT)")\ncon.execute("INSERT INTO users(name) VALUES (?)", ("Azhar",))\nprint(con.execute("SELECT * FROM users").fetchall())\ncon.close()',
"exercises": [
"Create an in-memory SQLite database.",
"Create a table.",
"Insert a row.",
"Insert multiple rows.",
"Select rows.",
"Filter rows with WHERE.",
"Update a row.",
"Delete a row.",
"Use a parameterized query.",
"Build a small SQLite CRUD program.",
],
"challenge": "Build a contact manager backed by SQLite with create, read, update, and delete operations.",
"hints": [
"Use sqlite3.connect().",
"Use ? placeholders for values.",
"Keep SQL structure separate from user-provided values.",
],
},
{
"title": "Async Basics",
"level": "Advanced",
"goal": "Understand async, await and asynchronous tasks.",
"concepts": [
("async", "async def defines a coroutine function."),
("await", "await pauses a coroutine until an awaitable operation completes."),
("asyncio", "asyncio provides Python's standard asynchronous framework."),
("Task", "asyncio.create_task() schedules a coroutine."),
("Concurrency", "Async code can efficiently manage many waiting operations."),
],
"example": 'import asyncio\n\nasync def main():\n print("Hello async")\n\nasyncio.run(main())',
"exercises": [
"Create an async function.",
"Run it with asyncio.run().",
"Use asyncio.sleep().",
"Create two async functions.",
"Run tasks concurrently.",
"Measure a simple async operation.",
"Use create_task().",
"Handle an async exception.",
"Build an async worker example.",
"Build a small async task runner.",
],
"challenge": "Build an async task runner that schedules several simulated waiting tasks concurrently.",
"hints": [
"Import asyncio.",
"Use async def for coroutines.",
"Use await asyncio.sleep(...) for a safe demonstration.",
],
},
{
"title": "Advanced Python",
"level": "Advanced",
"goal": "Explore decorators, generators, context managers and advanced syntax.",
"concepts": [
("Decorator", "A decorator wraps or modifies function behavior."),
("Generator", "A generator yields values lazily."),
("yield", "yield produces a value and pauses a generator."),
("Context manager", "A context manager handles setup and cleanup around a block."),
("Type hints", "Type hints document expected types and improve tooling."),
],
"example": 'def log_call(fn):\n def wrapper(*args, **kwargs):\n print("Calling function")\n return fn(*args, **kwargs)\n return wrapper\n\n@log_call\ndef hello(name):\n print("Hello", name)\n\nhello("Azhar")',
"exercises": [
"Create a simple decorator.",
"Create a decorator that accepts arguments.",
"Create a generator with yield.",
"Iterate over a generator.",
"Create a context manager with with.",
"Add type hints to a function.",
"Use a dataclass.",
"Create a custom iterator.",
"Combine a decorator with a function returning a value.",
"Refactor a small program using one advanced feature.",
],
"challenge": "Build a small reusable utility using a decorator, generator, or context manager and explain why you chose it.",
"hints": [
"A decorator receives a function and returns a function.",
"Generators use yield.",
"Choose the advanced feature that makes the program clearer.",
],
},
{
"title": "Security-Focused Python",
"level": "Advanced",
"goal": "Practice safe, defensive and security-aware Python.",
"concepts": [
("Secure randomness", "Use secrets rather than random for security-sensitive tokens."),
("Input validation", "Validate input before using it."),
("Least privilege", "Programs should request only the permissions they need."),
("Secrets", "Do not hard-code API keys or passwords in source code."),
("Authorized testing", "Only test systems and data you own or are explicitly authorized to test."),
],
"example": 'import secrets\n\ntoken = secrets.token_hex(16)\nprint(token)',
"exercises": [
"Generate a secure token with secrets.",
"Generate a secure random URL-safe token.",
"Validate a username format.",
"Validate numeric input.",
"Keep a secret out of source code.",
"Read a non-secret configuration value from an environment variable.",
"Hash a password using a suitable password-hashing library in an authorized project.",
"Avoid unsafe string-built SQL.",
"Create a safe file-name validator.",
"Write a security checklist for a small Python app.",
],
"challenge": "Build a defensive input-validation utility that rejects unsafe or malformed input and explains why.",
"hints": [
"Use secrets for security-sensitive random values.",
"Never place real API keys in source code.",
"Keep examples focused on systems and data you are authorized to use.",
],
},
{
"title": "Project Challenge",
"level": "Advanced",
"goal": "Combine your Python skills in a practical CLI project.",
"concepts": [
("Plan", "Define the problem, inputs, outputs, and features."),
("Design", "Break the project into functions, modules, or classes."),
("Build", "Implement one small feature at a time."),
("Test", "Test normal inputs, invalid inputs, and edge cases."),
("Document", "Explain how another user can install and run the project."),
],
"example": 'print("Build something useful!")',
"exercises": [
"Write a project idea.",
"Define three requirements.",
"Design the menu.",
"Define the data model.",
"Create the first function.",
"Create input validation.",
"Add persistent storage if needed.",
"Add error handling.",
"Add tests.",
"Write a README section for your project.",
],
"challenge": "Build a complete command-line application using multiple Python concepts you have learned.",
"hints": [
"Start small.",
"Separate input, logic, and output.",
"Test each feature before adding the next.",
],
},
{
"title": "Final Project",
"level": "Advanced",
"goal": "Plan, build, test and document a complete Python application.",
"concepts": [
("Requirements", "Write down exactly what the application must do."),
("Architecture", "Split the application into understandable components."),
("Implementation", "Build features incrementally."),
("Testing", "Verify normal behavior, edge cases, and failures."),
("Security", "Protect secrets and validate untrusted input."),
("Documentation", "Make installation and usage clear."),
],
"example": 'print("Your Python journey starts here!")',
"exercises": [
"Choose a final project idea.",
"Write the project requirements.",
"Create the project structure.",
"Implement the core feature.",
"Add input validation.",
"Add error handling.",
"Add persistent storage if needed.",
"Add tests.",
"Review security and secrets handling.",
"Document installation and usage.",
],
"challenge": "Build and document your own complete Python project. Use the skills from the entire roadmap.",
"hints": [
"Choose a project that is useful and achievable.",
"Build in small tested steps.",
"Do not put real credentials in your source code.",
],
},
]
# ============================================================
# GLOBAL API KEY
# ============================================================