4.6. Using Python Standard Library

The Python standard library is a set of modules included with every Python installation. Now you have a basic understanding of how functions and classes work, you can start to use modules like these that other programmers have written. You can use any function or call in the standard library by including a simple import statement at the top of your file. Let's look at two modules, random and math which can be useful in modeling many real-world situations.

For the list of all built-in modules, you can see here.

Here's how to generate a random number between 1 and 6.

Another useful function is choice(). This function takes in a list or tuple and returns a randomly chosen element.


For further about random module, see here.

Python also has a built-in module that you can use for mathematical tasks.

The math module has a set of methods and constants.


For further about math module, see here.

Exercise 4.6

  1. Dice
    Make a class Die with one attribute called sides, which has a default value of 6. Write a method called roll_die() that prints a random number between 1 and the number of sides the die has. Make a 6-sided die and roll it 10 times.
    Make a 10-sided die and a 20-sided die. Roll each die 10 times.

  2. Lottery
    Randomly select four numbers / letters from the provided list. Save them in one string called lucky_combo . Then, print a message saying:
    The lucky combination for today is: {lucky_combo}
    Any ticket matching that will win a prize.

  3. Lottery Analysis
    Write a loop that keeps pulling combinations (save it in my_ticket) and also counting them (save it in ticket_counter). The loop stops when my_ticket is the same as lucky_combo.
    Then, print a message reporting:
    You have bought {ticket_counter} tickets until you win the ticket.