Python challenges for GCSE Computer Science

118 Python programming challenges for GCSE Computer Science, in the order the course teaches them. Each one opens in the simulator with a starting program, and it is marked the moment you press Run: the robot either does the job or you are told what is missing.

118 challengesfree, runs in your browser

Other levels: GCSE · A level · Robot club · University

F1. Programming basics

  1. Your first program Print three lines. One of them must be exactly: I am a BugBot Lesson F1.1
  2. Say hello Three lines, each from one print: the greeting, the numbers 1 2 3 separated by commas in the print, and the word BugBot three times. Lesson F1.2
  3. Lights and numbers Set the LED first, then print the two sensor readings on their own lines, worded as the task shows. Nothing here needs the robot to move. Lesson F1.3
  4. Three notes Play the three notes one after another, each for the same short time. Nothing here needs the robot to move. Lesson F1.3
  5. Fix three errors One syntax error, one runtime error, one logic error. Fix the first error you are shown, run again, and watch where the robot goes. Lesson F1.4
  6. A tidy drive LED on, drive forward for a second, stop, LED off, print 'done'. Put a comment above each part saying what it does. Lesson F1.5
  7. Speed report Put 70 in a variable called speed. Print `speed: 70` and `half: 35` using the variable, then drive 20 cm at that speed. Lesson F1.6
  8. Three legs Store the three leg lengths in variables, drive them (forward, right, forward), and print their total. Lesson F1.6
  9. Greet by name Ask for the name and keep it in a variable, then use that variable in what you print. Change the LED after the greeting. Lesson F1.7
  10. Drive what you type What input() gives you is always text, so turn the answer into a number before you drive with it. Lesson F1.8
  11. Robot maths Use the same pair of numbers with each of the four operators, and print a labelled line for each. Remember which one throws the remainder away and which one keeps it. Lesson F1.9
  12. A third of the way Read the distance into a variable first, then drive a fraction of that variable. Reading the sensor twice can give you two different answers. Lesson F1.9
  13. Ask and drive Ask for both answers and convert each to the kind of number it should be: a side can have a decimal, a note cannot. Drive the four sides in order, sounding the note… Lesson F1.10

F2. Decisions and loops

  1. Fix the indentation Fix the indentation only. The two led and print lines belong inside the if; 'after the block' belongs outside it. Lesson F2.1
  2. Near or far Drive 20 cm. Then use two ifs: if the wall is under 40 cm away print 'near' and make the LED red; if it is 40 or more, print 'far' and make it green. Lesson F2.2
  3. Traffic light Drive first, then read the distance once into a variable and test it. Write all three branches, even though only one of them can run today. Lesson F2.3
  4. Safe to go? Read the distance, then choose between two paths with if and else. Only one of them drives. Lesson F2.3
  5. Command mode Compare the command word against each option in turn, and give the case that matches nothing something sensible to do. Lesson F2.4
  6. Count the corners One trip round a square is the same two steps repeated four times, so put them in a loop and use the loop's counter in what you print. Lesson F2.5
  7. Play a scale Use the loop counter to work out each note, so the frequency goes up by the same step every time round. Lesson F2.5
  8. Creep to the wall Keep going while there is still room: check the distance at the top of the loop and move a short way each time round, so you can stop as soon as it is close enough. Lesson F2.6
  9. Times grid One loop for the rows, and another inside it for the columns. Print without starting a new line inside the inner loop, then start one when each row finishes. Lesson F2.7
  10. Most room Keep two variables outside the loop: the best distance so far, and the direction it was found in. Update them only when a reading beats the best, then turn to that… Lesson F2.7
  11. Parking sensor Each time round the loop: move a little, read the gap, and choose the pause between beeps from that gap. Count the beeps as you go, and do the stopping, the long tone… Lesson F2.8

F3. Strings, lists and records

  1. Status report Drive first, then gather the readings and print them in one line, in the order and wording the task shows. Lesson F3.1
  2. Name tag There is a string method for upper case, square brackets for reaching one character (and a negative position counts from the end), and a built-in for counting the… Lesson F3.1
  3. Shift the letters Turn each letter into its code number, move it along by one, and wrap back to the start of the alphabet when it runs past Z. Build the answer up one letter at a time. Lesson F3.2
  4. A changing tune A list can be changed in place: replace one item by its position, and add another on the end. Then loop over the list to play it. Lesson F3.3
  5. Sensor log Take a reading, move a short way, and repeat, adding each reading to a list as you go. The smallest, largest and average all come from that list afterwards. Lesson F3.4
  6. Nearest column The grid is rows of readings. Look along the row you care about, keeping both the smallest reading and the position it was found at. Lesson F3.5
  7. Reading records Store each reading as a record with the direction it was taken in, and add it to a list before turning. Afterwards, loop over the list to print, and keep the record… Lesson F3.6
  8. Dice drive Roll inside the loop, print the roll, then drive a distance worked out from it. Keep a running total as you go. Lesson F3.7
  9. Survey the room Build the list of records first, then answer each question with its own pass over that list. Turn to the direction stored in the record you chose. Lesson F3.8

F4. Functions and structured code

  1. Signal at the corners Write the signal once as a function, then call it at each corner from a loop that drives and turns. Lesson F4.1
  2. Any polygon The function needs the number of sides and the length. Work the turn out from the number of sides: a full turn shared between them. Then call it twice with different… Lesson F4.2
  3. Room ahead Write a function that reads the sensor and takes the margin off, then drive the distance it gives back. Print what is left afterwards. Lesson F4.2
  4. Count the beeps A function cannot change a variable made outside it unless you say so. Either pass the count in and hand the new one back, or declare the outside variable global at the… Lesson F4.3
  5. Three stops Work out where you are, then how far you still have to go in each direction, and drive that difference. Sideways and forwards are separate moves. Do the signal at each… Lesson F4.4
  6. Use your module Put the driving function in the other file, with the size as its parameter. The task program imports that file and calls the function twice with different sizes. Lesson F4.5
  7. Patrol Write one function for a single step that drives a little and reports where the wall is. Call it from a loop that keeps going while the wall is still far enough away,… Lesson F4.6
  8. Patrol and return The patrol function counts its steps and hands the count back. The going-home function takes that count and reverses the same number of steps. The main program joins… Lesson F4.6

F5. Algorithms

  1. Any shape from an answer Ask how many sides and make it a whole number. The turn at each corner is a full turn shared between the sides. Then repeat drive-and-turn once per side. Lesson F5.1
  2. The password guard Ask once before the loop, then keep asking while the answer is still wrong, warning each time. Only after the loop does the robot unlock and drive. Lesson F5.2
  3. Steps from pseudocode Follow the pseudocode line by line: count the steps in a loop that runs while the wall is far enough away. At the end, test whether the count divides by two exactly to… Lesson F5.3
  4. Trace and fix Trace what the total does each time round. One line sets it back to its starting value when it should not. Move that line so it runs once, and print the counter and the… Lesson F5.4
  5. Find the marker Record the id straight ahead (cx near 160) at each of 8 turns. Then loop through the list counting checks until you find the target; its index times 45 is the direction. Lesson F5.5
  6. Binary search the markers Keep a low and a high edge and look at the middle of what is left. Compare the middle value with the target, then move whichever edge rules out half the list. Count and… Lesson F5.6
  7. Sort the tune Go through the list comparing each pair of neighbours and swapping them when they are the wrong way round. Repeat until a whole pass makes no swaps. Lesson F5.7
  8. Sort the survey Take each item in turn as the one to place, and shift the sorted items on its left along until there is a gap for it. Print the list after each item is placed. Lesson F5.8
  9. Merge two tunes Walk both lists at once with a position in each. Take the smaller of the two items in front of you and move that position on. When one list runs out, the rest of the… Lesson F5.9
  10. Sort the readings Survey into a list of records first, then sort those records by their distance. The middle of an even-length list is the average of the two middle values, and the last… Lesson F5.10

