There are several built-in functions in Python. We will discuss some of them below.
Working those Abs
The abs function returns the absolute value of a number. Try the following examples:
>>> print abs(9000)
>>> print abs(-9000)
>>> print abs(12.6)
>>> print abs(-12.6)
Min and Max...Always Comparing
If you need to find the largest or smallest number in a list, you can count on these two fellas to help you do so. Here they both are at work:
>>> print max([100, 200, 2, 4, 900, 6, 8000])
>>> print min(1000, 2000, 2, 1, 19, 80)
Summing Up the Range
If you ever find yourself wanting to sum up a range of numbers, you can do so by combining sum and range, like in the following program, where we calculate 1+2+3+4+5+6+7+8+9:
>>> print sum(range(1, 10))
In addition to the built-in functions, you can also work with modules, some of which we have already been using, like the math module and the decimal module. Here are some of the uses of the math module:
>>> import math
>>> math. sqrt(9)
Remember when using a module to import it first.
Math, unfortunately, ended for me in the ninth grade, so I can't really tell you what all of these functions do, but here is a list of the ones you will find in the math module:
Other modules include the cmath, which is used for complex numbers and has many of the same functions as math, yet returns results as a complex number type; the decimal module, that works with decimal numbers as opposed to floating points; and the random module, which has functions that allow you to generate random numbers and choose randomly from different elements.
Well that's it for this article. Now go forth and do brilliant math stuff with Python. I'll just be slaving away here, hard at work on the next programming tutorial. Check back frequently for another dazzling display from my massive stores of knowledge.
blog comments powered by Disqus