Python Number functions
Here’s a list of commonly used numeric functions in Python, many of which are part of the built-in math
module or native Python functions:
Native Python Numeric Functions
abs(x)
: Returns the absolute value of a numberx
.round(x, n)
: Rounds a numberx
ton
decimal places.max(iterable, *args)
: Returns the largest item in an iterable or the largest of two or more arguments.min(iterable, *args)
: Returns the smallest item in an iterable or the smallest of two or more arguments.sum(iterable, start=0)
: Returns the sum of all items in an iterable, starting with an initial value (default is0
).pow(x, y, z=None)
: Returnsx
raised to the power ofy
; ifz
is provided, it computes(x**y) % z
.divmod(x, y)
: Returns a tuple(quotient, remainder)
when dividingx
byy
.int(x, base=10)
: Convertsx
to an integer, optionally specifying the base (default is base 10).float(x)
: Convertsx
to a floating-point number.complex(real, imag)
: Returns a complex number with the specified real and imaginary parts.
math
Module Functions
To access these functions, you need to import the math
module.
math.sqrt(x)
: Returns the square root ofx
.math.ceil(x)
: Rounds a numberx
upward to the nearest integer.math.floor(x)
: Rounds a numberx
downward to the nearest integer.math.factorial(x)
: Returns the factorial ofx
.math.fabs(x)
: Returns the absolute value ofx
as a float.math.gcd(x, y)
: Returns the greatest common divisor ofx
andy
.math.log(x, base=math.e)
: Returns the logarithm ofx
to the given base. If no base is specified, it defaults to the natural logarithm.math.exp(x)
: Returns the value ofe
raised to the power ofx
.math.log10(x)
: Returns the base-10 logarithm ofx
.math.log2(x)
: Returns the base-2 logarithm ofx
.math.degrees(x)
: Converts an anglex
from radians to degrees.math.radians(x)
: Converts an anglex
from degrees to radians.math.sin(x)
: Returns the sine ofx
(wherex
is in radians).math.cos(x)
: Returns the cosine ofx
(wherex
is in radians).math.tan(x)
: Returns the tangent ofx
(wherex
is in radians).
random
Module (for random number generation)
The random
module provides functions for generating random numbers.
random.random()
: Returns a random float between 0.0 and 1.0.random.randint(a, b)
: Returns a random integer betweena
andb
, inclusive.random.uniform(a, b)
: Returns a random float betweena
andb
.random.choice(sequence)
: Returns a random element from the non-empty sequence (like a list or string).random.sample(population, k)
: Returns a list ofk
unique random elements from the population sequence.
Summary
Python provides a wide range of numeric functions, both built-in and through specialized modules like math
and random
. These functions cover essential mathematical operations, random number generation, and higher-level mathematical operations like logarithms and trigonometry.