A Python module is just a file that contains reusable code like functions. If a program is going to use functions that are stored in another module, it needs to first import that module.
The random module is one of the several modules available in python. It has functions for generating random numbers. The three functions associated with this module are:
1. random()---- Returns a random float value that is greater than or equal to 0.0 and less than 1.0.
2. randint(min,max)--- returns a random int value that is greater than or equal to the min argument and less than or equal to the maxargument.
3. randrange([start,],stop [,step]) --- Returns a random value greater than or equal to the start argument,less than the stop argument and a multiple of the step argument.
Here, we will write a program to illustrate its use. I have submitted earlier a program illustrating the use of this module(dieroll program) and again we write yet another program to illustrate its usage.
GUESS THE NUMBER GAME.
Task: To implement a game in which the user guesses a number generated randomly by the
computer. If the user guesses correctly, then a message is displayed informing the user
the number of guesses it took for him/her to guess correctly and the program ends. If
the guess is too high or low, than the user is given another chance to guess. And,if the
user is unable to guess correctly after 6 attempts, the program informs the user the
correct number and then ends.
THE PROGRAM.
import os
import sys
import random
print("Let us play a game. I will pick a number")
print("between 1 and 100 and you try to guess it")
compnum = random.randint(1,100)
guesscount = 0
guess = int(input("Your guess"))
while True:
guesscount = guesscount + 1
if (guess == compnum):
print("You got it in "+str(guesscount)+" guesses! My number was "+compnum)
break
if (guesscount == 6):
print("You did not get the number in 6 Guesses. My number is"+str(compnum))
break
if (guess < compnum):
print("That is too low. Try again")
guess = int(input("Your guess"))
elif (guess > compnum):
print("That is too high.Try again")
guess = int(input("Your guess"))