F6. Robust programs

  1. A validated drive Keep asking until the answer passes every check, and test the checks in order: is there anything there, is it a number, is it in range. Each failure has its own message. Lesson F6.1
  2. Operator login Give the loop a fixed number of attempts. Each time, check the name exists and that the stored password matches it before letting them in, and stop asking once they are. Lesson F6.2
  3. Fix it with tests The boundary is wrong: the lowest and highest allowed values should pass. Then add tests of your own, each a pair of an input and the answer you expect, including one… Lesson F6.3
  4. Fix the square Three bugs: the loop runs three times, side is reset to 20 inside the loop, and the turn goes the wrong way. Lesson F6.4
  5. Robot assembly Keep the register in a variable. Each instruction reads the word and acts on it. The jump instruction is the only one that changes where the program counter goes next,… Lesson F6.5
  6. Use the diagnostics There are three faults: one is a missing punctuation mark that ends a header line, one is a name spelled differently from where it was made, and one sets a counter… Lesson F6.6
  7. The fail-safe controller Three parts: a login that allows a limited number of tries, a parser that splits a command and refuses anything it does not recognise, and a main loop that acts on what… Lesson F6.7

F7. Files and databases

  1. Log the run Time the run by taking a clock reading before and after. Open the file so that writing adds to the end rather than replacing it, and remember the header line when you… Lesson F7.1
  2. Runs by robot Build a dictionary from robot_id to name from SELECT * FROM robots, then loop over SELECT * FROM runs and look each robot_id up. Lesson F7.2
  3. The longest square runs One SELECT does the whole job: choose the columns you need, filter to the task and the distance in the WHERE, and order by the distance so the longest is first. The… Lesson F7.3
  4. Log and correct Four statements in order: add the new run, change the one with the wrong task, remove the one that should not be there, then a SELECT that joins the two tables to list… Lesson F7.4
  5. The logbook Read the file to find the next run number; drive and time; append; CREATE TABLE and INSERT every line; SELECT COUNT(*); SELECT run, cm / seconds ... ORDER BY cm /… Lesson F7.5

F8. Data representation

  1. Frame sizes Multiply the pixels by the bytes each one takes. Bits are eight times the bytes, and the larger unit divides by a thousand. Lesson F8.1
  2. Play in binary Work down the place values from the largest. If the number is at least the place value, the bit is a 1 and you take that value off; otherwise it is a 0. Then sound a… Lesson F8.2
  3. Mix a colour Each byte becomes two hex digits: the first is how many sixteens, the second is what is left over. Look each one up in the digit string, join the six digits behind a… Lesson F8.3
  4. An 8-bit adder Work from the rightmost column to the left, adding the two bits and the carry from the column before. The column's answer is what is left after taking out any twos, and… Lesson F8.4
  5. Signed readings For a negative n: write -n in 8-bit binary, flip every bit, and add 1. Lesson F8.5
  6. Message sizes Count the characters for the first line, multiply by the bits per character for the second, and ask the encoded form for its length for the third. Then take each of the… Lesson F8.6
  7. Camera pixels For each row, for r, g, b in row: add '#' if (r + g + b) / 3 < 128 else '.'. Size in bits is width * height * depth. Lesson F8.7
  8. Find the note Build the samples with a sine wave, then find the frequency by counting how many times the wave crosses zero on the way up. Divide those crossings by how long the… Lesson F8.8
  9. Compress a row Walk the row counting how long the current run is. When the character changes, write the count and that character, then start counting again. To decode, gather the… Lesson F8.9
  10. Send a picture Turn the camera frame into rows of two characters, compress each row, and join the rows with a separator the receiver can split on. Check the message fits the radio… Lesson F8.10

