Free Python Exercises
Beginner to Advanced

494 hands-on Python coding exercises across 8 tracks that run right in your browser. No install, no account. Write real Python and get instant feedback.

Start Practising Free โ†’
๐Ÿฃ Beginner Python Exercises
Master Python fundamentals. Perfect if you've just started learning or are coming from another language.
โšก Intermediate Python Exercises
Level up with Python's most powerful features, the ones that make your code elegant and fast.
๐Ÿ”ฅ Advanced Python Exercises
Python concepts that separate intermediate coders from senior developers.

Complete Python Curriculum (494 Exercises)

Browse all 494 Python coding problems by learning track. Every problem runs in your browser with real-time test validation.

๐Ÿฃ Beginner Track 100 exercises

Variables, loops, conditionals, and foundational data structures.

Your First Scripteasy Store a Valueeasy Do Some Mathseasy Greet by Nameeasy Numbers Are Not Texteasy Convert a Form Valueeasy Format a Priceeasy Unpack Coordinateseasy Swap Two Valueseasy Shout a Messageeasy Slice an Order Codeeasy Format a Welcome Emaileasy Sanitise a Usernameeasy Rebuild a File Patheasy Parse a CSV Lineeasy Count and Locate a Keywordeasy Filter Log Lines by Leveleasy Check How a String Startseasy Repeat and Build a Lineeasy Pick from a Playlisteasy Count the Guestseasy Build a Task Queueeasy Retrieve the Latest Log Entryeasy Remove a Cancelled Jobeasy Sort a Priority Queueeasy Check a Shopping Carteasy Summarise a Sales Dayeasy Insert and Remove by Positioneasy Count and Locate an Itemeasy Copy a List Safelymedium Compare Two Numberseasy Check for Equalityeasy Is It on the List?easy Check Access Permissionseasy Flag a Suspicious Transactioneasy Flip a Switcheasy Combine Conditionseasy Check Membershipeasy Bring an Umbrellaeasy Approve or Decline a Paymenteasy Even or Oddeasy Check a Password Lengtheasy Grade a Test Scoreeasy Free Shipping Thresholdeasy Classify a Loan Applicationeasy Chain Several Conditionseasy Guard Against Bad Inputeasy Print Every Nameeasy Number a Reporteasy Print a Times Tableeasy Total a Shopping Carteasy Number a Menueasy Sample Every Other Readingeasy Skip Inactive Userseasy Find the First Failing Testeasy Loop With an Indexeasy Skip and Stopmedium Count Down a Launch Timereasy Double Until Bigeasy Stop at the Limiteasy Collect Valid Inputseasy Drain a Job Queueeasy Count Down to Zeroeasy Accumulate Until a Limitmedium Repeat Until Validmedium Read a Profile Fieldeasy Look Up a Customer Recordeasy Read a Setting with a Fallbackeasy Add a New Fieldeasy List All Config Keyseasy List Every Settingeasy Merge User Settingseasy Loop Over Keys and Valueseasy Remove an Entryeasy Check Before You Readmedium Your First Functioneasy Build a Greeting Functioneasy Add Two Numberseasy Calculate Shipping Costeasy Give an Argument a Defaulteasy Return the Longer Wordeasy Reuse One Functioneasy Return Versus Printeasy Give an Argument a Defaulteasy Return More Than One Valuemedium Call One Function From Anothermedium Double Every Numbereasy Uppercase Every Tageasy Build a List From a Rangeeasy Filter While Buildingeasy Square a List of Scoresmedium Keep the Long Wordsmedium Add Tax to Every Pricemedium Give a Class a Methodeasy Give an Object a Methodeasy Model a Productmedium Make Two Objectsmedium A Method That Changes Statemedium Change an Attributemedium Two Objects, Separate Datamedium
โšก Intermediate Track 100 exercises

Functions, comprehensions, error handling, OOP, and generators.

