logo

Simple text game with Python

In this article we will demonstrate how to create a simple guessing game.
The goal of the game is to guess the right number.

Example
An example run below:

python-text-game Simple text game with Python

You may like
Python Game Development for Beginners

Random number


The user will be asked to guess the random number. We first pick the random number:

from random import randint

x = randint(1,9)

The randint() function will pick a pseudo random number between 1 and 10. Then we have to continue until the correct number is found:

guess = -1

print("Guess the number below 10:")
while guess != x:
guess = int(raw_input("Guess: "))

if guess != x:
print("Wrong guess")
else:
print("Guessed correctly")

Python Guessing Game


The code below starts the game:

from random import randint

x = randint(1,9)
guess = -1

print "Guess the number below 10:"
while guess != x:
guess = int(raw_input("Guess: "))

if guess != x:
print("Wrong guess")
else:
print("Guessed correctly")

An example run:

Guess the number below 10:
Guess: 3
Wrong guess
Guess: 6
Wrong guess
..


BackNext

4 thoughts on “Simple text game with Python


  1. cam
    - July 9, 2016

    How do I play the game

    1. Frank
      - July 15, 2016

      Execute it with Python. (python game.py), where game.py is one of the files above

  2. Nathan
    - October 30, 2015

    How do you print a random float?

    1. Frank
      - October 31, 2015

      Hi Nathan,

      You can get a random float using the random.uniform() function.
      Example program generating a float between 1.1 and 5.5:

      import random
       x = random.uniform(1.1,5.5)
      print(x)

Leave a Reply

Login disabled