Python contains a large library of standard functions which can be used for common programming tasks. You can also create your own (see Section 3.11, ``Making Functions''). A function is just some Python code which is seperated from the rest of the program. This has several advantages: Repeated sections of code can be re-used without rewriting them many times, making your program clearer. Furthermore, if a function is separated from the rest of the program it provides a conceptual separation for the person writing it, so they can concentrate on either the function, or the rest of the program.
Python has some built-in functions, for example
range() that we have already used. These are available to any Python
To use a function we call it. To do this you type its name, followed by the required parameters enclosed in parentheses. Parameters are sometimes called arguments, and are similar to arguments in mathematics. In maths, if we write , we are using the function with the argument . Functions in computing often need more than one variable to calculate their result. These should be separated by commas, and the order you give them in is important. Refer to the discussion of the individual functions for details.
Even if a function takes no parameters (you will see examples of such functions later), the parentheses must be included.
However, the functions in the library are contained in separate modules, similar to the ones you have been writing and saving in the editor so far. In order to use a particular module, you must explicitly import it. This gives you access to the functions it contains.
The most useful module for us is the
math library3.11. If you want to use the functions it contains,
put the line
from math import * at the top of your program.
math functions are then accesible in the same way as the
built in functions. For example, to calculate the and of
we would write a module like this:
from math import * mynumber = pi / 3 print sin(mynumber) print cos(mynumber)
math module contains many functions, the most useful of which
are listed below. Remember that to use them you must
||Returns the square root of|
||Returns the natural log, i.e.|
||Returns the log to the base 10 of|
||Returns the sine of|
||Return the cosine of|
||Returns the tangent of|
||Return the arc sine of|
||Return the arc cosine of|
||Return the arc tangent of|
||Return the absolute value, i.e. the modulus, of|
||Rounds a float down to its integer|
math library also contains two constants:
pi, , and
e, . These do not require parentheses (see the above example).
floor function always rounds down which can produced
unexpected results! For example
>>> floor(-3.01) -4.0
math library to write a program to print out the
and of numbers from 0 to in intervals of . You will
need to use the
math''. Modern computer languages are generally written according to US English spelling conventions. You do the math!