Filter and Transform at Onceeasy Set Comprehension for Unique Valueseasy Generate a Multiplication Tablemedium Build a Word Length Indexmedium Extract Unique Domainsmedium Flatten a Nested Listmedium Conditional Expression Inside a Comprehensionmedium Count Vowels in a Stringeasy Parse a Log Headereasy Pad Invoice Numberseasy Convert Headers to Title Casemedium Format a Price Listmedium Split on Multiple Delimitersmedium Build a Slugmedium Truncate With an Ellipsismedium Extract Numbers from Texteasy Find All Matcheseasy Redact Phone Numbersmedium Validate an Email Patternmedium Capture Groups From a Log Linemedium Named Groups for Readabilitymedium Substitute With a Functionhard Number a Report with enumerate()easy Find New Subscriberseasy Set Operations for Access Controleasy Pair Headers with Row Valueseasy Find Common Skillsmedium Tuples as Dictionary Keysmedium Unpack Nested Tuplesmedium Safe Lookups With geteasy Count Without Countereasy Merge With Precedenceeasy Invert a Dictionarymedium setdefault for Groupingmedium Filter a Dictionarymedium Nested Dictionary Accesshard Counter for Frequencieseasy Group Words by First Lettermedium Model a Point with namedtuplemedium Keep the Last N Readingsmedium defaultdict Removes the Guardmedium deque for Both Endsmedium Counter Arithmetichard Sort by a Key Functioneasy Sort Without Losing the Originaleasy Sort Dictionaries by Fieldmedium Stable Sort in Practicemedium Sort Strings as Numbersmedium Sort by Two Fieldshard Unpack a List into Argumentseasy Build a Flexible Aggregatormedium Set a Default Timeoutmedium Accept Keyword Argumentsmedium Keyword-Only Argumentsmedium Mutable Default Trapmedium Forward Arguments With *args and **kwargshard Write a Price Adjuster Lambdaeasy Validate a Batch with any() and all()easy Apply Discounts with map()medium Filter Short Passwordsmedium Sort a Leaderboard by Scoremedium Multiply a List with reduce()medium Return a Functionhard Write a Simple Decoratorhard Stream Results Lazilymedium Sum Squares Without a Listmedium Write a Generator Functionmedium Generator Expressions Save Memorymedium Take the First Nmedium Chain and Zip Iteratorshard Build a Custom Iteratorhard Catch a Runtime Erroreasy Catch Narrowlyeasy Validate Form Inputmedium Handle Multiple Exception Typesmedium else and finallymedium Raise Your Own Exceptionmedium Add Context When Re-raisinghard Retry With a Limithard Parse a JSON Stringeasy Read CSV From a Stringmedium Handle Quoted Fieldsmedium Produce JSON Outputmedium Handle Malformed JSONmedium Write CSV to a Stringhard Difference Between Dateseasy Add a Durationeasy Parse and Format a Datemedium Sort Records by Datemedium Group by Monthhard Add a Static Validatormedium Build an Alternative Constructormedium String Representationmedium Properties Instead of Gettersmedium Call super() Correctlymedium Dataclasses Cut the Boilerplatemedium Extend an Animal Classmedium Override and Extend a Methodmedium Equality and Hashinghard Make an Object Iterablehard
๐Ÿ”ฌ Advanced Track 34 exercises

Dataclasses, context managers, closures, enums, and protocols.

Flatten a Matrixmedium Build a Word Length Indexmedium Invert a Dictionarymedium Create a Multiplier Factorymedium Write a Logging Decoratorhard Track Function Call Counthard Build a Rate Limiterhard Compute Area as a Propertymedium Make a Class Human Readablemedium Make a Class Work with len()medium Operator Overloading: Containseasy Callable Objectseasy Operator Overloading: Additionmedium Property Setter with Validationmedium Abstract Base Classesmedium Enumerationseasy Define a Lightweight Data Modelmedium Add Computed Fields to a Dataclassmedium Partial Functionsmedium Preserving Function Metadatamedium Manual Memoizationhard Custom Iterator Protocolmedium Generate All Feature Pairingshard Chunk a List into Batcheshard itertools.chaineasy itertools.producteasy itertools.accumulateeasy Generator Pipelinehard Compute Power Recursivelymedium Flatten a Nested Listmedium Compute Fibonacci Recursivelyhard Context Manager with Error Handlingmedium Manage Resources Safelyhard __slots__ for Memory Efficiencyeasy
๐Ÿ† Interview Prep 100 exercises

Two pointers, sliding window, binary search, trees, and dynamic programming.

