Bu yazıyı Türkçe okuyun · Leer en español
What does this project do?
In the third episode of the Python for Kids series, we write our first game: the computer picks a number between 1 and 100 and you try to find it. We learn random, if, elif, else, the while loop and break. For ages 10 and up who are new to Python.
- Age group: 10 and up
- Level: Beginner
- Time: About 30 minutes
- What you will learn: random, if, elif, else, the while loop, a counter
What you need
| Item | Notes |
|---|---|
| Computer | Windows, macOS or Linux |
| Python 3 | Free from python.org; IDLE comes with it |
Code
In IDLE, open a new window with File → New File, type the code, save it as guessing_game.py and press F5 to run it.
# Number Guessing Game - ozandamci.com
import random
number = random.randint(1, 100)
tries = 0
print("I picked a number between 1 and 100. Can you guess it?")
while True:
guess = int(input("Your guess: "))
tries = tries + 1
if guess < number:
print("Try a bigger number.")
elif guess > number:
print("Try a smaller number.")
else:
print("You got it! My number was", number)
print("You found it in", tries, "guesses.")
break
Step by step
- The computer picks a number: the random library makes random numbers.
randint(1, 100)picks a number between 1 and 100 (both included). - A counter and the rules: the
triesvariable starts at zero and goes up by one with every guess. Then we print the rule of the game. - An endless loop:
while True:repeats the lines inside it again and again. Each time it reads a guess, turns it into a number withint()and adds one totries. - Too small or too big?
ifthe guess is smaller, it says “Try a bigger number”.elif(else if) the guess is bigger, it says “Try a smaller number”. - You got it!
else:if neither is true, the guess is right. It prints the number and how many guesses it took;breakleaves the loop.
Try it yourself
- A harder game: use
randint(1, 1000)to pick a number between 1 and 1000 - Limited tries: when
triesreaches 7, print “You lost” and stop withbreak - Praise: if it took fewer than 3 guesses, print “You are amazing!”





“Python for Kids: Make a Number Guessing Game (Code and Guide)” için 2 yorum