Project 7 of 13, for Caitlin
Number Guessing Game
The computer picks a number from 1 to 100. You guess, and it counts every try.
No account needed. Your work is kept in this browser until you sign up.
The brief
- CaitlinI want a game, a proper one, where the computer picks a number and you guess it.
- CaitlinIt tells you too high, too low or got it, and it counts your guesses.
- CaitlinFewest guesses is basically a high score, which makes it a proper game.
- PaulIt'll need a loop that doesn't know when it's going to end, and that's new.
The computer picks a whole number from 1 to 100. Then it asks Guess? until the game is over.
- Too low or too high: say so.
- Right: print
Got it in 4.(however many guesses it took) and stop. qinstead of a number: printIt was 37.(the real number) and stop. Everyone gives up sometimes.- A guess below 1 or above 100 gets
Between 1 and 100.and doesn't count as a guess.
Guess? 50 Too high. Guess? 25 Too low. Guess? 37 Got it in 3.
What you learn
The lesson, step by step
Repeat while it's true
A
whileloop repeats the indented lines under it for as long as its test, the comparison afterwhile, isTrue.You need one when you can't know the number of passes in advance. A
forloop counts its passes before it starts. A guessing game can't: it goes on until someone gets the number.Python asks the test at the top, before every pass. When the answer is
False, it jumps to the first line after the loop. The example prints3,2,1, thenGo.The usual slip is to read
whilelikeif. Anifruns its lines once. Awhilegoes back to the top after every pass and asks again.Change line 1 to
count = 5and run it.While it lasts
Caitlin's games all have lives. This loop keeps going while there are some left.
Counting as you go
A running total is a variable that starts at 0 before a loop and has something added to it on every pass:
total = total + points.A counter is the same thing, adding 1 each time:
rounds = rounds + 1. Caitlin's game will count guesses this way.The example adds 10, 20 and 30. It prints the total after each round, 10, 30 and 60, and then
Final total: 60.The usual slip is to put
total = 0inside the loop. Then it runs on every pass, the total goes back to 0 each time, and only the last amount survives. Set it once, above the loop.Back to zero
This is meant to count five tries. Read the indents carefully.
A word that means stop
A sentinel is a value that means stop, not another answer. Here it's the word
stop.!=means is not equal to, so the loop runs while the word is anything else.It lets a loop take as many answers as someone has, then end when they say so.
The program asks once before the loop, so the test has a word to look at. It asks again on the last line inside the loop, ready for the next pass. Type
hello,tea, thenstop, and it printsYou said hello,You said tea, thenStopped.People often expect
stopto be printed too. It never is. It's tested at the top, and the loop ends before doing anything with it.Until the round is done
Caitlin does the Studio's tea round. Her stop word is
done: the loop makes drinks until she types it.A loop that never ends
An infinite loop is a loop whose test never becomes
False, so it goes round for ever and the program hangs. Everyone writes one sooner or later, so it's worth knowing the fix.The example prints
Bongthree times, thenQuiet. Line 4 is what stops it. Delete line 4 and run it:chimesstays at 3,chimes > 0staysTrue, and the bongs carry on until the editor gives up after 2000 lines. A loop that prints nothing just hangs, and you press Stop.The usual slip is to expect the variable in the test to change by itself. It never does. A line inside the loop has to change it on every pass, like line 4 here.
Round and round
Neil's kart does three laps, then comes in for a pit stop. Or it's meant to.
Borrowing tools
A module is a file of extra tools that comes with Python.
importloads one, so your program can use it.Python starts small, and keeps tools like square roots and random numbers in modules until you ask for them.
mathhas the maths.randomhas the random numbers Caitlin's game needs.Put
import mathat the top of the file. Then write the module's name, a dot and the tool:math.sqrt(49)means the square root tool insidemath. The example prints7.0.The usual slip is to leave out the import. Then Python has never heard of
math, and the line that uses it stops with a NameError. Delete line 1 and run it to see.A number nobody chose
random.randint(1, 100)uses therandinttool in therandommodule to pick a number for Caitlin's game. Look at what's at the top of this file.Picking at random
random.randint(low, high)picks a whole number fromlowtohigh, and either end can come up.It's how a program gets a number nobody chose: a dice roll, a raffle ticket, a secret for a guessing game.
The example picks a seat from 1 to 5 for the tea round and prints it twice. Run it a few times. The seat changes from run to run, but within one run both lines show the same seat.
That's the thing people get wrong.
randintpicks once, each time it's called, on line 3. The variableseatkeeps that number. Readingseatagain doesn't pick again.Unlike
range(1, 5), which stops before 5,randint(1, 5)can give 5.Pick a number
This is how Caitlin's game will pick its secret number.
Stop now
breakleaves a loop straight away.while True:is a loop whose test is alwaysTrue, so it never stops by itself. That suits a game that can't know how many guesses it needs but knows exactly when to stop. Inside it, anifdecides when, andbreakends the loop.Type
tea, thenopen. It printsWrong.fortea. Foropen,breakskips the rest of that pass, soWrong.doesn't print, and the program carries on after the loop withCome in.The usual slip is to think
breakends the whole program. It only leaves the loop. Everything after the loop still runs.Leaving early
Each pass adds 1 to
guess. Follow it pass by pass untilguessis 3.Skip this one
continueskips the rest of this pass and goes straight back to the top of the loop for the next one.It's for the ones that don't count. Caitlin's game will use it for a guess outside 1 to 100: say so, then skip the counting.
Seat 3 has brought their own tea. When
seatis 3,continueskips theprint, and the loop moves on to seat 4. The example prints tea for seats 1, 2, 4 and 5, thenRound done.The usual slip comes from English, where continue means carry on. In Python it means skip ahead. And it's not
break: the loop keeps going.Not that one
This loop counts up to 4 and skips one number on the way.
How Paul would do it
- PaulThe server cupboard's got a padlock and I keep forgetting the code. It's the same shape as Caitlin's game.
Paul's padlock program has the same shape as Caitlin's game: a secret, a counter, a quit word, a code that doesn't count, and a win.
The labels beside the code are the steps he took. Line 13's
continueskips a code that isn't four digits, so it never reaches line 14 and never counts as a try. Eachbreakends the loop: one for giving up, one for opening the lock.Your game takes the same steps, in the same order.
Fix Yahya's version
- YahyaThis is my data logger. There were two input lines exactly the same, so I took one out.
- YahyaFewer lines should mean a faster program, but it's been thinking ever since I typed 14. Can you look?
Yahya's logger takes readings from the weather station outside the Archive until he types
stop, then gives the average.Run it and type
14. Nothing more happens, because his loop never ends and prints nothing while it goes round. Press Stop.Then fix it so this works:
Reading? 14 Reading? 12 Reading? stop Readings: 2 Average: 13.0 degrees:.1fshows one decimal place, as:.2fshows two.On the board
- CaitlinAnything under twenty doesn't go on the board, and even I agree with that one.
Caitlin types in the day's scores from the arcade cabinet, then
done. Arrange the lines so the low ones are turned away, only the rest are counted, anddoneends it.Score? 25 Score? 10 Too low for the board. Score? 30 Score? done On the board: 2Make the guessing game
Write Caitlin's game. Pick the number with
random.randint(1, 100).Guess? 50 Too high. Guess? 25 Too low. Guess? 37 Got it in 3.qprintsIt was 37.(the real number) and ends the game. A guess below 1 or above 100 getsBetween 1 and 100.and doesn't count.Use
while True, with abreakfor each way to finish and acontinuefor a guess that doesn't count, as in Paul's padlock. The labels from his program are in the file.The checks fix the number, then try a win, a
q, a right first guess, and guesses of 0, 100 and 150. While you test it yourself,print(secret)near the top saves a lot of guessing. Take it out before you press Check.Ship it
- CaitlinThirty-seven in three, and Yahya reckons he'd have done it in two.
- YahyaIf you halve what's left every time you never need more than seven guesses. It's just maths.
- CaitlinIt's a game, Yahya! Fewest guesses goes on the board.