Find a Budget Matcheasy Find the Top Searched Termeasy First Non-Repeating Charactereasy Detect Duplicate Valueseasy Merge Two Dictionaries by Keyeasy Group Anagrams Togethermedium Top K Frequent Elementsmedium Product Except Selfmedium Longest Consecutive Runmedium Subarray Sum Equals Khard Check for Palindromeseasy Detect Word Anagramseasy Reverse a Breadcrumb Patheasy Valid Palindrome, Messy Inputeasy Reverse the Words, Not the Letterseasy Longest Common Prefixmedium Longest Substring Without Repeatsmedium Compress a Repeated Stringmedium Word Frequency, Rankedmedium Merge Two Sorted Queuesmedium Move Zeros to the Endmedium Container With Most Watermedium Remove Duplicates In Placemedium Three Sum to Zerohard Rolling Averageeasy Maximum Sum Windowmedium Smallest Window Above a Thresholdmedium Longest Window With Two Distinct Valueshard Find All Anagram Positionshard Validate Bracket Syntaxmedium Undo Stack With Min Lookupmedium Next Greater Pricemedium Evaluate Reverse Polishmedium Queue From Two Stacksmedium Sliding Window Maximumhard Search a Sorted Cataloguemedium First and Last Positionmedium Square Root Without Mathmedium Search a Rotated Loghard Minimum Capacity to Shiphard Find the Middle Nodeeasy Reverse a Linked Listmedium Detect a Cyclemedium Merge Two Sorted Listsmedium Remove the Nth From the Endmedium Depth of a Treeeasy Invert a Treeeasy Level Order Traversalmedium Lowest Common Ancestormedium Validate a Search Treehard Count Connected Servicesmedium Shortest Path in Hopsmedium Flood Fill a Regionmedium Detect a Dependency Cyclehard Order the Build Stepshard K Largest Without Sortingeasy Merge K Sorted Streamsmedium Task Scheduler by Prioritymedium Kth Smallest in a Streamhard Can Attend Every Meetingeasy Merge Overlapping Bookingsmedium Insert a New Intervalmedium Minimum Meeting Roomshard Make Change With Fewest Coinseasy Best Time to Buy a Stockmedium Jump to the Endmedium Gas Station Loophard Cache Fibonacci Resultsmedium Climbing Stairsmedium House Robbermedium Maximum Subarray Summedium Unique Paths on a Gridmedium Coin Change, Any Coinshard Longest Increasing Subsequencehard All Subsetsmedium All Permutationsmedium Letter Combinations of a Phone Numbermedium Combination Sumhard Rotate an Imagemedium Zero Out Rows and Columnsmedium Spiral Orderhard Locate a Missing Transaction IDeasy Power of Two Checkeasy Single Unpaired Valuemedium Count the Set Bitsmedium Reverse an Integer Safelymedium Comprehensions Over Loopseasy Unpacking and Star Argseasy Generators for Large Streamsmedium Context Manager for Cleanuphard Dataclass Over Boilerplatemedium Properties Over Gettersmedium Custom Exceptionsmedium Design an LRU Cachehard Find the Missing Edge Caseeasy Write the Assertionsmedium Property-Based Thinkinghard Fix the Generated Solutionmedium Spot the Quadratichard Review Before You Shiphard
๐Ÿ“Š Data Analysis 16 exercises

Summarising, normalizing, grouping, and statistical operations.

Summarise Sales Figureseasy Compute a Weighted Averageeasy Normalise Performance Scoresmedium Rank Values in a Datasetmedium Tally Survey Responseseasy Find the Top Sellereasy Average Revenue by Departmentmedium Group Sales by Regionmedium Detect Missing Data Pointseasy Parse a CSV Reportmedium Bucket Users by Age Groupmedium Flag Anomalous Sensor Readingsmedium Measure Variable Correlationhard Smooth a Price Time Seriesmedium Find the Longest Active Streakmedium Calculate Month over Month Growthmedium
โš™๏ธ Automation 16 exercises

Text parsing, log filtering, contact extraction, and file management.

Harvest Contact Emailseasy Validate Customer Phone Numberseasy Extract URLs from Texteasy Extract Error Messages from Logsmedium Validate an Email Addressmedium Decode an API Responseeasy Build a Query Stringeasy Generate a Monthly Reportmedium Auto Fill a Contract Templatemedium Count Keyword Mentionseasy Deduplicate a Contact Listeasy Count Words and Lineseasy Convert Config to Environment Variableseasy Parse a Server Config Filemedium Generate a URL Slugmedium Format a Log Timestampeasy
๐Ÿค– AI Wiring 64 exercises

Prompt templating, token counting, JSON schemas, tool calling, and RAG.

Build a Prompt Templateeasy Count Tokens (Simple)easy Build a Chat Message Listeasy Truncate to Token Budgeteasy Parse a JSON Responseeasy Extract a Bullet Listeasy Handle Malformed JSONmedium Strip Code Fencesmedium Extract Key-Value Pairsmedium Validate Required Fieldsmedium Chunk a Documentmedium Simple Keyword Searchmedium Rank by Keyword Overlapmedium Build a Context Windowmedium Deduplicate Retrieved Chunkseasy Assert Output Schemamedium Normalise a Scoreeasy Flatten a Nested LLM Responsemedium Pick the Best Completionmedium Format a Prompt with Historymedium Parse a Tool Callmedium Route by Intentmedium Retry on Empty Responsemedium Merge Tool Resultshard Filter Hallucinated Fieldshard Injection Guardhard Split on Sentence Boundarieshard Extract JSON from Mixed Texthard Cap Response Lengtheasy Log LLM Callsmedium Few-Shot Examplesmedium Chain of Thought Prefixeasy Role Injectioneasy Detect Sensitive Datamedium Summarise Conversationmedium Parse a Numbered Listeasy Extract a Scoremedium Split Into Sectionsmedium Detect Refusaleasy Normalise Whitespaceeasy Score by Recencymedium Filter by Minimum Scoreeasy Build a Source Listeasy Truncate Chunk to Fitmedium Overlap Chunkinghard Enforce Max Lengtheasy Convert to Snake Casemedium Ensure List Outputmedium Round All Floatseasy Build a Tool Schemamedium Validate Tool Argumentsmedium Chain Tool Resultshard Handle Tool Timeouthard Add Output Format Instructionseasy Build a Multi-Step Promptmedium Remove Preamblemedium Count Sentenceseasy Compute Coveragemedium Remove Short Chunkseasy Detect Missing Valuesmedium Serialize for APImedium Pick the Right Toolmedium Paginate Resultshard Redact PII Before Sendinghard
๐Ÿงช Testing & Debugging 64 exercises

