CODING
ADVENTURE
0 / 12 completed

CASE 06 / CHAPTER 5

Find the prime locker

Functions, loops and remainders

IN THE STORY

The hackathon clue names four training lockers. Only the prime-numbered locker contains the next note.

The idea

A function is a named set of instructions. def defines it; calling it runs it with a supplied value. return sends a result back. A prime is a whole number greater than one with exactly two positive divisors: one and itself. % gives the remainder after division. range(2, number) produces values from two up to, but not including, number. Checking each smaller divisor makes this version straightforward to trace.

Your mission

Complete the divisibility test. The function must reject any number that divides evenly by a smaller candidate divisor.

Replace ____ with the missing expression, then choose Run code. Match the expected output before trying your own changes.

Before you run it

Why does the function reject 1 before starting its loop?

A little help?

Hint 1: a nudge

A remainder of zero means the division was exact.

Hint 2: a closer look

Compare number % divisor with zero.

How the answer works

Only 29 is prime. A list stores the locker numbers in order. The function answers a yes/no question for each one. A tiny prime checker is a maths exercise, not a tool for breaking encryption.

This replaces the code in the editor. Save your version first if you want to keep it.

Make it yours

Test 0, 1, 2 and 49. Explain why 2 succeeds even though its divisor loop has no iterations.

prime_locker.pyPYTHON 3

Four spaces indent a block. Ctrl / ⌘ + Enter runs your code. Tab moves to the next control.

OUTPUTPython loads when you run
Your program's output will appear here.

Take a guess. Try a line. See what happens.

Expected output

Try locker 29

Code runs on your device. The first run downloads the Python engine (about 10 MB); later runs use the browser cache. Stop ends a run without losing your code.