Number guessing game – Random
Summary : The earlier version of the number guessing game had the number hard coded in it. This time, let’s use the random library from python to let the program fix on a random number.
# In this program we will enhance the number guessing game
# by including a random number rather than a hard-coded secret
import random
secret_num = random.randint(1,101)
print ( " Guess a number between 1 and 100")
num = input ()
while ( True ):
if int(num) > secret_num :
print ( " guess a lower number " )
num = input ()
if int(num) < secret_num :
print ( " guess a higher number" )
num = input ()
if int(num) == secret_num :
print ( " Hurray !! you guessed it ")
break
random is a standard library in python that can generate random numbers for you. There are many functions in this library and the one we are using here is randint that can generate a random integer between a given start and end number range. Once you got that, the rest of the program is exactly similar to the previous version of the number guessing game.