Search for '{{search_term}}'

Solution: Number guessing game in Python

CMOS is the Code-Maven Open Source podcast that also includes video interviews. Subscribe to this feed RSS feed with your Podcast listener app or via iTunes iTunes.

In this exercise, you were asked to create the first version of the Number guessing game. Here we are going to see a solution in Python.

Solution in Python 2


import random

hidden = random.randrange(1, 201)
# print hidden

guess = int(raw_input("Please enter your guess: "))

if guess == hidden:
    print "Hit!"
elif guess < hidden:
    print "Your guess is too low"
    print "Your guess is too high"

The first thing is to load the random module. It has a method called randrange that can generate an integer number ina given range. In our case we wanted to have a number that can be 1 .. 200 but because of the way the Python range works we had to call the method with 201 as the ranges in Python never include the upper boundary.

the commneted out

# print hidden

is only there so if we remove the commenting, then we can see what was the hidden value and we can check if the program works as expected.

Then we use the raw_input function to prompt and to read the value from the standard input. Just as in Ruby, here too the value we receive is a string. We use the int function to convert it to an integer number.

Once we have the guess we can compare it to the hidden number and provide feedback to the user.

Solution in Python 3


import random

hidden = random.randrange(1, 201)

guess = int(input("Please enter your guess: "))

if guess == hidden:
elif guess < hidden:
    print("Your guess is too low")
    print("Your guess is too high")

There are two differences compared to the Python 2 solution:

  1. print() is now a function. It requires parentheses around the parameters.
  2. Instead of raw_input, now we should use the plain input function to get values from standard input.


In the comments, please wrap your code snippets within <pre> </pre> tags and use spaces for indentation.
comments powered by Disqus