Skip to content
Justice Tech School

Python Tutorial

Readable code for beginners, used everywhere from data to AI.

Start learning Python
Getting started5 lessons
  1. 1Python IntroductionWhat Python is and how to print.
  2. 2Getting StartedInstalling Python and running your first program.
  3. 3Python SyntaxIndentation and how a program is laid out.
  4. 4Output with print()Showing values on the screen.
  5. 5CommentsNotes that Python ignores.
Basics16 lessons
  1. 6Variables and TypesNaming values.
  2. 7Variable NamesRules and habits for naming.
  3. 8Assigning Many ValuesSeveral variables on one line.
  4. 9Global and Local VariablesWhere a variable can be used.
  5. 10Data TypesThe built-in kinds of value.
  6. 11Numbersint, float and arithmetic.
  7. 12CastingConverting between types.
  8. 13BooleansTrue and False.
  9. 14OperatorsArithmetic, comparison, logic and more.
  10. 15NoneThe value that means nothing.
  11. 16Numbers: int, float and complexPython has int (unlimited size), float and complex numbers.
  12. 17Booleans and NoneTrue and False are booleans.
  13. 18Input and Outputprint() writes text and input() reads a line as a string.
  14. 19Type ConversionUse int(), float(), str(), bool(), list() and tuple() to convert.
  15. 20Operators: Comparison, Logical, MembershipCompare with == != < >, combine with and, or, not, test membership with in and identity wi.
  16. 21Comments and DocstringsComments start with #.
Strings9 lessons
  1. 22StringsWorking with text.
  2. 23Slicing Strings and ListsTaking a part with [start:stop:step].
  3. 24String MethodsChanging, searching and splitting text.
  4. 25String Formattingf-strings and format().
  5. 26Escape CharactersSpecial characters inside strings.
  6. 27String Slicing and IndexingIndex from 0 or from the end with negatives.
  7. 28More String Methodssplit, join, strip, replace, find, startswith, endswith, upper, lower, title and count cov.
  8. 29f-strings in Depthf-strings embed expressions and format them: {x:.2f}, {n:,}, {s:>10}, {n:05d}, {x!r}.
  9. 30Checking and Cleaning Stringsisdigit, isalpha, isalnum, isspace and islower test content.
Collections18 lessons
  1. 31ListsOrdered collections.
  2. 32List MethodsAdding, removing and searching.
  3. 33List ComprehensionBuilding lists in one line.
  4. 34Sorting Listssort() and sorted().
  5. 35Copying ListsWhy b = a is not a copy.
  6. 36TuplesLists that cannot change.
  7. 37SetsUnique values and set maths.
  8. 38DictionariesKey and value pairs.
  9. 39Dictionary Methodskeys, values, items and more.
  10. 40Nested CollectionsLists and dicts inside each other.
  11. 41Dictionary and Set ComprehensionsComprehensions beyond lists.
  12. 42List Methodsappend, extend, insert, remove, pop, index, count, sort and reverse change lists in place.
  13. 43List ComprehensionsA comprehension builds a list in one line: [expr for x in items if cond].
  14. 44Tuples and UnpackingTuples are immutable sequences.
  15. 45Dictionary Methodsget avoids KeyError, setdefault inserts defaults, items, keys and values iterate and updat.
  16. 46Sets and Set OperationsSets hold unique items.
  17. 47collections: Counter, defaultdict, dequeCounter counts items, defaultdict creates missing values and deque is a fast queue for bot.
  18. 48Sorting with key and SortedPass key= to sort by any rule and reverse=True to flip.
Control flow11 lessons
  1. 49Conditionsif, elif and else.
  2. 50The match StatementMatching a value against patterns.
  3. 51Loopsfor and while.
  4. 52While LoopsRepeating while a condition is true.
  5. 53break, continue and elseControlling loops.
  6. 54The range() FunctionSequences of numbers.
  7. 55enumerate() and zip()Looping with positions and in pairs.
  8. 56if, elif and elsePython uses indentation for blocks.
  9. 57while Loops, break and continuewhile repeats while the condition is true.
  10. 58for Loops and rangefor walks over any iterable.
  11. 59match Statementmatch compares a value with patterns, like a powerful switch.
Functions14 lessons
  1. 60FunctionsReusable code with def.
  2. 61Function ArgumentsPositional, keyword, default, *args and **kwargs.
  3. 62Return ValuesSending results back.
  4. 63Lambda FunctionsSmall anonymous functions.
  5. 64Scope and the LEGB RuleHow Python finds a name.
  6. 65RecursionA function that calls itself.
  7. 66DecoratorsAdding behaviour to a function.
  8. 67IteratorsHow for loops really work.
  9. 68GeneratorsProducing values one at a time.
  10. 69*args and **kwargs*args collects extra positional arguments in a tuple and **kwargs collects keyword argumen.
  11. 70lambda, map, filterlambda makes small anonymous functions.
  12. 71Scope: local, global, nonlocalNames are looked up local, enclosing, global then built in.
  13. 72Decorators BasicsA decorator wraps a function to add behaviour.
  14. 73Generators and yieldA generator function uses yield to produce values one at a time and saves memory.
