Numbers

The Python standard library includes a wide variety of tools for many different purposes. We’ve already seen and worked with some of them, including math, sys, csv, gzip, and others.

The standard library contains modules for operating system functions, debugging, profiling and unit testing, graphical interfaces and multimedia services, internet protocols and data handling, and many more.

math

The math library has a lot of useful functions in it. If you finished the exercises from the Functions section, you will have looked at it to find the math.ceil(x) function, which returns the smallest integer that is greater than or equal to the input x.

The library has most typical math functions such as square root, logarithmic functions, trigonometric functions, and other specialized math functions.

In addition, it contains two constant variables that are stored to the greatest precision the machine allows.

>>> import math
>>> math.pi
3.141592653589793
>>> math.e
2.718281828459045
>>> math.sqrt(121)
11.0

With the math.pi constant, we can calculate the area of a circle to the greatest precision possible on the machine:

>>> import math
>>> radius = 2.75
>>> area = math.pi * radius ** 2
>>> area
23.75829444277281

In a similar manner to math.ceil(x), there is math.floor(x). It find the largest integer less than or equal to the input x:

>>> math.floor(area)
23
>>> math.floor(math.pi)
3

random

Python also has a random module used for generating randomness.

Let’s use random to generate a random number between 0 and 1:

>>> import random
>>> random.random()
0.5512233773956505

There is a randrange() function that selects a random number in a range specified just like the range() function:

>>> random.randrange(21)
6
>>> random.randrange(21)
20

Because it works just like range(), we could tell it we only want even numbers:

>>> random.randrange(0, 21, 2)
12
>>> random.randrange(0, 21, 2)
0

We can also generate a random integer between two numbers, inclusively:

>>> random.randint(10, 20)
15
>>> random.randint(10, 20)
20

We can use help to find out more about the random and randint functions or about the random module:

>>> help(random.random)
>>> help(random.randint)
>>> help(random)

There is also a shuffle function:

>>> import random
>>> numbers = list(range(1, 10))
>>> numbers
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> random.shuffle(numbers)
>>> numbers
[7, 6, 3, 9, 5, 2, 4, 1, 8]

There’s also a choice function:

>>> colors = ["red", "blue", "green", "yellow"]
>>> random.choice(colors)
'yellow'
>>> random.choice(colors)
'blue'

The choice function only works on indexable iterables, so it won’t work on sets:

>>> colors = set(colors)
>>> colors
{'green', 'yellow', 'red', 'blue'}
>>> random.choice(colors)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
    File "python3.4/random.py", line 256, in choice
        return seq[i]
TypeError: 'set' object does not support indexing
>>> random.choice(tuple(colors))
'green'

There are many other useful functions in the random module. To see more, check out the documentation for random.

Random Exercises

Roll Die

Create a program roll.py that simulates rolling one or more dice. The number of sides on the dice should be provided as arguments. Each argument represents the number of sides of a die, so python roll.py 6 6 means rolling 2 6-sided dice. If no arguments are given, assume a single 6 sided die.

Examples:

$ python roll.py
5
$ python roll.py 6
4
$ python roll.py 20
10
$ python roll.py 6 6
7

Random Line

Create a program randline.py that accepts either an argument from the command-line or standard input text. The argument is treated as a file name and the standard input text is treated as lines of text. The program should return a random line from the file or from the standard input lines.

Example usage (with us-state-capitals.csv):

$ cat us-state-capitals.csv | python randline.py
Mississippi,Jackson
$ python randline.py us-state-capitals.csv
New Mexico,Santa Fe

Shuffle

Make a shuffle.py program that accepts an input file name and an output file name as input. The program should read the lines in the input file and write them to the output file in a random order.

Capital Guesser

Write a program that reads us-state-capitals.csv, picks a random state, and asks the user for the capital. The user has three chances to guess the capital before the game gives away the answer. The number of capitals that have been correctly guessed in a row should be printed out after each correct guess.

Example usage:

$ python guess_capitals.py
Guess U.S. State Capitals

What is the capital of California? Sacramento
Correct!  You have correctly guessed 1 capitals in a row!

What is the capital of Texas? Dallas.
Sorry that's not right.

What is the capital of Texas? Austin
Correct!  You have correctly guessed 2 capitals in a row!

What is the capital of Nevada? Reno
Sorry that's not right.

What is the capital of Nevada? Las Vegas
Sorry that's not right.

What is the capital of Nevada? Paradise
Sorry that's not right.
The capital of Nevada is Carson City.

What is the capital of Ohio? Columbus
Correct!  You have correctly guessed 1 capitals in a row!