F9. Logic and computer systems

  1. Truth tables Two nested loops give you every combination of the two inputs. Work Q out from your gate functions rather than writing the answers down. Lesson F9.1
  2. A half adder XOR is true when the inputs differ, which is the same as saying at least one is true but not both: build it from OR, AND and NOT. The carry is the plain AND of the… Lesson F9.2
  3. A stored program Add one more branch to the processor loop for subtracting, and change the program in memory so it subtracts instead of adds. After the loop ends, read the answer back… Lesson F9.3
  4. Trace the cycle Each time round: copy the program counter into the address register, fetch what is there, report it, then move the counter on. Decode and carry out the instruction… Lesson F9.4
  5. The cache model Call the model once for each size in the range, printing as you go. Track the best size by keeping it only when a size beats the best hits so far, so the smallest of… Lesson F9.5
  6. Out of RAM Keep a list of what is in RAM, oldest first, and a list of what has been moved out. Before loading an app, keep moving the oldest out while it still does not fit,… Lesson F9.6
  7. The storage chooser Look at every device and skip the ones that are too small or that have moving parts when the job forbids them. Of those left, keep the one whose price, its capacity… Lesson F9.7
  8. Sense, decide, act Start the robot moving, then loop: read the gap, decide, act. While there is room, keep the LED green. When the gap is too small, stop, turn the LED red, sound the tone… Lesson F9.8
  9. A round-robin scheduler Take the job at the front of the queue and run it for the slice, or for what it has left if that is less. Add the time on, then either put it back at the end of the… Lesson F9.9

F10. Networks

  1. Roll call Send the question, then keep checking for messages for a second or so. Each reply carries a name after a label: split it off, print it and collect it. The count is how… Lesson F10.1
  2. A learning switch For each frame, first note which port its sender came in on. Then look the destination up in the table: send it to that port if you know it, and to every port if you do… Lesson F10.2
  3. Ping the server For each ping, take a clock reading, send, then wait in small steps until a reply arrives, and take the clock reading again. The difference is the round trip. Collect… Lesson F10.3
  4. Route around a failure Breadth-first search: keep a queue of robots to visit and a record of which robot you reached each one from. When it is done, follow that record back from the end to… Lesson F10.4
  5. Packets Slice the message into equal pieces and label each one with its number and how many there are in total. To reassemble, sort by the number at the front of each packet,… Lesson F10.5
  6. Look it up Ask the DNS robot first and pull the address out of its reply. Use that address to ask the Scout where it is, take the two numbers out of its answer, and drive to a… Lesson F10.6
  7. A tiny web client Send the request and wait for the reply. The reply starts with the status number, so split it off the front and turn it into a number; what is left is the body. Choose… Lesson F10.7
  8. Wrap and unwrap Going down, each layer puts its header in front of what it was given, and you report the result at each step. Coming back up, take one header off the front at a time. Lesson F10.8
  9. Deliver the report For each packet, keep sending it until the reply is the acknowledgement for that packet's number. Count every send, including the repeats, and only move to the next… Lesson F10.9

F11. Cyber security

  1. Rank the risks Give each risk a score of likelihood times impact, then sort the list by that score, highest first. The biggest risk is whatever ends up at the front. Lesson F11.1
  2. A malware scanner For each file, collect every signature that appears anywhere in its contents. A file with any matches is infected and you list them; a file with none is clean. Count… Lesson F11.2
  3. A phishing filter Write the scoring function so it counts how many warning signs appear in the message, ignoring capitals. Then print each subject with its score, marking the ones that… Lesson F11.3
  4. Flood detector Count the requests per address into a dictionary, then sort those counts from the largest down. Mark and collect any address that reaches the threshold, and list the… Lesson F11.4
  5. A password checker Score one point for each rule the password meets: long enough, a lower-case letter, an upper-case letter, a digit, and a character that is neither a letter nor a digit.… Lesson F11.5
  6. Send a secret Encrypt the message with the shared key, report what you are sending, and send that rather than the plain words. Decrypt each reply by shifting the other way. Lesson F11.6
  7. A firewall For each packet, walk the rules in order and stop at the first one that matches, taking its decision. A rule matches when its address and port either match the packet… Lesson F11.7
  8. An access checker Check the role exists before anything else, and say so if it does not. Otherwise look the role up and see whether the action is in the list of things it may do. Count… Lesson F11.8
  9. Secure the robot Send the password and wait for the reply, which is encrypted. Decrypt it with the key shifting the other way, split the command into its word and its number, and drive… Lesson F11.9

