Python libraries and modules

The Python standard library gives you ready-made functions for common tasks so you don't have to write everything from scratch — a topic every UK GCSE Computer Science specification requires. This unit covers the import statement in its two forms, how to call library functions, and the two libraries GCSE and A Level pupils meet most often: random (for dice, coin flips and random choices) and math (for square roots, rounding and pi). Every example runs in the browser via RunPy. Perfect for classroom teaching, GCSE and A Level revision, and independent or home-schooled learners.


What you'll learn

  • Use import module to load a library
  • Call library functions as module.function()
  • Use random.randint(a, b) and random.choice(sequence)
  • Use math.sqrt(), math.floor(), math.ceil() and math.pi
  • Understand the difference between import module and from module import name

UK GCSE topic coverage

  • Modules and imports
  • random
  • time
  • datetime
  • math
  • Applied libraries

Worked example

Roll two dice using the random library

import random

die1 = random.randint(1, 6)
die2 = random.randint(1, 6)
print("You rolled", die1, "and", die2, "= ", die1 + die2)

Try a full unit free with a RunPy account

Sign up free and get the whole of Unit 1 (Input, Output and Variables) with checked tasks and instant feedback, plus a selection of the exam-style questions so you can practice on real GCSE-style content before upgrading.


Lessons in this unit

Full interactive lessons with checked tasks are available to signed-in RunPy users. Unit 1 and a selection of exam-style questions are free with a RunPy account.

  1. What is a module?
  2. The random module
  3. The time module
  4. The datetime module
  5. The math module
  6. Bringing it together

Frequently asked questions

What is the difference between a library and a module?
In Python they're often used interchangeably at GCSE level. A module is a single file of code you can import; a library is a collection of related modules. random and math are both modules in the standard library.
Do I need to install these?
No. random and math are part of Python's standard library, so they're always available. Just import them.
How is random.randint different from random.randrange?
random.randint(a, b) includes both endpoints, so randint(1, 6) can return 1 through 6. random.randrange(a, b) excludes the upper endpoint, like range(). GCSE questions overwhelmingly use randint.