How to Create a Guess My Number Game in Python

Submitted by: 
Language: 
Visitors have accessed this post 329 times.

Introduction:
This tutorial is on how to make a guess my number game in Python.

The Game:
This is a simple game where the computer chooses a random number, then the player has a certain amount of guesses to guess the correct number by following the feedback (too high, or too low).

The Imports:
First we need to import the random module to let the computer choose a random number...

  1. import random;

The Variables:
Next we want to create the variables that will be used throughout the game. We need the current player lives count, the number to guess, and the current player guess. The number (computers) to guess is in caps because it is a constant and will not change.

  1. GUESS = random.randint(0, 100);
  2. lives = 5;
  3. player = int(input("Enter your guess...\n"));

The Game Loop:
Now we perform the real game loop. While the player has lives left, and the players current guess is not the correct number, we output whether their current guess is too high, or too low, remove one life, and ask for another number guess...

  1. while (player is not GUESS and lives > 0):
  2. if (player < GUESS):
  3. print("Wrong, too low.");
  4. else:
  5. print("Wrong, too high.");
  6. lives -= 1;
  7. player = int(input("\n"+str(lives+1)+" lives left.\nEnter your guess...\n"));

The Ending:
Finally we come out of the while loop and check if the player has any lives left (they can play on 0, so we check if lives is equal to 0 or higher), if they do they won so we say "Correct!". If they haven't won, we tell them the correct number...

  1. if (lives > -1):
  2. print("Correct!");
  3. else:
  4. print("You ran out of lives. The correct answer was " + str(GUESS));

Add new comment

Filtered HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • You may insert videos with [video:URL]
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd> <table> <tr> <td> <th> <img> <h1> <h2> <h3> <iframe> [video]
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <asp>, <c>, <cpp>, <csharp>, <css>, <html4strict>, <java>, <javascript>, <mysql>, <php>, <python>, <sql>, <vb>, <vbnet>. The supported tag styles are: <foo>, [foo].
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.