Additional programming techniques

Random Number Generation

Random number generation is essential for simulations, games, and testing.

In PseudoCode you can use the following to provide a random number

# Creates a random integer between 1 and 6 inclusive. 
myVariable = random(1,6) 

#Creates a random real number between -1.0 and 10.0 inclusive.
myVariable = random(-1.0,10.0)

In python you need to import Python's random module to have the ability to generate random numbers.

Importing the Random Module

import random

Generating Random Numbers

Random Integer

Random Integer: random.randint(a, b)

Returns a random integer N such that a <= N <= b.

import random

random_int = random.randint(1, 10)
print(random_int)  # Output: Random integer between 1 and 10

Random Float

Random Float: random.random()

Returns a random float between 0.0 and 1.0.

import random

random_float = random.random()
print(random_float)  # Output: Random float between 0.0 and 1.0

Random Choice from a List

To return a randomly selected element from a non-empty sequence you can use a random integer on the size of the list.

colours = ['red', 'blue', 'green']
random_colours = colours[random.randint(0, len(colours))]
print(random_colours)  # Output: Randomly chosen colours from the list

this looks a bit messy but this part

random.randint(1, len(colours))

Will return a random number between of either 0, 1, 2 and then as it is contained with colours[ *here* ] it will select a random colour. This is a useful skill to be aware of.

However, for ease of coding Python Random also comes built in with a useful method

Random Choice from a List: random.choice(seq)


colours = ['red', 'blue', 'green']
random_colours = random.choice(colours)
print(random_colours)  # Output: Randomly chosen colours from the list
Previous
Sub programs (functions and procedures)