Numerical Functions

Learn about the different numerical functions available in Python.

We'll cover the following

Numbers

Here are some built-in functions on numbers:

  • abs(x) returns the absolute value of a number x (or the magnitude of a complex number).

  • bin(int) returns a binary string representation of int.

  • chr(int) returns the character whose Unicode representation is int. The inverse operation is ord.

  • divmod(x, y) returns the tuple (x // yx % y) for integers.

  • float(x) converts a string or integer x to a floating-point number.

  • hex(int) returns a hexadecimal string representation of int.

  • int(x) converts a string x to an integer, or truncates a float x to an integer.

  • oct(int) returns an octal string representation of int.

  • pow(x, y) returns x to the power y.

  • round(float) returns the integer nearest to the given float value.

  • round(float, int) returns float rounded to int 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 to x.

  • math.floor(x) returns the largest integer smaller than or equal to x.

  • math.trunc(x) returns the integer value obtained by dropping everything after the decimal point.

  • math.sqrt(x) returns the square root of x.

  • math.log(x) and math.log10(x) return the natural logarithm and the base 10 logarithm of x, respectively.

  • All the usual trig functions: sin, cos, acos, radians, etc.

  • Also in the math library: the constants math.pi, math.e, and math.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 sequence seq.

  • random.shuffle(seq) shuffles the sequence seq in place (that is, the original list is changed).

  • random.random() returns a random floating-point number, r, in the range 0.0 ≤ r < 1.0.

  • random.randint(a, b) returns a random integer, r, in the range a ≤ r ≤ b.

Reminder: If you use the from module import * version of the import statement, you can leave off the module prefix (in this case, math. and random.).

Get hands-on with 1400+ tech skills courses.