Skip to main content

Chapter 5a - Random



import random

print(random.randrange(10, 20))

Possible random values in this range are: 10, 11, 12, 13, 14, 15, 16, 17, 18, 19

20 is out of this range as it returns values less than that specified as the second argument.

  • Change the code above so it chooses a number from 30-39

Tossing a Coin

import random
import time

print('This is a simulation of a coin toss')
print('Tossing coin now...\n')


toss_result = random.randrange(0,2)
#randrange generates a random number from the range of 0 to less than 2

#check what the value of toss_result is

if toss_result == 0:

(i) Does the user provide any input here? No

(ii) What are the possible outputs? Heads or Tails

(iii) Which line of code requires that the random module be imported? Line 7

(iv) What are the values stored by toss_result?

0 and 1 only, comment line 8 helps in answering this question


  • Create a program to randomnly assign someone in either blue or red team

🙋‍♀️ Sample program



import random

print(random.uniform(10, 20))


import random

import time

print('This program simulates the throw of a dice')

print('Throwing the dice now...\n')


face = random.randrange(1,7) # generate a random number in the range 1 to 6

print("You got a " + str(face))


Practice: simulate a dice of 20 faces

  • This is the program for a dice of only number 6 (not working)
  • Fix it so it has 20 faces 1, 2, 3, 4... 20