Modules are very useful to use in our programs. They are pieces of code that someone else wrote (they could even be your own modules) that you can import into your program. They have functions on them that you can call to perform something special.


Some common modules are sys, os, math and random. These are really handy and one of my favorites is random. We could create a little dice rolling program using random:

import random

This very simple program will print out a random number between 1 and 6.

You can import modules in various ways:

  • import random will simply import all of random's functions prefixed by random as we saw in the example above. -
  • import random as rand will allow you to shorten the command like: print(rand.randint(1,6))
  • from random import randint will allow you to call randint without any prefix: print(randint(1,6))
  • from random import * will import all of randoms methods in a manner that you don't have to prefix them (I don't recommend doing this)

results matching ""

    No results matching ""