Fast, accurate typing makes coding much smoother, so this typing game uses real lines of Python instead of random sentences. Each round shows a line of code; type it exactly and the game works out your words per minute and accuracy.
Building it teaches you how to measure time in Python and how to compare two strings character by character.
Play Code Typing Test
Press ▶ Play to start the game. When it asks you something, type your answer and press Enter.
View and edit the code (44 lines)
How to play
- Type the line of code shown, exactly, then press Enter.
- You get three lines per game.
- Your speed (WPM) and accuracy are shown after each line, with an average at the end.
The complete Code Typing Test code
Here is the whole program (44 lines). It only uses Python's standard library, so it runs anywhere Python 3 is installed.
import random
import time
LINES = [
'print("Hello, world!")',
"for i in range(10):",
"total = sum(scores) / len(scores)",
"if guess == secret:",
"names = [n.upper() for n in names]",
"while lives > 0:",
"def greet(name):",
"word = random.choice(WORDS)",
]
def accuracy(typed, target):
right = sum(1 for a, b in zip(typed, target) if a == b)
return round(100 * right / max(len(target), len(typed), 1))
def wpm(chars, seconds):
return round((chars / 5) / (seconds / 60)) if seconds > 0 else 0
print("CODE TYPING TEST - type each line exactly")
speeds, scores = [], []
for target in random.sample(LINES, 3):
print("\n " + target)
input("Press Enter when you're ready...")
start = time.time()
typed = input(">> ")
seconds = time.time() - start
acc = accuracy(typed, target)
speed = wpm(len(typed), seconds)
speeds.append(speed)
scores.append(acc)
print(f"{seconds:.1f}s | {speed} WPM | {acc}% accurate")
if acc < 100:
for i, (a, b) in enumerate(zip(typed, target)):
if a != b:
print(f"First mistake at character {i + 1}: you typed {a!r}, expected {b!r}")
break
print(f"\nAverage: {sum(speeds) // len(speeds)} WPM at {sum(scores) // len(scores)}% accuracy")How the Code Typing Test game works, step by step
01Pick three lines at random
random.sample(LINES, 3) returns three different lines, so you never get the same line twice in one game.
for target in random.sample(LINES, 3):02Start the clock when the player is ready
The first input() just waits for Enter. The timer starts right after, and stops when the line is submitted.
input("Press Enter when you're ready...")
start = time.time()
typed = input(">> ")
seconds = time.time() - start03Words per minute
Typing tests count every 5 characters as one word. Divide by the minutes taken: (chars / 5) / (seconds / 60).
return round((chars / 5) / (seconds / 60))04Accuracy, character by character
zip() pairs up typed and expected characters. Count the matches and divide by the longer length, so missing or extra characters lower the score.
right = sum(1 for a, b in zip(typed, target) if a == b)05Point out the first mistake
enumerate() gives the position, and !r in the f-string shows the character in quotes, so a missing space is easy to spot.
print(f"... you typed {a!r}, expected {b!r}")What you'll learn
- Measuring time with
time.time() random.sample()- Comparing strings with
zip() - Division,
round()andmax() !rin f-strings
Python concepts in this game:
Code Typing Test coding challenges
Write the key parts of the game yourself. Press Run to try your code and Check to test it. Each challenge you pass earns a star (saved in this browser).
Words per minute
Write wpm(chars, seconds): every 5 characters count as one word. Return the words per minute rounded to a whole number, or 0 if seconds is 0.
Hint
words = chars / 5, minutes = seconds / 60, answer = round(words / minutes).
Show a solution
def wpm(chars, seconds):
if seconds == 0:
return 0
words = chars / 5
minutes = seconds / 60
return round(words / minutes)
print(wpm(50, 30))Accuracy
Write accuracy(typed, target): count positions where the characters match, divide by the longer of the two lengths, and return a whole-number percentage. Two empty strings are 100.
Hint
Use max(len(typed), len(target)) as the bottom of the fraction so extra and missing characters both count against you.
Show a solution
def accuracy(typed, target):
longest = max(len(typed), len(target))
if longest == 0:
return 100
right = 0
for a, b in zip(typed, target):
if a == b:
right += 1
return round(100 * right / longest)
print(accuracy("prnt(x)", "print(x)"))Find the first mistake
Write first_mistake(typed, target): return the position (starting at 1) of the first character that differs. If one string is just shorter, the position after it. If they're equal, return 0.
Hint
Loop with enumerate(zip(typed, target)). After the loop, handle different lengths.
Show a solution
def first_mistake(typed, target):
for i, (a, b) in enumerate(zip(typed, target)):
if a != b:
return i + 1
if len(typed) != len(target):
return min(len(typed), len(target)) + 1
return 0
print(first_mistake("for i in rnge(3):", "for i in range(3):"))Make it your own
Once your challenges pass, try one of these upgrades:
- Add longer multi-line code snippets.
- Keep a personal best WPM in a file.
- Only count correct characters towards your speed.
- Add a countdown 3, 2, 1 with time.sleep().
Frequently asked questions
How do you measure typing speed in Python?
Record time.time() before the player types and after they press Enter. Words per minute is (characters / 5) divided by (seconds / 60).
How do I compare what was typed with the target text?
zip() the two strings together and count the positions where the characters match. Divide by the longer length for an accuracy percentage.
Why practise typing code instead of normal text?
Code uses brackets, colons, quotes and symbols that ordinary typing tests skip. Practising them makes writing Python faster and cuts down on typos.