Back to: Python Programming
We can generate random numbers in python by importing the “random” module. The random module gives us access to a lot of useful methods involving random numbers. For a comprehensive list:
import random
print(help(random))
To simulate the roll of a dice, we’ll need a whole integer between 1 and 6.
import random
number = random.randint(1, 6) # <-- random integer from 1 to 6
print(number)
The minimum and maximum value of the random number can be specified by a variable:
import random
low = 20
high = 45
number = random.randint(low, high)
print(number)
For a random floating point number, use the random() method:
import random
number = random.random() # <-- generates float between 0 and 1
print(number)
0.8858268235954725
To pick a random choice from a sequence, if we have a tuple of options, we can access the random module, then use the choice method and place our tuple within the choice method.
import random
options = ("rock", "paper", "scissors")
option = random.choice(options)
print(option)
There is also a shuffle method which allows us to shuffle a sequence:
import random
cards = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A']
random.shuffle(cards)
print(cards)
['Q', '7', 'K', '5', '4', 'J', '10', '3', '9', '6', '2', 'A', '8']
Exercise
Create a number guessing game. A user has to guess a number between a certain range (1 – 100).
import random
low = 1
high = 100
guesses = 0
number = random.randint(low, high)
while True:
guess = int(input(f"Guess a number between {low} and {high}: "))
guesses += 1
if guess < number:
print(f"{guess} is too low")
elif guess > number:
print(f"{guess} is too high")
else:
print(f"Well done!! {guess} is correct")
break
print(f"You guessed the answer in {guesses} tries!")