Random Module
Introduction to Programming in Python
Randomness Remember that one of Python’s libraries is the random module.
Several useful functions are defined there.
randint(a,b) : generate a random integer between a and b,
Dr. Bill Young inclusively.
Department of Computer Science randrange(a, b) : generate a random integer between a and
University of Texas at Austin b-1, inclusively.
random() : generate a float in the range (0 . . . 1).
Last updated: June 4, 2021 at 11:05
Texas Summer Discovery Slideset 13: 1 Randomness Texas Summer Discovery Slideset 13: 2 Randomness
Random Numbers: Examples Aside on Import
There are several different ways to use import.
>>> import random
>>> random . randint (0 , 9) # same as randrange (0 , 10)
8 >>> import random # imports module , not names
>>> random . randint (0 , 9) >>> random ()
3 Traceback ( most recent call last ) :
>>> random . randrange (0 , 10) # same as randint (0 , 9) File " < stdin > " , line 1 , in < module >
2 TypeError : ’ module ’ object is not callable
>>> random . randrange (0 , 10) >>> random . random ()
0 0 . 4 6 7 14 5 2 2 5 2 5 8 8 2 87 3
>>> random . randrange (0 , 10) >>> from random import random # import name random
3 >>> random ()
>>> random . random () 0 .9 8 93 7 20 3 04 83 0 84 2
0. 6 89 0 1 39 4 3 33 82 49 >>> randint (0 , 9) # but not randint
>>> random . random () Traceback ( most recent call last ) :
0 . 5 4 6 6 0 6 11 3 40 2 98 4 3 File " < stdin > " , line 1 , in < module >
NameError : name ’ randint ’ is not defined
>>> from random import * # import all names
It’s often useful to generate random values to test your programs >>> randint (0 , 9)
5
or to perform scientific experiments.
Texas Summer Discovery Slideset 13: 3 Randomness Texas Summer Discovery Slideset 13: 4 Randomness
Rolling Dice Randomness Exercise
Exercise: Generate a series of random integers between 1 and 6
Suppose we have a 6-sided dice. If it’s a fair dice it should land and count how often each appears. See how close each approaches
equally often on any of the six sides. to 1/6 of the total. How do we do this?
So the probabilities should be:
roll odds
1 1/6
2 1/6
3 1/6
4 1/6
5 1/6
6 1/6
Let’s see if our random function can act like a fair dice.
Texas Summer Discovery Slideset 13: 5 Randomness Texas Summer Discovery Slideset 13: 6 Randomness
Randomness Exercise Randomness Exercise
Exercise: Generate a series of random integers between 1 and 6 def printResults ( counts ) :
and count how often each appears. See how close each approaches # Compute and print expected probability :
to 1/6 of the total. How do we do this? oneSixth = 1/6
print ( " 1/6 = " , round ( oneSixth , 6) )
# Print header line :
In file rollDice.py: print ( " Roll \ tCount \ tProbability \ tDifference " )
# Roll a 6 - sided dice and see how fair it is . # See how close the actual values were to the
# expected probability of 1/6.
from random import randint for i in range ( 1 , 7 ) :
NUMROLLS = 1000000 count = counts [i -1]
prob = count / NUMROLLS
def rollDice ( ) : diff = (( prob - oneSixth ) / oneSixth ) * 100.0
# Create an list of 6 zeros : print (i , count , prob , round ( diff , 2) , sep = " \ t " )
counts = [0] * 6
for i in range ( NUMROLLS ) : def main () :
# Record each roll in counts list : counts = rollDice ()
roll = randint (1 , 6) printResults ( counts )
counts [ roll -1] += 1
return counts main ()
Texas Summer Discovery Slideset 13: 7 Randomness Texas Summer Discovery Slideset 13: 8 Randomness
Rolling Dice Exercise: Flipping a Coin
Exercise: How many times do you have to flip a coin to get k
heads in a row? How could you write a program to try that?
Here’s the results of one run of the program. Would you expect
the results to always look like this? What would you expect to
from randomnessTest import *
happen if you increase or decrease NUMROLLS? >>> flipCoin ( 5 )
Found sequence of 5 heads at 45 flips !
> python rollDice . py >>> flipCoin ( 2 )
1/6 = 0.166667 Found sequence of 2 heads at 15 flips !
Roll Count Probability Difference >>> flipCoin ( 10 )
1 166963 0.166963 0.18 Found sequence of 10 heads at 798 flips !
2 166958 0.166958 0.17 >>> flipCoin ( 15 )
3 166628 0.166628 -0.02 Found sequence of 15 heads at 117725 flips !
4 166271 0.166271 -0.24 >>> flipCoin ( 20 )
5 166473 0.166473 -0.12 Found sequence of 20 heads at 28782 flips !
6 166707 0.166707 0.02 >>> flipCoin ( 20 )
Found sequence of 20 heads at 3677435 flips !
>>> flipCoin ( 1 )
Found sequence of 1 heads at 4 flips !
>>> flipCoin ( 25 )
Found sequence of 25 heads at 62705525 flips !
Texas Summer Discovery Slideset 13: 9 Randomness Texas Summer Discovery Slideset 13: 10 Randomness
Exercise: Flipping a Coin Exercise: Guessing Game
In file randomnessTest.py:
# Flip a coin until you get k heads in a row and return Suppose we want to implement a guessing game with the user.
# the number of flips required .
TAIL , HEAD = 0 , 1 Generate a random integer between 1 and 99. Accept guesses from
the user until he or she guesses the number or exceeds the allowed
def flipCoin ( k ) :
""" Flip a coin until k consecutive heads appear . Print
number of guesses. It should be possible to guess the number in
number of flips required ? """ no more than 7 guesses. Why?
flipCount = 0
c onse cutive Heads = 0 The program should behave as follows:
while True :
flip = randint (0 , 1) 1 If the user guesses the number, congratulate him or her and
flipCount += 1 stop play.
if flip == HEAD :
co nsecut i ve He ad s += 1 2 If an illegal guess is entered, say so, but count it as one guess.
if c on sec u ti v eH e ad s == k :
print ( " Found sequence of " , k , " heads at " , 3 If the user exceeds 7 guesses, say so and stop play.
flipCount , " flips ! " )
return
4 If the guess is too low/high, say so and allow another guess.
else :
co nsecut i ve He ad s = 0
Texas Summer Discovery Slideset 13: 11 Randomness Texas Summer Discovery Slideset 13: 12 Randomness
Exercise: Guessing Game Exercise: Guessing Game
> python GuessingGame . py
Enter an integer from 1 to 99: 135 > python GuessingGame . py
That ’s an illegal guess . Try again ! Enter an integer from 1 to 99: 50
Enter an integer from 1 to 99: 50 Guess is too high . Try again !
Guess is too low . Try again ! Enter an integer from 1 to 99: 25
Enter an integer from 1 to 99: 75 Guess is too high . Try again !
Guess is too low . Try again ! Enter an integer from 1 to 99: 12
Enter an integer from 1 to 99: 87 Guess is too high . Try again !
Guess is too high . Try again ! Enter an integer from 1 to 99: 6
Enter an integer from 1 to 99: 81 Guess is too high . Try again !
Guess is too low . Try again ! Enter an integer from 1 to 99: 3
Enter an integer from 1 to 99: 84 Guess is too high . Try again !
Guess is too low . Try again ! Enter an integer from 1 to 99: 2
Enter an integer from 1 to 99: 86 Guess is too high . Try again !
Guess is too high . Try again ! Enter an integer from 1 to 99: 1
Whoops ! You took too many guesses . The answer was 85 C on grat ula tions ! You took 7 guesses !
Texas Summer Discovery Slideset 13: 13 Randomness Texas Summer Discovery Slideset 13: 14 Randomness
Guessing Game Solution
import random
GUESSESALLOWED = 7
def main () :
n = random . randint (1 , 99)
guesses = 0
while guesses < GUESSE SALLOWED :
guess = int ( input ( " Enter an integer 1 to 99: " ) )
if guess < 1 or guess > 99:
print ( " That ’s an illegal guess . Try again ! " )
elif guess == n :
print ( " Con grat u lati ons ! You took " , \
guesses + 1 , " guesses ! " )
return
elif guess < n :
print ( " Guess is too low . Try again ! " )
else :
print ( " Guess is too high . Try again ! " )
guesses += 1
print ( " Whoops ! You took too many guesses . " , \
" The answer was " , n )
main ()
Texas Summer Discovery Slideset 13: 15 Randomness