Did you know? Programmers convert coffee to code.

If you like my articles, sponsor me a coffee.

At the other end of the link I post some results of my other hobbies, like playing bass. It is worth checking it out ;)

Guess the number — the first approach

Now let’s write a script which implements a basic “Guess the number” game. The rules of the game are:

  • The user selects if he/she wants to guess a number between 1 and 100 or 1 and 1000
  • Based on the number-range the user has a fixed number of guesses
  • The application generates a number to guess
  • The user enters a number
    • if it is the secret number the application congratulates the user and ask if he/she wants to play another round or not
    • else the application tells the user if the secret number is less or greater than the number provided
    • the guess count is increased
  • if the user used up all guesses then the application tells him/her the secret number and asks if the user wants to play another round or not

As you can see, the rules are simple but seem complicated to implement. It is up to you how you want to handle wrong input types (no numbers).

This article is an excerpt of my book Python 3 in Anger. For a more detailed version take a look at the book.

Well, it is not as difficult as it sounds. Let’s see some example output of my solution:

<br />
Should the secret number between 1 and 100 or 1 and 1000? 100<br />
You have chosen 100, you will have 7 guesses to find the secret number.<br />
I have chosen the secret number...<br />
What's your guess? 34<br />
The secret number is higher...<br />
What's your guess? 54<br />
The secret number is higher...<br />
What's your guess? 66<br />
Congrats, you have Won!<br />
The secret number was  66<br />
Do you want to play another round? (yes / no) yes<br />
Should the secret number between 1 and 100 or 1 and 1000? 1000<br />
You have chosen 1000, you will have 10 guesses to find the secret number.<br />
I have chosen the secret number...<br />
What's your guess? 500<br />
The secret number is lower...<br />
What's your guess? 400<br />
The secret number is lower...<br />
What's your guess? 300<br />
The secret number is higher...<br />
What's your guess? 350<br />
The secret number is higher...<br />
What's your guess? 375<br />
The secret number is lower...<br />
What's your guess? 370<br />
The secret number is lower...<br />
What's your guess? 360<br />
The secret number is higher...<br />
What's your guess? 365<br />
The secret number is lower...<br />
What's your guess? 364<br />
The secret number is lower...<br />
What's your guess? 363<br />
The secret number is lower...<br />
Sorry, you lose.<br />
The secret number was  362<br />
Do you want to play another round? (yes / no) no<br />

As you can see the application does not stop when the guesses run out and it displays a message if the user won or lost.

Let’s look at the code.

<br />
__author__ = 'GHajba'</p>
<p>import random</p>
<p>while True:<br />
    while True:<br />
        try:<br />
            max_number = int(input('Should the secret number between 1 and 100 or 1 and 1000? '))<br />
        except ValueError:<br />
            print(&quot;This was not a number!&quot;)<br />
            continue<br />
        if max_number != 100 and max_number != 1000:<br />
            continue<br />
        else:<br />
            break</p>
<p>    if max_number == 100:<br />
        guess_count = 7<br />
    else:<br />
        guess_count = 10</p>
<p>    print('You have chosen {}, you will have {} guesses to find the secret number.'.format(max_number, guess_count))</p>
<p>    secret_number = random.randint(1, max_number)</p>
<p>    print('I have chosen the secret number...')</p>
<p>    guesses = 0</p>
<p>    while guess_count - guesses:<br />
        try:<br />
            guesses += 1<br />
            guessed = int(input(&quot;What's your guess? &quot;))<br />
        except ValueError:<br />
            continue<br />
        if guessed == secret_number:<br />
            print('Congrats, you have Won!')<br />
            break<br />
        elif guessed &gt; secret_number:<br />
            print('The secret number is lower...')<br />
        else:<br />
            print('The secret number is higher...')<br />
    else:<br />
        print(&quot;Sorry, you lose.&quot;)</p>
<p>    print(&quot;The secret number was &quot;, secret_number)<br />
    answer = ''<br />
    while answer.lower() not in ['yes', 'no', 'y', 'n']:<br />
        answer = input(&quot;Do you want to play another round? (yes / no) &quot;)</p>
<p>    if 'no' == answer or 'n' == answer:<br />
        break<br />

As you can see, the code is quite heavy because we include a lot of loops to verify the input and to handle the main game loop. And perhaps you will find this code later not readable at all. To solve this problem we will learn about functions and then we will refactor this piece of code to use functions.

However there are some alternative solutions to this script too. For example you can change the while loop in the middle to a for loop:

<br />
for guesses in range(guess_count):<br />

In this case the loop iterates through the range of guesses and ends if the last number is reached.

Share the knowledge!
GHajba

Senior developer, consultant, author, mentor, apprentice. I love to share my knowledge and insights what I achieve through my daily work which is not trivial -- at least not for me.

Click Here to Leave a Comment Below

>
%d bloggers like this: