Solution: Number guessing game in Python

来源:互联网 时间:1970-01-01

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

Solution in Python 2


import randomhidden = random.randrange(1, 201)# print hiddenguess = int(raw_input("Please enter your guess: "))if guess == hidden: print "Hit!"elif guess < hidden: print "Your guess is too low"else: print "Your guess is too high"

The first thing is to load the randommodule. It has a method called randrangethat 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_inputfunction 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 intfunction to convert it to an integer number.

Once we have the guesswe can compare it to the hiddennumber and provide feedback to the user.

Solution in Python 3


import randomhidden = random.randrange(1, 201)print(hidden)guess = int(input("Please enter your guess: "))if guess == hidden: print("Hit!")elif guess < hidden: print("Your guess is too low")else: print("Your guess is too high")

There are two differences compared to the Python 2 solution:

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