Unit testing, mocking, assertions, edge cases, and regression testing.

Your First Asserteasy Catch a Failing Asserteasy Assert With a Messageeasy Assert Typeseasy Assert a Rangeeasy Write a Test Casemedium Test for Exceptionsmedium Multiple Assertionsmedium Edge Cases: Empty Inputmedium Boundary Valuesmedium Test Return Typeseasy Test for No Side Effectsmedium Replace a Dependencymedium Count Callsmedium Mock a Return Valuemedium Verify Call Argumentshard Find the Bugmedium Test String Outputeasy Parametric Testing (Manual)medium Test a List Resulteasy Negative Testingmedium Side Effectshard Test Idempotencymedium Spot the Missing Casemedium Test setUpmedium Test a Dict Resulteasy Patch a Built-inhard Test None Handlingmedium Regression Testhard Full Test Suitehard Assert Approximate Equalityeasy Assert Sortedeasy Assert No Duplicateseasy Assert Dict Subsetmedium Assert All Items Matchmedium assertIneasy assertIsNoneeasy assertGreatereasy Test Raises with Messagemedium tearDownmedium Skip a Testmedium Count Failuresmedium assertAlmostEqualeasy Assert Not Calledmedium Mock a Propertymedium Spy on Call Args Listmedium Reset a Mockeasy Patch os.getcwdhard Mock Multiple Return Valuesmedium Assert Called Onceeasy Mock a Context Managerhard Test a Generatormedium Test Mutationmedium Test With Large Inputmedium Test Chained Callsmedium Test a Recursive Functionhard Test Order Independencehard Test Error Message Contentmedium Test a Class Methodmedium Test __str__easy Test Immutabilityhard Test Caching Behaviourhard Verify No Exception Raisedeasy Full Red-Green-Refactorhard

All exercises run in your browser

Real CPython via WebAssembly. No install. No account needed to start.

Try Your First Exercise Free โ†’

Why Python coding exercises beat tutorials

Reading about Python is easy. You nod along, the code in the examples makes sense, and you feel like you're making progress. Then you close the tab and open a blank file, and nothing comes out. This is the tutorial gap, and it's where most self-taught programmers get stuck.

The fix is deliberate practice: writing code from scratch, seeing it run or fail, and correcting it yourself. PyChallenge is built entirely around this loop. Every exercise gives you a blank editor, a clear goal, and instant feedback the moment you hit Run.

What makes a good Python exercise?

Good Python exercises share a few traits:

Python exercises for beginners

If you're new to Python, the best exercises start with the absolute basics: printing output, assigning variables, and using strings. From there, work up to conditionals and loops. The goal at this stage isn't elegance. It's building a mental model of how Python executes code line by line.

Python exercises for intermediate developers

Once you're comfortable with the basics, the real power of Python opens up. List comprehensions, functions with *args and **kwargs, classes, and error handling are the topics that separate casual Python readers from developers who can actually build things. These are the topics where PyChallenge's intermediate track focuses.

Python exercises for advanced topics

Advanced Python (decorators, generators, metaclasses, dataclasses, context managers) is where most online resources run out of good exercises. PyChallenge covers these topics with hands-on problems that require you to write real implementations, not just recognise patterns.

Frequently asked questions

Do I need to install Python?

No. PyChallenge runs actual CPython in your browser via WebAssembly (Pyodide 0.25). Every exercise runs locally in your tab. There's no server, no install, and no account required.

Is PyChallenge free?

Yes. All exercises are free. You can use the app without signing up. Creating an account (also free) lets you save your XP and daily streak across sessions.

How many Python exercises are there?

PyChallenge currently has 494 exercises across 8 tracks: Beginner, Intermediate, Advanced, Automation, Data Analysis, Interview Prep, AI Wiring, and Break It. New exercises are added regularly.