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