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) 9000 >>> print abs(-9000) 9000 >>> print abs(12.6) 12.6 >>> print abs(-12.6) 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]) 8000 >>> print min(1000, 2000, 2, 1, 19, 80) 1 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)) 45 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: Square Root >>> import math >>> math.sqrt(3) 1.7320508075688772 >>> math. sqrt(9) 3.0 >>> math.sqrt(32) 5.6568542494923806 >>> math.sqrt(1200) 34.641016151377549 >>> Remember when using a module to import it first. Exponentiation >>> math.exp(12) 162754.79141900392 >>> math.exp(1) 2.7182818284590451 >>> math.exp(50) 5.184705528587072e+021 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. Conclusion 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. Till then...
blog comments powered by Disqus |
|
|
|
|
|
|
|