Python
Learn Python by typing clean, idiomatic code.
Practice Pythonic code by typing it: list and dict comprehensions, generators, decorators, context managers, and the duck typing that makes Python feel effortless. Every snippet is clean, idiomatic Python, and an AI tutor explains each line — why a comprehension beats a loop, how a decorator wraps a function — so good habits form as you build speed.
Progress0 / 754 solved · 0/50 sections
best wpm
0
avg wpm
0
accuracy
0%
runs
0
level
1
rating
1000
Run Python on your machine
1. Install the toolchain
brew install python # or: sudo apt install python32. Save your code as hello.py, then compile & run
python3 hello.pyprogress by section
1Fundamentals0/30start →
Hello, worldVariables and f-stringsBooleans and NoneConstants by conventionfor over a rangeDefine a functionif / elif / elseIntegers never overflowNumeric typesString basicsConditional expressionwhile loopbreak and continueChained comparisonsList comprehensionDefault argumentsDocstringsLoop with an indexRead from stdinKeyword argumentsReturn multiple valuesParse a numberTruthinessType hintsTuple unpackingfor ... elseFormat numbersMatch statement*args and **kwargsWalrus operator
2Strings In Depth0/19start →
Search a stringCount occurrencesStrings are immutableIndex and sliceClassify charactersIterate charactersCase and trimmingRepeat and padReplace textsplit and joinIterate linesCapitalize and title caseZero-pad numbersBuild a stringstr.formatSplit once with partitionStrip a prefix or suffixstr vs bytesTranslate characters
3Values & References0/18start →
Names bind to objectsCompare to None with isAliasingCopy a list with [:]The id() of an objectImmutable arguments are safeis vs ==Mutable vs immutableTuples are immutableShallow copyImmutable means hashablePass-by-object-referenceRebinding a parameter is localAugmented assignment differs by typeDeep copyMutable default argument gotchaShallow copy shares nested objectsA tuple can hold a mutable object
4Slices & Arrays0/19Unlock →
Slice a rangeCount occurrencesFirst and lastMembership testOmit start or stopCopy via [:]Find an indexNegative indicesReverse with a slicesorted returns a new listStep and strideSlice assignmentDelete a sliceSlice objectsSort in place with a keyBinary search with bisectFixed-size chunksKeep a list sortedSliding windows
5Data structures0/20Unlock →
6Iterators0/20Unlock →
itertools.chainComprehensionsenumeratefiltermapany and allitertools.countitertools.cycleA generator functionGenerator expressionitertools.islicenext with a defaulttakewhile and dropwhilezipitertools.accumulateA lazy infinite generatoritertools.productUnzip with zip(*)itertools.groupbyiter over a callable
7Traits0/18Unlock →
8Generics0/18Unlock →
Typing containersTyping a callableGeneric classGeneric functionReturn T or NoneGeneric returning a listTwo type parametersBounded TypeVarConstrained TypeVarGeneric dataclassGeneric over an iterableGeneric with a key functionTwo-parameter generic classNewTypetyping.SelfGeneric StackProtocol as a boundParamSpec
9Lifetimes0/14Unlock →
10Closures0/19Unlock →
A lambdaCapturing the environmentmap and filterA small inline helperCallbacksReturning a functionCapturing in a filterHigher-order functionfunctools.partialfunctools.reducereduce with an initial valueA lambda as a sort keyCurryingnonlocalA list of functionsA stateful closureCompose two functionsA decoratorLoop-variable capture gotcha
11Pattern Matching0/19Unlock →
Literals and wildcardUnpacking in assignmentCapture a valueOr-patternsMatch a tuple's shapeUnpacking in a for loopmatch as a value chooserCapture with asMatch guardsRanges via a guardMapping patternsNested unpackingSequence patternsBind the ends, skip the middleMatch on typeClass patternsCapture the rest of a mappingPositional class patternsNested patterns
12Error Handling0/19Unlock →
try / exceptassert an invariantBind the exceptionRaise an exceptionContext in messagesCustom exception classEAFP styletry / except / elsefinally for cleanupCatch several typesRead exception argsException with attributesCleanup with a context managertry / except / else / finallyException hierarchyOrdered handlersRe-raiseEmit a warningChaining with raise from
13Option & Result0/18Unlock →
None means absenceGuard against Nonedict.get with a defaultor for a fallbackOptional type hintConditional defaultDrop the Nonesgetattr with a defaultTransform only if presenttry/except as ResultRequire all presentChained lookupsNone as a default argFirst truthy valuenext with a defaultcontextlib.suppressCoalesce several optionsWalrus for optionals
14Conversions0/15Unlock →
15Collection Conversions0/18Unlock →
16Math0/19Unlock →
17Encoding0/21Unlock →
ASCII checks and caseBytes to stringChar and code pointString to bytesList code pointsFormat number basesHex decodeHex encodeParse a number in a baseBase64 encode and decodeLossy decodeBytes to integerROT13Integer to bytesPercent-encode for URLsPercent-decode a URLURL-safe base64binascii and CRC32Caesar cipherBuild and parse a query stringXOR cipher
18Random0/20Unlock →
Pick a random elementRandom integerRandom float in [0, 1)Coin flipRandom from a rangeShuffle in placeRandom float in a rangeSample without replacementReproducible sequencesRandom stringUUID version 4Random bytesRandom enum memberWeighted choicesDice histogramSecure passwordsecrets.randbelowRandom tokensNormal distributionTriangular distribution
19Data I/O0/18Unlock →
Parse CSV rowsParse JSONSum a column of numbersTab-separated valuesSelect one columnCSV into a number matrixWrite CSVCSV with a headerSplit off the headerPretty-print JSONJSON round-tripWhitespace-separated matrixSkip blanks and commentsPrint an aligned tableCSV to a file and backWrite CSV from dictsParse key=value configDrop unparseable rows
20Linear Algebra0/22Unlock →
Matrix shapeDot productScalar multiplyA matrix of zerosElementwise addArgmax of a vectorFlatten a matrixIdentity matrixOne-hot encodeTraceStack rows (vstack)ReLU and sigmoidApply a function elementwiseColumn meansColumn sumsCosine similarityMatrix times vectorTransposeMatrix multiplyMin-max normalize columnsSoftmaxStandardize columns (z-score)
21Text Processing0/18Unlock →
Word countCapitalize and title caseCount occurrencesReplace textReverse word orderStrip whitespaceCount vowelsZero-pad a numberPad and alignCharacter frequencyLongest wordNumber the linesTitle case each wordMost common wordsWrap and shortenTruncate with an ellipsisString similarityLevenshtein distance
22Date & Time0/17Unlock →
23Memory0/13Unlock →
24Modules0/18Unlock →
from ... importImport a moduleThe __main__ guardimport ... asInspect a moduleA module's docstringfrom ... import ... asGrouped importA module's __name__Standard-library tourImport a submoduleLook up a name dynamicallyNamespaces avoid clashesRelative importsA module's namespaceControl export with __all__Import by nameReload a module
25Macros0/21Unlock →
classmethod and staticmethoddataclass as codegenA simple decoratorgetattr / setattr / hasattrnamedtuple codegenfunctools.partialproperty as a decoratorCallable objects with __call__Decorate a function with argumentseval and execDispatch by method namefunctools.lru_cacheGenerate attributes in a loopfunctools.wrapsA class decoratorcontextlib.contextmanagerStateful decoratorA decorator with arguments__getattr__ hookStacking decoratorsA simple metaclass
26Testing0/20Unlock →
Plain assert statementsassertTrue and assertFalseA unit testMultiple test methodsTesting string outputAssert on a whole listassertIn and assertNotInassertIsNone and assertIsNotNoneParametrize-like loopassertRaisessetUp fixturesSkipping testsassertAlmostEqual for floatsdoctestRun a suite programmaticallyMock basicsassertRaisesRegexsetUp and tearDownTable-driven with subTestpatch.object
27Algorithms0/12Unlock →
28Sorting Algorithms0/13Unlock →
29Expression Parsing0/6Unlock →
30Idioms0/15Unlock →
31OOP & Traits0/14Unlock →
32Trait Objects0/12Unlock →
33Design Patterns0/14Unlock →
34Async0/11Unlock →
35File I/O0/10Unlock →
36Filesystem0/20Unlock →
Does a path exist?Copy a fileFiles vs directoriesList a directoryBuild a pathCreate nested directoriesRemove a fileRename or moveChange the extensionPath componentsRemove a whole treeSorted listingFile sizeA temporary directoryGlob by extensionLast modified timeWalk a tree with os.walkAbsolute pathWalk a tree with rglobTotal size of a tree
37Networking0/16Unlock →
Resolve a hostnameParse an HTTP request lineRoute by pathParse and validate an addressBuild a query stringParse a URLBind an ephemeral portBuild an HTTP responseReceive until closedShut down a connectionA TCP listening socketSocket timeoutUDP send and receivePrepare an HTTP requesthttp.server request handlerTCP client and server
38Concurrency0/15Unlock →
39Unsafe & FFI0/14Unlock →
40Commands0/15Unlock →
Just the user's argsCommand-line argumentsCurrent directoryEnv var with a defaultRead an environment variableIterate all env varsSet and remove a variableExit with a codePath to this fileFind a program on PATHParse args with argparseCommand exit statusRun a commandPass env to a childRead all of stdin
41Array0/10Unlock →
43String0/10Unlock →
45Interval0/5Unlock →
46Linked List0/6Unlock →
47Tree0/14Unlock →
Invert Binary TreeMaximum Depth of Binary TreeSame TreeLowest Common Ancestor of a BSTBinary Tree Level Order TraversalSubtree of Another TreeKth Smallest Element in a BSTImplement Trie (Prefix Tree)Validate Binary Search TreeAdd and Search WordConstruct Binary Tree from Preorder and InorderBinary Tree Maximum Path SumSerialize and Deserialize Binary TreeWord Search II