F12. Technology and society

  1. Weigh up the robots Print each effect with its sign, adding the scores into a running total. Then choose between three verdicts by testing whether the total is above, below or exactly zero. Lesson F12.1
  2. Anonymise the log Number the students as you walk the list, printing only the number and the distance. Keep a running total of the distances, and the number of records is the length of… Lesson F12.2
  3. Which law? In which_law, lower the action then check the words in order: password/hack/malware, personal/customer details, copy/pirate. Count the ones that match no law. Lesson F12.3
  4. May I use it? If the licence is not in the table, say so. Otherwise look up what that licence allows and check it against the use asked for, remembering that using it unchanged is… Lesson F12.4
  5. The classroom's footprint Energy for one device is its watts times its hours times the days times how many there are, converted from watt-hours to kilowatt-hours. Add them up, then turn the… Lesson F12.5
  6. Check the contrast The ratio is the lighter luminance plus a small offset, divided by the darker one plus the same offset. Compare it with the threshold to decide pass or fail, count the… Lesson F12.6
  7. Audit the training set Count each label into a dictionary, then sort from the most common down. A label's share is its count out of the total; mark the ones below the threshold and collect… Lesson F12.7
  8. How automatable? A job's score is the total of each task's share times how automatable that task is. Sort the jobs by that score, mark the ones at or above the threshold, and find the… Lesson F12.8
  9. Write the report Read the file and drop the header line. Give each new name the next number and keep its running totals, so the report can talk about students without naming them. Turn… Lesson F12.9

F13. Exam preparation

  1. Your timing plan Minutes a mark is the paper's minutes divided by its marks. A question's time is that rate times its marks, rounded. Keep running totals of the marks and the minutes as… Lesson F13.1
  2. Print the trace Print the row at the top of each pass, before changing anything, with the result of the check. The row that ends the loop is printed too, with the check false, and then… Lesson F13.2
  3. Pseudocode into Python The answer from input() is text, so make it a whole number first. FOR 1 TO steps includes the last one, so the range has to reach one past it. Add the 10 on before you… Lesson F13.3
  4. An exam-style program Keep a running total of how far you have driven and loop while it is less than the target. Each step is the step size, or whatever is left if that is smaller. Count the… Lesson F13.4
  5. The conversion drill For the binary, work down the place values from 128, taking each one that fits. For the hex, the first digit is how many sixteens and the second is what is left, looked… Lesson F13.5
  6. Mark a long answer Count how many phrases from each list appear in the lowered answer, with the conclusion worth two. Then decide the note: no phrase from one of the two sides, no… Lesson F13.6
  7. Repair the program Three faults: how many times the loop runs, a variable that is set back to zero every time round when it should be set once before the loop, and the colour at the end. Lesson F13.7
  8. Build a revision plan Sessions are six take the confidence. Sort the topics by confidence, least first, and print them. Then walk the days, taking the next topic that still has sessions left… Lesson F13.8
  9. The revision robot For each record, print the topic and question, read the answer, and compare both sides lowered and stripped. Count the score, and count the wrong answers per topic in a… Lesson F13.9

Questions

Are these Python challenges free?

Yes. Every challenge runs in the browser with nothing to install.

How are the challenges checked?

The simulator runs your program and checks what the robot did and what it printed against the challenge's goals. If something is missing it says what, so you can fix it and run it again.

Are there solutions?

There is no answer to copy. Each challenge has a Stuck? button that tells you what to work out next, and the lesson it comes from teaches everything the challenge needs.

What order should I do them in?

Top to bottom. They follow the course, so each section only needs what the sections before it taught.