The module 'random' is imported when random numbers are needed. It is a 'built in' module (included in the Python standard library which is installed with the language) but nevertheless it must be imported.
'random' offers a number of helpful functions such as:
- random.seed(seednum): initializes the random number generator (if not used then seed is the current system time). Use of the same seednum reproduces the random number sequence
- random.randint(start, stop): returns a random integer in [start, stop]
- random.randrange(start, stop[,step]): returns a random elemen in [start, stop] with [step] beng optional
- random.shuffle(x): Shuffles the sequence x
import random
random.seed(12345)
a = random.randint(1,10)
a
b = random.randrange(1,20,2)
b
- math.exp(x): returns e**x
- math.log(x[, base]): returns the natural logarithm of x (to base e or to a given base)
- math.pow(x, y): raise x to the power of y
- math.sqrt(x): returns the square root of x
- math.pi: The mathematical constant π = 3.141592...
- math.e: The mathematical constant e = 2.718281...
import math
r = 1
circ = 2*math.pi*r
area = math.pi*pow(r,2)
vol = 4/3*math.pi*pow(r,3)
area, vol
- exponents and roots
- multiplication and division
- addition and subtraction
When in doubt use parentheses
# An example with more complex operations
x = 5
# Calculating exp(x) by calling math.exp() function
res1 = math.exp(x)
# The exponential function may also be calculated as a Taylor series using also math.factorial()
res2 = 1+x/math.factorial(1)+x**2/math.factorial(2)+x**3/math.factorial(3)+\
x**4/math.factorial(4)+x**5/math.factorial(5)+x**6/math.factorial(6)+\
x**7/math.factorial(7)+x**8/math.factorial(8)+x**9/math.factorial(9)+\
x**10/math.factorial(10)
# Note the use of '\' above to separate one long logical codeline into many physical lines
# The results we get from the two methods are close enough but not similar
# Include more factors in the Taylor series to get a better approximation
res1, res2
. Free learning material
. See full copyright and disclaimer notice