Python Exercises
400 exercises with a Check button that tests your code. Each one links to the lesson that teaches it.
Start with the 50 practice problems
Classic problems from FizzBuzz to an LRU cache, in order of difficulty. Also on one page.
- FizzBuzz
- Reverse the Words
- Count the Vowels
- Palindrome Check
- Sum of Digits
- Largest Number Without max()
- Remove Duplicates, Keep the Order
- Second Largest Value
- Most Common Character
- Are They Anagrams?
- Factorial, With a Proper Error
- Is It Prime?
- Letter Grade
- Title Case Without .title()
- Common Elements
- Flatten a List of Lists
- Merge Two Inventories
- Invert a Dictionary
- Password Strength Check
- Average of Messy Input
- Fibonacci Generator
- Sieve of Eratosthenes
- Caesar Cipher
- Top Words in a Text
- Group the Anagrams
- Balanced Brackets
- Run-Length Encoding
- Binary Search
- Merge Two Sorted Lists
- Rotate a List
- Deep Flatten
- Roman Numerals
- Longest Common Prefix
- Parse a Log Line With Regex
- A Bank Account Class
- Two Sum
- Longest Substring Without Repeats
- Merge Overlapping Intervals
- Top K Frequent Elements
- Maximum Subarray (Kadane)
- Coin Change (Dynamic Programming)
- Longest Increasing Subsequence
- Shortest Path in a Graph (BFS)
- LRU Cache
- Trie for Autocomplete
- Write a Memoize Decorator
- A Retry Decorator With Arguments
- A Context Manager That Cleans Up
- Revenue by Region With pandas
- Leaderboard With a Dataclass
Python Fundamentals
Beginner
- Print a GreetingBeginner
- Restaurant BillBeginner
- Personal IntroductionBeginner
- Fix the Bug: Broken CalculatorBeginner
Variables and Data Types
- Create Variables of Each TypeBeginner
- Temperature ConverterBeginner
- Predict the Output: Truthy or Falsy?Beginner
- Fix the Bug: String + Number CrashBeginner
- Swap Two VariablesBeginner
- Type Conversion ChainBeginner
Numbers and Math
- Calculate the Total CostBeginner
- Even or Odd CheckerBeginner
- Fix the Bug: Wrong DivisionBeginner
- Fahrenheit to Celsius ConverterBeginner
- Predict the OutputBeginner
- Compound Interest CalculatorBeginner
Strings
- Build a Greeting with ConcatenationBeginner
- Get the First and Last CharacterBeginner
- Reverse a StringBeginner
- Predict the Slice OutputBeginner
- Fix the Bug: Mutating a StringBeginner
- Check If a Word Is in a SentenceBeginner
- Extract a Domain from an Email AddressBeginner
String Methods
- Clean Up User InputBeginner
- Count Word OccurrencesBeginner
- Replace All OccurrencesBeginner
- Split a CSV LineBeginner
- Fix the Bug: find() vs index()Beginner
- Validate a UsernameBeginner
String Formatting
- Format a Receipt LineBeginner
- Format a Large Number with CommasBeginner
- Create a Formatted Table RowBeginner
- Fix the Broken f-stringBeginner
- Generate a Personalized Email GreetingBeginner
Booleans and Operators
- Check if a Number Is in RangeBeginner
- Validate a String LengthBeginner
- Predict the Logical OutputBeginner
- Fix the Comparison BugBeginner
- Check for a Leap YearBeginner
- Evaluate Truthiness with bool()Beginner
Input and Output
- Print with a Custom SeparatorBeginner
- Print Items on the Same LineBeginner
- Create a Multiplication TableBeginner
- Print a Formatted ReceiptBeginner
Type Conversion
- String to Int and MultiplyBeginner
- Float to Int: What Gets Lost?Beginner
- Predict the Output: Type ConversionsBeginner
- Fix the Bug: String and Int ConcatenationBeginner
- Convert Only the NumbersBeginner
Clean Code
- Add Comments and a DocstringBeginner
- Fix the Bad Variable NamesBeginner
- Rewrite Messy Code with PEP 8 StyleBeginner
- Refactor: Clean Up This CodeBeginner
Control Flow
If-Else
- Even or OddBeginner
- Temperature AdvisorBeginner
- Predict the OutputBeginner
- Fix the Grade CalculatorBeginner
- Ternary Ticket PriceBeginner
- Login ValidatorBeginner
For Loop
- Print the Shopping ListBeginner
- Sum Numbers 1 to 10Beginner
- Predict the OutputBeginner
- Fix the Bug: Letter CounterBeginner
- Numbered MenuBeginner
- Reverse a StringBeginner
- Student Grade ReportBeginner
While Loop
- Countdown TimerBeginner
- Power of 2 FinderBeginner
- Predict the OutputBeginner
- Fix the Bug: Digit CounterBeginner
- The Collatz SequenceBeginner
Break and Continue
- Find the First Negative NumberBeginner
- Print Without VowelsBeginner
- Predict the OutputBeginner
- Fix the Bug: Sum Until NegativeBeginner
- Password Checker with for-elseBeginner
Nested Loops
- Print a RectangleBeginner
- Predict the OutputIntermediate
- Number TriangleIntermediate
- Sum All Grid ValuesIntermediate
- All Outfit CombinationsIntermediate
- Fix the Coordinate GridIntermediate
Error Messages
- Fix the SyntaxErrorBeginner
- Fix the NameErrorBeginner
- Fix the TypeErrorBeginner
- Fix the IndexErrorBeginner
- Fix the ValueErrorBeginner
- Fix All the BugsBeginner
Data Structures
List
- Create a List and Print Its LengthBeginner
- Access the Last Item with Negative IndexingBeginner
- Shopping List: Add and Remove ItemsBeginner
- Fix the Bug: IndexErrorBeginner
- Sum All Numbers Using a LoopBeginner
- Find the Largest Number Without max()Intermediate
- Predict the Output: List AliasingIntermediate
- Reverse a List Without reverse() or [::-1]Intermediate
List Comprehension
- Double Every NumberBeginner
- Filter Even NumbersBeginner
- Predict the Output: if vs if-elseIntermediate
- Create a Dict ComprehensionIntermediate
- Unique Vowels with a Set ComprehensionIntermediate
- Fix the Bug: Wrong Comprehension SyntaxIntermediate
- Refactor a Loop into a ComprehensionIntermediate
- Flatten a MatrixAdvanced
Tuple
- Create a Tuple and Access ElementsBeginner
- Predict the Output: Single Item TupleBeginner
- Unpack a TupleBeginner
- Fix the Bug: Modifying a TupleBeginner
- Loop and Unpack Student ScoresIntermediate
Dictionary
- Create a Dictionary and Access a ValueBeginner
- Add and Modify Dictionary EntriesBeginner
- Safe Access with get()Beginner
- Loop Through a DictionaryBeginner
- Predict the Output: Duplicate KeysBeginner
- Fix the Bug: Checking for a ValueIntermediate
- Build a Word CounterIntermediate
- Access Nested Dictionary DataIntermediate
Set
- Remove Duplicates from a ListBeginner
- Predict the Set OutputBeginner
- Find Students in Both ClassesIntermediate
- Fix the Empty Set BugIntermediate
- Find Missing IngredientsIntermediate
- Deduplicate While Preserving OrderAdvanced
Slicing
- Get the Middle ItemsBeginner
- Predict the Slice OutputBeginner
- Extract Even-Indexed ItemsIntermediate
- Reverse a WordBeginner
- Fix the Slicing BugIntermediate
- Palindrome CheckerAdvanced
Unpacking
- Unpack a CoordinateBeginner
- Swap Two VariablesBeginner
- Head and Tail with StarIntermediate
- Predict the Unpacking OutputIntermediate
- Unpack Student RecordsAdvanced
Sorting
- Sort a List of NumbersBeginner
- Predict the Output: sort() vs sorted()Beginner
- Sort Words by LengthIntermediate
- Fix the Bug: Case-Sensitive SortingIntermediate
- Sort Students by GradeIntermediate
- Sort by Multiple CriteriaAdvanced
Nested Data
- Access Nested List ItemsBeginner
- Predict the Output: Nested Dict AccessBeginner
- Find the Highest ScorerIntermediate
- Group Words by First LetterIntermediate
- Fix the Bug: Nested List TrapIntermediate
- Calculate Class AveragesAdvanced
Copy and Deepcopy
- Predict the Output: Assignment AliasingBeginner
- Make an Independent CopyBeginner
- Predict the Output: Shallow Copy TrapIntermediate
- Safe Copy of Nested DataIntermediate
- Fix the Game State BugAdvanced
Functions
Function
- Say HelloBeginner
- Predict the OutputBeginner
- Area of a RectangleBeginner
- Fix the Broken FunctionIntermediate
- Temperature ConverterIntermediate
- Build a Grade CalculatorAdvanced
Function Arguments
- Predict the Keyword CallBeginner
- Greeting with a DefaultBeginner
- Sum All NumbersIntermediate
- Fix the Mutable DefaultIntermediate
- Build a Profile StringIntermediate
- Flexible CalculatorAdvanced
- Refactor to Use **kwargsAdvanced
Lambda
- Predict the Lambda OutputBeginner
- Sort by Last CharacterBeginner
- Filter and TransformIntermediate
- Sort Students by GPAIntermediate
- Sort Words by LengthAdvanced
Scope and Closures
- Predict the Scope OutputBeginner
- Fix the Global Counter BugBeginner
- Build a Greeting ClosureIntermediate
- Build a Counter with nonlocalIntermediate
- Build a Running Average ClosureAdvanced
Recursion
- Predict Recursive OutputBeginner
- Recursive Sum 1 to NBeginner
- Fix the Broken Power FunctionIntermediate
- Recursive FibonacciIntermediate
- Reverse a String RecursivelyIntermediate
- Count Digits RecursivelyAdvanced
Map, Filter and Reduce
- Square Every NumberBeginner
- Filter Out Short WordsBeginner
- Predict the Pipeline OutputBeginner
- Fix the Broken PipelineIntermediate
- Find the Product with reduce()Intermediate
- Build a Data PipelineAdvanced
- Refactor to a List ComprehensionAdvanced
Error Handling
Try-Except
- Safe DivisionBeginner
- Predict the OutputBeginner
- Fix the Number ConverterIntermediate
- Input Validator with raiseIntermediate
- Safe Dictionary LookupAdvanced
- Build a Safe CalculatorAdvanced
Custom Exceptions
- Create a Custom ExceptionBeginner
- Predict the Exception HierarchyBeginner
- Exception with Extra DataIntermediate
- Build a Shopping Cart Exception HierarchyAdvanced
- Refactor: Replace Generic with Custom ExceptionsAdvanced
Context Manager
- Predict the Output: Basic withIntermediate
- Write a Logging Context ManagerIntermediate
- Fix the Bug: Missing CleanupIntermediate
- Write an Indentation Context ManagerAdvanced
- Refactor: Replace try/finally with a Context ManagerAdvanced
- Build a Batch Processor Context ManagerAdvanced
Logging
- Predict the Output: Log Level FilteringBeginner
- Add Logging to a FunctionBeginner
- Fix the Bug: Missing MessagesIntermediate
- Build a Login Validator with LoggingIntermediate
- Refactor: Replace print() with LoggingIntermediate
Modules & Packaging
Imports
- Predict the Output: import vs from...importBeginner
- Use the random ModuleBeginner
- Fix the Bug: Broken ImportsBeginner
- Use Import AliasesBeginner
- Write a Module with __name__ GuardIntermediate
Package
- Build a Package Structure DictionaryBeginner
- Fix the Broken __all__ ExportIntermediate
- Predict the Import PathIntermediate
- Refactor Into a Package RegistryAdvanced
Virtual Environment
- Parse a Requirements FileBeginner
- Fix the Dependency ResolverIntermediate
- Predict the Environment CheckIntermediate
- Build a Virtual Environment ManagerAdvanced
PyPI Packaging
- Build Package MetadataBeginner
- Fix the Version ComparatorIntermediate
- Predict the Build OutputIntermediate
- Refactor the Version BumperIntermediate
- Build a Release ManagerAdvanced
File I/O & Data Formats
File Handling
- Read and Print File ContentsBeginner
- Predict the Read OutputBeginner
- Write and Read BackIntermediate
- Fix the File Reading BugIntermediate
- Line Number FormatterAdvanced
CSV
- Read CSV and Print NamesBeginner
- Predict the DictReader OutputBeginner
- Build a CSV StringIntermediate
- Fix the CSV Sum BugIntermediate
- Filter and Count CSV RowsAdvanced
JSON
- Parse a JSON StringBeginner
- Predict the JSON OutputBeginner
- Create Pretty JSONIntermediate
- Fix the JSON Parsing BugIntermediate
- Refactor String Concatenation to json.dumpsIntermediate
- Extract Data from Nested API JSONAdvanced
pathlib
- Extract Path ComponentsBeginner
- Predict the Joined PathBeginner
- Change File ExtensionIntermediate
- Fix the Path Joining BugIntermediate
- Filter Files by ExtensionAdvanced
Object-Oriented Programming
Classes and Objects
- Create a Book ClassBeginner
- Add a Method to RectangleBeginner
- Predict the Counter OutputBeginner
- Fix the Student ClassIntermediate
- Add __str__ to a ProductIntermediate
- Build a Player Class with Score TrackingIntermediate
- Refactor Functions into a ClassAdvanced
Inheritance
- Create a Vehicle SubclassBeginner
- Override the describe() MethodBeginner
- Predict the super() OutputIntermediate
- Fix the Inheritance BugIntermediate
- Build a Shape Area CalculatorIntermediate
- Build a Notification SystemAdvanced
Classmethod and Staticmethod
- Create a Factory MethodBeginner
- Add a Static ValidatorBeginner
- Predict the Method OutputIntermediate
- Fix the Factory MethodIntermediate
- Build a Temperature ConverterAdvanced
@property
- Create a Read-Only Name PropertyBeginner
- Add Age Validation with a SetterIntermediate
- Fix the Infinite RecursionIntermediate
- Build a Computed Full NameIntermediate
- Predict the Temperature OutputIntermediate
- Refactor to Use @propertyAdvanced
Magic Methods
- Add String Representations to a BookBeginner
- Build a Team with __len__Beginner
- Fix the Broken Equality CheckIntermediate
- Make a Gradebook IndexableIntermediate
- Predict the Magic Method OutputIntermediate
- Make Tasks Sortable by PriorityIntermediate
- Create a Callable FormatterAdvanced
- Refactor a Playlist with Magic MethodsAdvanced
Operator Overloading
- Add Two Points TogetherBeginner
- Scale a Vector with MultiplicationIntermediate
- Fix the Broken __iadd__Intermediate
- Predict the Operator OutputIntermediate
- Build a Fraction ClassAdvanced
- Refactor Methods to OperatorsAdvanced
Abstract Base Class
- Create an Animal ABCIntermediate
- Predict the ABC ErrorIntermediate
- Fix the Broken ABCIntermediate
- Abstract Property: Employee TypesAdvanced
- Refactor to Use ABCAdvanced
Multiple Inheritance
- Create a Hybrid ClassIntermediate
- Predict the MROAdvanced
- Fix the Cooperative __init__Advanced
- Build a TimestampMixinAdvanced
- Predict the super() ChainAdvanced
Dataclass
- Create a Product DataclassBeginner
- Playlist with Default TagsIntermediate
- Fix the Dataclass BugIntermediate
- Rectangle with Computed AreaIntermediate
- Predict Frozen BehaviorIntermediate
- Sort Students by GPAIntermediate
- Refactor to a DataclassAdvanced
NamedTuple and TypedDict
- Create a NamedTuple for RGB ColorsBeginner
- Build a TypedDict for API ResponseBeginner
- Predict the Output: ImmutabilityIntermediate
- Convert a Dict to a NamedTupleIntermediate
- Choose the Right ContainerAdvanced
__slots__
- Create a Slotted ClassBeginner
- Predict the Output: Slots RestrictionBeginner
- Fix the Bug: Missing SlotIntermediate
- Slots with InheritanceAdvanced
- Compare Memory: Regular vs SlottedAdvanced
Advanced Dataclass
- Validate with __post_init__Beginner
- Safe List Default with field()Beginner
- Predict the Output: Frozen DataclassIntermediate
- Computed Field with __post_init__Intermediate
- Dataclass InheritanceAdvanced
- Refactor: Add Validation and Computed FieldsAdvanced
Composition
- Build a Computer with CompositionBeginner
- Predict the Output: Swapping ComponentsIntermediate
- Compose Multiple AbilitiesIntermediate
- Refactor Inheritance to CompositionAdvanced
- Dependency Injection: Notification SystemAdvanced
Testing
pytest
- Write Your First TestBeginner
- Fix the Failing TestBeginner
- Predict the Test ResultsIntermediate
- Test the Edge CasesIntermediate
- Build a Mini Test RunnerAdvanced
- Refactor Repetitive TestsAdvanced
Mocking
- Create a Mock Email ServiceIntermediate
- Predict the Mock BehaviorIntermediate
- Mock the ClockAdvanced
- Build a Test FixtureAdvanced
- Fix the Broken MockAdvanced
TDD
- Your First TDD CycleIntermediate
- TDD: Build a Password ValidatorAdvanced
- Predict the TDD ProcessIntermediate
- TDD Bug Fix: Reproduce Then FixAdvanced
- TDD Challenge: Build a Word CounterAdvanced
Standard Library Essentials
collections
- Count Character FrequencyBeginner
- Find the Top 2 Most Common WordsBeginner
- Group Names by First LetterIntermediate
- Predict the deque OutputBeginner
- Build a Recent History TrackerIntermediate
- Create and Use a namedtupleIntermediate
- Fix the defaultdict BugAdvanced
itertools
- Flatten a Nested ListBeginner
- Generate All Coin Flip OutcomesIntermediate
- Find All 2-Letter PermutationsIntermediate