Revise Computingrevisecomputing.co.uk
At a glanceFeaturesStudentsPricingHow it worksFree GCSE notesExam dates
At a glanceFeaturesStudentsPricingHow it worksFree GCSE notesExam dates

Knowledge organisers / Random Number Generation

Off-by-one

All topicsPractise exam questions
Knowledge organiser

Random Number Generation

301.14c

Avoid fencepost errors.

What you need to know

Off-by-one errors with random numbers happen when you use the wrong range boundaries. Remember that randint(a, b) includes both a and b.

Key points

  • randint(1, 6) includes both 1 and 6
  • randint(0, 9) gives 10 possible values (0 through 9)
  • Don't confuse with range() which excludes the end
  • Test with the minimum and maximum values to verify

Code examples

Off-by-one check
python
import random
# Want numbers 1 to 10 inclusive
num = random.randint(1, 10)  # Correct: includes 10

# Common mistake with range:
# range(1, 10) gives 1-9 (excludes 10)
# randint(1, 10) gives 1-10 (includes 10)