Python for Kids: Make a Number Guessing Game (Code and Guide)

Python for Kids: Make a Number Guessing Game (Code and Guide)

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

ItemNotes
ComputerWindows, macOS or Linux
Python 3Free 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

  1. The computer picks a number: the random library makes random numbers. randint(1, 100) picks a number between 1 and 100 (both included).
  2. A counter and the rules: the tries variable starts at zero and goes up by one with every guess. Then we print the rule of the game.
  3. An endless loop: while True: repeats the lines inside it again and again. Each time it reads a guess, turns it into a number with int() and adds one to tries.
  4. Too small or too big? if the guess is smaller, it says “Try a bigger number”. elif (else if) the guess is bigger, it says “Try a smaller number”.
  5. You got it! else: if neither is true, the guess is right. It prints the number and how many guesses it took; break leaves the loop.

Try it yourself

  • A harder game: use randint(1, 1000) to pick a number between 1 and 1000
  • Limited tries: when tries reaches 7, print “You lost” and stop with break
  • Praise: if it took fewer than 3 guesses, print “You are amazing!”

Video

The narration is in Turkish. English subtitles are available: click CC on the video.

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

Bir Cevap Yazın