Numbers
Here are some built-in functions on numbers:
-
abs(x)
returns the absolute value of a numberx
(or the magnitude of a complex number). -
bin(int)
returns a binary string representation ofint
. -
chr(int)
returns the character whose Unicode representation isint
. The inverse operation isord
. -
divmod(x, y)
returns the tuple (x // y
,x % y
) for integers. -
float(x)
converts a string or integerx
to a floating-point number. -
hex(int)
returns a hexadecimal string representation ofint
. -
int(x)
converts a stringx
to an integer, or truncates a floatx
to an integer. -
oct(int)
returns an octal string representation ofint
. -
pow(x, y)
returnsx
to the powery
. -
round(float)
returns the integer nearest to the givenfloat
value. -
round(float, int)
returnsfloat
rounded toint
digits after the decimal point.
Math
Here are some of the functions you get if you import the math
module:
-
math.ceil(x)
returns the smallest integer greater than or equal tox
. -
math.floor(x)
returns the largest integer smaller than or equal tox
. -
math.trunc(x)
returns the integer value obtained by dropping everything after the decimal point. -
math.sqrt(x)
returns the square root ofx
. -
math.log(x)
andmath.log10(x)
return the natural logarithm and the base 10 logarithm ofx
, respectively. -
All the usual trig functions:
sin
,cos
,acos
,radians
, etc. -
Also in the math library: the constants
math.pi
,math.e
, andmath.tau
.
Random
Here are some of the functions that you get if you import the random
module:
-
random.choice(seq)
returns a randomly chosen element with a replacement from the sequenceseq
. -
random.shuffle(seq)
shuffles the sequenceseq
in place (that is, the original list is changed). -
random.random()
returns a random floating-point number,r
, in the range0.0 ≤ r < 1.0
. -
random.randint(a, b)
returns a random integer,r
, in the rangea ≤ r ≤ b
.
Reminder: If you use the
from module import *
version of theimport
statement, you can leave off themodule
prefix (in this case,math.
andrandom.
).
Get hands-on with 1400+ tech skills courses.