Python has thousands of libary functions pre-written for you to use. They a grouped into modules, which can be imported.
We specify the module name when we use the function or constant, as in
import math # math gets you sin, cos
y = math.sin(0.6)
x = math.cos(0.4)
print math.pi # prints 3.1415...etc...
You will need to do a search of the python documentation to see the full range of modules. Use your
Python system, or:
http://docs.python.org/modindex.html
Here we will provide a short list of the more common functions used in intro programs.
Built-in functions
These need not be imported. Look at the Lists page for details of
len max min range len
We also have:
f = float("12.34") # converts string to a decimal (float) number
f = float(12) # changes int (whole number) into a decimal (i.e 12.0)
x = pow(a, b) # a to the power b
x = round(y) # rounds to nearest integer (0.5 goes to number above)
s = str(n) # converts n into a string
Libraries
The string library has useful stuff for case conversion, searching,
splitting strings into separate items, etc
The random library:
import random
x = random.randint(0,3) # random integer in range 0 to 3 inclusive
x = random.choice( ["up", "down", "left", "right"] ) # random choice from list,
# tuple, or string
| |