Night 10: Guess my number
คุณเรียนจบคืนนี้แล้วด้วย Python หรือรหัสเทียม และนับรวมในทั้งสองภาษา คุณสามารถฝึกอีกครั้งได้ตามต้องการ
Tonight: guess my number
- Tonight you build your first game!
- Your pet thinks of a number. The player guesses. Your pet says "too low" or "too high".
- Nothing new to learn: you use
input(),if,whileand a counter together.
Words for tonight
| Word | Meaning |
|---|---|
| guess | an answer when you are not sure |
| secret | something only one person knows |
| hint | a small help that shows the way |
Step 1: one guess
- Start small. Read one guess and give one hint.
secret = 7
guess = 5
if guess < secret:
print("Too low")
elif guess > secret:
print("Too high")
else:
print("You got it!")
- Change
guessto 9, then 7, and press Run each time.
Step 2: guess again and again
- Put the hint inside a
whileloop. The loop goes on while the guess is wrong.
| Line | What it does |
|---|---|
while guess != secret: |
go on while the guess is wrong |
if … else |
give a hint |
guess = int(input()) |
read the next guess |
- After the loop, the guess must be right. Print
You got it!.
Step 3: count the tries
- A counter tells the player how well they did.
tries = 1at the start, thentries = tries + 1after each new guess.
A real game uses random
- In a real game, the secret is different each time:
import random
secret = random.randint(1, 10)
print("I am thinking of a number from 1 to 10.")
- In the tasks the secret is always
7. Then the checker can test your game fairly. - When you finish, change
7torandom.randint(1, 10)and play it yourself!
ความยาก 2/5 · 140 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
Your pet's secret number is 7. Read one guess with int(input()). Print Too low, Too high หรือ You got it!.
คลิก Run เพื่อดูผลลัพธ์ที่นี่
ความยาก 3/5 · 200 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
Now let the player guess again and again. After each wrong guess, print Too low หรือ Too high and read the next guess. When the guess is right, print You got it!.
คลิก Run เพื่อดูผลลัพธ์ที่นี่
ความยาก 3/5 · 200 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
Count the guesses in tries. At the end, print You got it in and the number of tries, then tries!. For guesses 3, 9, 7 the last line is You got it in 3 tries!.
คลิก Run เพื่อดูผลลัพธ์ที่นี่
ความยาก 4/5 · 280 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
Make the game harder: only 3 tries. If the player gets it, print You got it!. If all 3 guesses are wrong, print Too low หรือ Too high for each, then Out of tries! It was 7.
คลิก Run เพื่อดูผลลัพธ์ที่นี่