Modules and packages10 lessons
  1. 74Modules and importReusing code from other files.
  2. 75Packages and pipInstalling third party code.
  3. 76The math ModuleMaths functions and constants.
  4. 77The random ModuleRandom choices.
  5. 78Dates and TimesThe datetime module.
  6. 79JSONReading and writing JSON data.
  7. 80Regular ExpressionsPattern matching with re.
  8. 81The collections ModuleCounter, defaultdict and deque.
  9. 82Standard Library TourPython ships with math, random, datetime, os, sys, re, itertools and more.
  10. 83pathlib for File Pathspathlib.Path represents paths as objects.
Files and input6 lessons
  1. 84User InputReading text typed by the user.
  2. 85Reading FilesOpening and reading text files.
  3. 86Writing and AppendingSaving text to files.
  4. 87Files and Folders with osChecking, renaming and deleting files.
  5. 88Reading and Writing FilesUse with open() so the file closes.
  6. 89JSON and CSVThe json module converts dicts to text and back.
Classes and objects10 lessons
  1. 90Classes and ObjectsBlueprints for your own types.
  2. 91The __init__ MethodSetting up each new object.
  3. 92Methods and selfFunctions that belong to an object.
  4. 93InheritanceBuilding one class on another.
  5. 94PolymorphismDifferent objects, same method name.
  6. 95Class and Instance AttributesShared data versus per-object data.
  7. 96Special (Dunder) Methods__str__, __repr__, __len__ and friends.
  8. 97DataclassesLess code for simple classes.
  9. 98Dataclasses@dataclass writes __init__, __repr__ and __eq__ for you.
  10. 99Special MethodsDunder methods customise objects: __str__, __repr__, __len__, __eq__, __add__ and __iter__.
Error handling5 lessons
  1. 100Errors and try/exceptHandling mistakes gracefully.
  2. 101Raising ErrorsSignalling problems yourself.
  3. 102try, except, else and finallyThe full error handling toolkit.
  4. 103Testing with assertChecking your code is right.
  5. 104raise and Custom Exceptionsraise throws an exception.
More PythonPremium3 lessons
  1. 105Type HintsDescribing what types you expect.
  2. 106Virtual EnvironmentsA separate set of packages for each project.
  3. 107Style Guide (PEP 8)Writing code others can read.
Advanced PythonPremium17 lessons
  1. 108DecoratorsA decorator is a function that takes a function and returns a new one, adding behaviour ar.
  2. 109Decorators With ArgumentsTo pass options, write a function that returns the decorator.
  3. 110Generators and yieldA function with yield returns a generator that produces values one at a time and pauses be.
  4. 111Generator Pipelines and yield fromChain generators like a pipeline so each step handles one item at a time.
  5. 112The Iterator ProtocolAn iterator has __iter__ and __next__ and raises StopIteration when finished.
  6. 113Context ManagersThe with statement guarantees cleanup even if an error happens.
  7. 114Dataclasses@dataclass writes __init__, __repr__ and __eq__ for you from annotated fields.
  8. 115Advanced TypingGenerics, Protocol, TypedDict and Literal describe code more precisely.
  9. 116functools: cache, partial and reducelru_cache remembers results of expensive pure functions.
  10. 117itertoolsitertools builds fast, memory friendly loops: count, cycle, chain, islice, groupby, produc.
  11. 118Properties and DescriptorsA property turns a method into an attribute with validation.
  12. 119Special MethodsDunder methods let your objects work with Python syntax: __repr__ for printing, __len__ fo.
  13. 120Abstract Classes and EnumsAn abstract base class forces subclasses to implement certain methods.
  14. 121Metaclasses and Class HooksA class is an object made by a metaclass, usually type.
  15. 122__slots__ and Memory__slots__ replaces the per object dictionary with fixed storage, saving memory when you cr.
  16. 123asyncio Basicsasync def defines a coroutine.
  17. 124Running Tasks Togetherasyncio.gather runs coroutines concurrently and returns their results in order.
Python in practicePremium14 lessons
  1. 125Testing with unittestTests prove code still works after changes.
  2. 126Mocking and Isolationunittest.mock replaces slow or unpredictable parts such as the network or the clock with f.
  3. 127LoggingThe logging module records events with levels (DEBUG, INFO, WARNING, ERROR, CRITICAL), tim.
  4. 128Command Line Programs with argparseargparse builds a command line interface with options, types, defaults and automatic help.
  5. 129pathlib and Working With Filespathlib.Path treats paths as objects: join with /, read and write text, iterate folders an.
  6. 130JSON and CSV in Practicejson converts between Python objects and text.
  7. 131Dates, Times and Time Zonesdatetime handles dates and arithmetic.
  8. 132Regular Expressions In Depthre handles pattern matching.
  9. 133Databases from Pythonsqlite3 is built in.
  10. 134Threads and ProcessesThreads share memory and help with waiting on I/O.
  11. 135Measuring and Improving SpeedMeasure first with timeit and cProfile, then fix the real hotspot.
  12. 136Packaging and pyproject.tomlModern packages describe themselves in pyproject.toml.
  13. 137Calling Web APIsThe requests library (or the built in urllib) calls HTTP APIs.
  14. 138Python Best PracticesUse virtual environments, type hints, small functions, descriptive names, tests and a form.
Next steps1 lessons
  1. 139What Next?Where to go after the basics.