Guess the Number

Tags: tiny, beginner, game

Guess the Number is a classic game for beginners to practice basic programming techniques. In this game, the computer thinks of a random number between 1 and 100. The player has 10 chances to guess the number. After each guess, the computer tells the player if it was too high or too low.

guess_the_number.py
 1"""Guess the Number, by Al Sweigart al@inventwithpython.com
 2Try to guess the secret number based on hints.
 3This code is available at https://nostarch.com/big-book-small-python-programming
 4Tags: tiny, beginner, game"""
 5
 6import random
 7
 8
 9def askForGuess():
10    while True:
11        guess = input('> ')  # Enter the guess.
12
13        if guess.isdecimal():
14            return int(guess)  # Convert string guess to an integer.
15        print('Please enter a number between 1 and 100.')
16
17
18print('Guess the Number, by Al Sweigart al@inventwithpython.com')
19print()
20secretNumber = random.randint(1, 100)  # Select a random number.
21print('I am thinking of a number between 1 and 100.')
22
23for i in range(10):  # Give the player 10 guesses.
24    print('You have {} guesses left. Take a guess.'.format(10 - i))
25
26    guess = askForGuess()
27    if guess == secretNumber:
28        break  # Break out of the for loop if the guess is correct.
29
30    # Offer a hint:
31    if guess < secretNumber:
32        print('Your guess is too low.')
33    if guess > secretNumber:
34        print('Your guess is too high.')
35
36# Reveal the results:
37if guess == secretNumber:
38    print('Yay! You guessed my number!')
39else:
40    print('Game over. The number I was thinking of was', secretNumber)

https://inventwithpython.com/bigbookpython/project31.html