## 10.6 Mathematics 

The math module gives access to the underlying C library functions for floating point math: 

>>> import math >>> math.cos(math.pi /4) 0.70710678118654757 >>> math.log( 1024 ,2) 10.0 

The random module provides tools for making random selections: 

>>> import random >>> random.choice(['apple','pear','banana']) 'apple' >>> random.sample( range(100 ),10 ) # sampling without replacement [30, 83, 16, 4, 8, 81, 41, 50, 18, 33] >>> random.random() # random float 0.17970987693706186 >>> random.randrange( 6) # random integer chosen from range(6) 4 

The statistics module calculates basic statistical properties (the mean, median, variance, etc.) of numeric data: 

>>> import statistics >>> data =[2.75 ,1.75 ,1.25 ,0.25 ,0.5 ,1.25 ,3.5 ] >>> statistics.mean(data) 1.6071428571428572 >>> statistics.median(data) 1.25 >>> statistics.variance(data) 1.3720238095238095 

The SciPy project <https://scipy.org> has many other modules for numerical computations. 

## 10.7 Internet Access 

There are a number of modules for accessing the internet and processing internet protocols. Two of the simplest are urllib.request for retrieving data from URLs and$_{smtplib}$for sending mail: 

>>> from urllib.request import urlopen >>> with urlopen( 'http://tycho.usno.navy.mil/cgi-bin/timer.pl ') as response: ... for line in response: ... line =line.decode('utf-8 ') # Decoding the binary data to text. ... if 'EST' in line or 'EDT' in line: # look for Eastern Time ... print(line) <BR>Nov. 25, 09:43:32 PM EST >>> import smtplib >>> server =smtplib.SMTP('localhost') >>> server.sendmail( 'soothsayer@example.org','jcaesar@example.org ', ... """To: jcaesar@example.org ... From: soothsayer@example.org ... ... Beware the Ides of March. ... """ ) >>> server.quit() 

(Note that the second example needs a mailserver running on localhost.) 

