Python practice
Python exercises that check your code as you go.
264 exercises, from your first print() to graph algorithms. Write real Python in your browser, check it against tests, and see in plain English what to fix. No sign-up.
- Real Python 3.14
- Errors explained
- input() works
- Progress kept in your browser
264 exercises
NoviceFirst programs: print, input, arithmetic and simple text.
Printing
Input and output
- Hello, nameRead a name and greet that person.
- Echo, echoRead a word and print it twice, each time on its own line.
- Full nameRead a first name and a last name and print the full name.
- Age next yearRead someone's age and say how old they will be next year.
- Backwards orderRead three lines and print them in the opposite order.
- Swap two valuesRead two lines, a and b, and print them swapped: b first, then a.
- A tiny storyRead an animal and a verb, and print a sentence with them.
- Favourite foodRead a name and a food, and say who likes what.
- InitialsRead a first and a last name and print the initials, each followed by a dot.
Arithmetic
- Sum of two numbersRead two whole numbers and print their sum.
- DifferenceRead two whole numbers a and b and print a - b.
- ProductRead two whole numbers and print their product.
- Square and cubeRead a whole number n and print its square and its cube.
- Rectangle area and perimeterRead the width and height of a rectangle and print its area and its perimeter.
- Average of threeRead three whole numbers and print their average with exactly two decimals.
- Whole division and remainderRead two positive whole numbers a and b.
- Minutes to hoursRead a number of minutes and say how many hours and minutes that is.
- Seconds to a clockRead a number of seconds (less than one day) and print it as hours, minutes and
- Celsius to FahrenheitRead a temperature in degrees Celsius and convert it to Fahrenheit:
- Kilometres to milesOne kilometre is 0.621371 miles.
- Last digitRead a positive whole number and print its last digit.
- Tens digitRead a positive whole number and print its tens digit (the second digit from the
- Sum of three digitsRead a three-digit number and print the sum of its digits.
- Circle areaRead the radius of a circle and print its area with two decimals.
- PowerRead two whole numbers a and b (b is not negative) and print a to the power of b.
- ChangeA shop sells something for a price; the customer pays with a larger note.
- Split the billFriends share a restaurant bill equally.
- Pizza slicesSome pizza slices are shared equally.
- Average speedRead a distance in kilometres and a time in hours, and print the average speed in
- Round itRead a number with decimals and print it three ways, one per line: rounded to the
- Remainder by 2Read a whole number and print the remainder when it is divided by 2.
Strings
- How long is it?Read a line of text and print how many characters it has (spaces count).
- Make it loudRead a line and shout it: print it in capital letters followed by three exclamation
- WhisperRead a line and print it in small letters.
- First and last letterRead a word and print its first and its last character, separated by a space.
- Repeat a wordRead a word and a number n, and print the word n times without spaces.
- Spaces to underscoresRead a line and replace every space with an underscore, like in file names.
- Count the letter aRead a line and print how many times the small letter a appears in it.
- Title caseRead a line and print it with the first letter of every word in capitals.
- Trim the spacesRead a line that may have spaces at the start and the end.
- First three lettersRead a word and print its first three characters.
- BackwardsRead a word and print it backwards.
Formatting
- Receipt lineRead an item, its price and a quantity, and print a receipt line with the total
- PercentageRead a score and the maximum score, and print the score as a percentage with one
- Clock timeRead hours and minutes and print the time as HH:MM, with leading zeros.
- Date formatRead a day, a month and a year, and print the date as DD.MM.YYYY.
- Big moneyRead an amount of money and print it with a comma between thousands and exactly
- Score table rowRead a name and a score and print them as one row of a table: the name left-aligned
BeginnerDecisions and loops: if, for and while, lists and strings.
Conditions
- Even or oddRead a whole number and say whether it is even or odd.
- Positive, negative or zeroRead a number and say whether it is positive, negative or zero.
- The larger numberRead two different whole numbers and print the larger one, without using max().
- Largest of threeRead three whole numbers and print the largest, without using max().
- In orderRead two whole numbers and print them from the smaller to the larger, on one line.
- Grade from a scoreTurn a test score into a grade: 90 or more is A, 80 or more is B, 70 or more is C,
- Leap yearA year is a leap year if it divides by 4, except years that divide by 100, which are
- Ticket priceA cinema ticket costs 5 for children under 12, 7 for people aged 65 or more, and 10
- Secret passwordThe password is python123.
- Divisible?Read two whole numbers a and b (b is not 0).
- Can it be a triangle?Three lengths make a triangle when each one is smaller than the sum of the other
- Kind of triangleRead the three sides of a triangle and name its kind: equilateral (all sides equal),
- Which quadrant?Read a point (x, y) where neither coordinate is 0, and print its quadrant: 1 for
- Day of the weekRead a number from 1 to 7 and print the day: 1 is Monday, 7 is Sunday.
For loops
- Count to nRead n and print the numbers from 1 to n, one per line.
- CountdownRead n and count down from n to 1, one number per line, then print Liftoff!
- Sum from 1 to nRead n and print 1 + 2 + ... + n, using a loop.
- Times tableRead n and print its times table from 1 to 10.
- FactorialThe factorial of n is 1 * 2 * ... * n, and the factorial of 0 is 1.
- Even numbersRead n and print all even numbers from 2 to n on one line, separated by spaces.
- Powers of twoRead n and print the first n powers of two, starting with 1, on one line.
- Table of squaresRead n and print, for every number from 1 to n, the number and its square.
- Add them upRead how many numbers follow, then the numbers, and print their sum.
- Average of n numbersRead n and then n numbers; print their average with two decimals.
- Highest scoreRead n scores and print the highest one, without using max().
- Count the positivesRead n numbers and count how many of them are greater than zero.
- FizzBuzzPrint the numbers from 1 to n, but print Fizz instead of numbers divisible by 3,
- Staircase of starsRead n and print a staircase: row 1 has one star, row 2 has two, up to n stars.
While loops
- How many digits?Count the digits of a positive whole number using a while loop and // 10 (not len).
- Sum of the digitsAdd up the digits of a whole number of any length using a while loop.
- Reverse a numberRead a positive whole number and print its digits in reverse order, as a number
- Add until zeroKeep reading numbers and adding them up until you read 0.
- Guess the numberThe first line is a secret number.
- Collatz stepsStart with n.
- Saving upYou save the same amount every month.
- Money doublesMoney in a bank grows by a fixed percentage every year.
Strings
- Count the vowelsCount the vowels (a, e, i, o, u, small or capital) in a line.
- PalindromeA palindrome reads the same backwards, like level.
- Count the wordsCount the words in a line.
- Longest wordPrint the longest word in a line.
- AcronymMake an acronym from the first letter of every word, in capitals.
- Spell it outPrint the letters of a word separated by dashes.
- Remove the vowelsPrint a line without its vowels (a, e, i, o, u, small or capital).
- Digits in textCount the digits (0-9) in a line of text.
- How many times?Count how often a letter appears in a line, ignoring capital letters.
- Strong passwordA password is strong when it has at least 8 characters, at least one digit and at
- SpOnGeBoB casePrint a word with its letters alternating: the 1st, 3rd, 5th... in small letters and
Lists
- Sum of a listRead numbers from one line and print their sum.
- Smallest and largestRead numbers from one line and print the smallest and the largest.
- Reverse a listRead words on one line and print them in reverse order.
- Count even numbersRead numbers from one line and count how many are even.
- Above averagePrint the numbers that are greater than the average of all the numbers, in their
- Find a numberFind where a number first appears in a list.
- Shopping totalRead a shopping list and print the total price with two decimals.
- Second largestPrint the second largest different number in a list.
IntermediateFunctions, dictionaries, nested loops and working with text.
Functions
- Prime checkWrite a function is_prime(n) that returns True when n is a prime number (it has
- Greatest common divisorWrite gcd(a, b) with Euclid's method: while b is not 0, replace (a, b) with
- Least common multipleWrite lcm(a, b), the smallest number both a and b divide into.
- Primes up to nPrint all prime numbers up to and including n, on one line.
- Perfect numberA number is perfect if it equals the sum of its divisors smaller than itself, like
- Fibonacci numberThe Fibonacci numbers start 0, 1 and each next one is the sum of the previous two:
- Digital rootAdd up the digits of a number, then the digits of the result, and so on until one
- Temperature converterWrite two functions, c_to_f and f_to_c, and convert a temperature that comes with
Nested loops
- Multiplication gridPrint an n by n multiplication grid.
- PyramidPrint a pyramid of stars n rows high.
- Number trianglePrint n rows: row i holds the numbers 1 to i separated by spaces.
- Hollow squarePrint an n by n square of # with only the border filled; the inside is spaces.
- DiamondPrint a diamond of stars: a pyramid of n rows, then the same pyramid upside down
- CheckerboardPrint an n by n checkerboard of # and .
- Pairs that add upCount the pairs of positions (i < j) whose numbers add up to a target.
Lists
- Remove duplicatesRemove repeated words but keep the first appearance of each, in the original order.
- Rotate a listRotate a list k places to the right: the last k items move to the front.
- Merge two sorted listsMerge two lists that are each sorted into one sorted list, walking through both at
- Running totalPrint the running totals of a list: each position holds the sum of all numbers up
- MedianThe median is the middle value of the sorted numbers; with an even count it is the
- Most common numberPrint the number that appears most often.
- Longest rising runFind the length of the longest stretch of numbers next to each other where each is
- Zeros to the endMove every 0 to the end of the list, keeping the other numbers in their order.
- Rows of kPrint the items in rows of k; the last row may be shorter.
- Sort descendingSort numbers from the largest to the smallest.
Dictionaries
- Word frequencyCount how often each word appears (ignore capital letters).
- Letter chartCount the letters in a line (ignore capitals, spaces and punctuation) and draw a bar
- Phone bookRead a phone book, then answer questions about it.
- AnagramsTwo words are anagrams when they use exactly the same letters, like listen and
- Group by first letterGroup words by their first letter.
- Average per studentRead scores; a student can appear several times.
- Stock countA shop records deliveries (positive) and sales (negative).
- First unique letterFind the first character that appears only once in a word.
Sets
- Different wordsHow many different words are in a line?
- In both listsPrint the numbers that appear in both lists, sorted, each once.
- The missing numberThe numbers from 1 to n are given in some order, but one is missing.
- PangramA pangram uses every letter of the English alphabet at least once.
- In just one listPrint the numbers that are in exactly one of the two lists, sorted.
Sorting
Text processing
- Caesar cipherShift every letter forward in the alphabet by a number of places, wrapping from z
- Run-length encodingCompress a word by writing each run of the same letter as the letter and how many
- Run-length decodingUndo run-length encoding: each letter is followed by how many times it repeats (the
- camelCase to snake_caseConvert a camelCase name to snake_case: put an underscore before each capital letter
- Roman numeralsConvert a Roman numeral to a number.
- To binaryWrite a number in binary by repeatedly dividing by 2 and collecting the remainders.
- No repeated lettersAn isogram is a word with no letter repeated.
- Reverse each wordReverse the letters of every word but keep the words in their order.
- Capitalise sentencesMake the first letter of every sentence a capital.
- Simple email checkCheck an email address: exactly one @, something before it, and after it a dot with
AdvancedRecursion, sorting and searching, stacks, queues and classes.
Recursion
- Towers of HanoiMove n disks from peg A to peg C using peg B, one disk at a time, never putting a
- All binary stringsPrint every string of 0s and 1s of length n, in increasing order, using recursion.
- PermutationsPrint every different ordering of the letters of a word, in alphabetical order,
- Subsets with a sumCount the subsets (choices of positions) of the list whose numbers add up to the
- Flatten a nested listA list can contain numbers and other lists, nested to any depth.
- Paths in a gridIn a grid of r rows and c columns you start top-left and may only move right or
- Climbing stairsYou climb a staircase taking 1, 2 or 3 steps at a time.
- Fair splitCan the numbers be split into two groups with the same sum?
Sorting algorithms
- Bubble sort swapsSort the numbers with bubble sort (repeatedly swap neighbours that are in the wrong
- Selection sort, step by stepSelection sort: for each position from the left, find the smallest remaining number
- Insertion sort, step by stepInsertion sort: take each number from the second one on and move it left until it
- Counting inversionsAn inversion is a pair of positions i < j with a[i] > a[j].
- Sort by frequencySort the letters of a word by how often they appear, most frequent first; equally
- By length, then alphabetSort words by length, shortest first; words of the same length alphabetically
- Sort by digit sumSort positive numbers by the sum of their digits; numbers with the same digit sum by
2D lists
- Transpose a matrixSwap the rows and the columns of a matrix.
- Matrix multiplicationMultiply an n by m matrix A by an m by p matrix B.
- Rotate a pictureRotate a grid of characters 90 degrees clockwise.
- Spiral orderPrint the numbers of a matrix in spiral order: along the top row, down the right
- Row and column totalsPrint the matrix with the sum of each row added at the end of the row, and a last
- Magic squareA magic square has every row, every column and both diagonals adding up to the same
- Count the islandsA map shows land (#) and water (.).
- Who won?Look at a finished tic-tac-toe board and say who won: X, O, or draw if nobody has
- Minesweeper numbersReplace every empty square (.) of a minesweeper field with the number of mines (*)
Comprehensions
- Pythagorean triplesFind all triples a < b < c up to n with a*a + b*b == c*c, using a list
- Pascal's trianglePrint the first n rows of Pascal's triangle: each row starts and ends with 1, and
- Divisors tableFor every number from 1 to n, print the number, a colon, and its divisors.
- Word lengthsBuild a dictionary {word: length} with a dictionary comprehension (each word once,
Exceptions
Classes
- Bank accountWrite a class Account with deposit, withdraw and a balance.
- FractionsWrite a Fraction class that adds two fractions and keeps the result in lowest terms
- VectorsWrite a Vector class for 2D vectors with + (addition), a dot product method and a
- ShapesWrite a base class Shape with an area() method and subclasses Circle, Rectangle and
- Clock arithmeticWrite a Time class holding hours and minutes, with a method that adds minutes and
Searching
- Binary searchFind a number in a sorted list with binary search: look at the middle and keep
- First and last positionA sorted list may contain repeats.
- Integer square rootFind the largest whole number r with r * r <= n using binary search (no ** 0.5,
- How many in range?Answer many questions: how many numbers of the list lie between a and b (both
Stacks and queues
- Balanced bracketsCheck that every bracket (), [] and {} is closed by the right kind in the right
- Postfix calculatorEvaluate an expression in postfix notation (operators after their numbers), e.g.
- UndoA tiny editor: type <word> adds the word to the end of the text, undo cancels the
- Counting outn people stand in a circle, numbered 1 to n.
- Next greater numberFor every number, print the first number to its right that is greater, or -1 if
- Back and forwardSimulate a browser starting at home: visit <page> opens a page (and clears the
Techniques
- Two numbers to a targetFind the first pair of positions i < j whose numbers add up to the target: the
- Best k days in a rowFind the largest total of k numbers next to each other.
- Anagram groupsGroup the words that are anagrams of each other.
- Days between datesHow many days are there from the first date to the second?
ExpertAlgorithms: graphs, dynamic programming, backtracking and more.
Dynamic programming
- Longest increasing subsequenceFind the length of the longest strictly increasing subsequence (numbers in order,
- Edit distanceThe edit distance is the smallest number of single-letter insertions, deletions and
- KnapsackChoose items to put in a bag without going over its capacity, making the total value
- Fewest coinsPay an amount exactly with the fewest coins; every coin value can be used as often
- Ways to make changeIn how many ways can an amount be made from the coins (each value used any number of
- Longest common subsequenceFind the length of the longest sequence of characters that appears in both texts in
- Best stretchFind the largest sum of a non-empty run of neighbouring numbers (Kadane's algorithm
- Longest palindrome insideFind the longest part of a text (consecutive characters) that is a palindrome.
- Cheapest path downWalk from the top-left to the bottom-right of a grid of costs, moving only right or
- Word breakCan the text be split into words that are all in the dictionary (words may be used
Graphs
- Shortest way outFind the fewest steps from S to E in a maze; # is a wall, and you move up, down,
- Groups of friendsn people are numbered 1 to n, and m friendships are given.
- Shortest distancesRoads join n towns (two-way, with lengths).
- Order of coursesCourses 1 to n have prerequisites: "a b" means a must come before b.
- Two teamsPairs of players refuse to be in the same team.
- The extra cableCables are added one by one between computers.
- Cheapest networkConnect all n towns with cables as cheaply as possible (a minimum spanning tree).
- Knight's journeyOn an n by n chessboard, what is the smallest number of knight moves from one square
- Spreading mouldEach minute, mould (M) spreads to the fresh fruit (F) next to it (up, down, left,
- Word ladderChange the start word into the end word one letter at a time; every word along the
Backtracking
- N queensIn how many ways can n queens be placed on an n by n board so that no two attack
- Sudoku solverSolve a sudoku: fill the empty cells (0) so every row, column and 3x3 box contains
- Combination sumPrint every combination of the given numbers (each number may be used several
- All bracket patternsPrint every balanced arrangement of n pairs of round brackets, in dictionary order
- Choose k of nPrint every way to choose k different numbers from 1 to n, each in ascending order,
- Word searchCan the word be traced in the grid by moving between neighbouring letters (up, down,
Number theory
- Counting primes fastCount the prime numbers up to n, for n as large as 2,000,000.
- Huge powersCompute a to the power b, modulo m, where b can have 18 digits.
- Prime factorsWrite a number as a product of primes, from smallest to largest, like
- Modular inverseFind x between 0 and m - 1 with a * x mod m = 1, using the extended Euclidean
- Euler's totientCount how many numbers from 1 to n share no common divisor with n except 1.
- Combinations modulo a primeCompute C(n, k), the number of ways to choose k items out of n, modulo 1000000007,
- Any base to any baseConvert a number between bases 2 and 36.
Greedy algorithms
- Most meetingsOne room, many meetings with start and end times.
- Rooms neededGiven meetings with start and end times, how many rooms are needed so that none
- Fewest jumpsEach number says how far you may jump forward from that position.
- Fractional knapsackItems can be cut, so you may take part of one.
- Joining ropesJoining two ropes costs the sum of their lengths.
String algorithms
- Find every matchPrint every position (from 0) where the pattern occurs in the text, overlapping
- Common beginningPrint the longest beginning that all words share, or none if they share nothing.
- Repeating patternFind the shortest piece that, repeated a whole number of times, makes the text (for
- Longest stretch without repeatsFind the length of the longest run of consecutive characters with no character
- Different piecesHow many different non-empty substrings (runs of consecutive characters) does a text
Parsing
Simulation
Data structures
The topics
Each with the idea in a minute, an example, and the mistake to watch for.
- Printing4
- Input and output9
- Arithmetic22
- Strings22
- Formatting6
- Conditions14
- For loops14
- While loops8
- Lists18
- Functions8
- Nested loops7
- Dictionaries8
- Sets5
- Sorting4
- Text processing10
- Recursion8
- Sorting algorithms7
- 2D lists9
- Comprehensions4
- Exceptions4
- Classes5
- Searching4
- Stacks and queues6
- Techniques4
- Dynamic programming10
- Graphs10
- Backtracking6
- Number theory7
- Greedy algorithms5
- String algorithms5
- Parsing3
- Simulation3
- Data structures3
- Geometry2
Questions
- Do I need an account?
- No. Open an exercise and start typing. Your code and the exercises you solve are kept in this browser, on this device, until you clear its data.
- Which Python is it?
- Real Python 3.14, running in your browser (Pyodide), with its standard library. Nothing to install, and your code never leaves your computer to run.
- How is my code checked?
- Check runs your program on each example and on hidden tests, then compares what it printed with the answer. A test that fails says why, in plain English, with what was expected beside what your program printed.
- Why are some tests hidden?
- So a program has to solve the problem, not just print the examples' answers. A hidden test that fails shows you the input it was given, so you can work out what your program missed.
- Can I see a solution?
- Once your code passes every test, you can compare it with ours. Not before: tutors set these exercises as homework. Stuck? Each exercise has the idea behind its topic, with an example.
- Does input() work?
- Yes. Press Run and your program asks in the output, as it would in a terminal: type the answer and press Enter. Check gives your program each test's input by itself.
- Is it for GCSE and A level?
- Novice to Intermediate cover what GCSE Computer Science asks you to program: input and output, decisions, loops, strings, lists, functions, searching and sorting. Advanced and Expert go on to A level and beyond: recursion, classes, stacks and queues, graphs.