Python Tutorial (10) - Number

Time: Column:Python views:308

Python Number Data Types

Python uses number data types to store numerical values.

Data types in Python are immutable, which means that if the value of a number data type changes, memory space will be reallocated.

Here’s an example where Number objects are created when values are assigned to variables:

var1 = 1
var2 = 10

You can also use the del statement to delete the reference to some number objects.

The syntax for the del statement is:

del var1[,var2[,var3[....,varN]]]

You can delete a single or multiple object references, for example:

del var
del var_a, var_b

Python Supports Three Different Numeric Types:

  • Integer (int): Integer values can be positive or negative whole numbers, without decimal points. In Python 3, integers have unlimited precision and can be used as long types.

  • Float (float): Floats consist of an integer part and a fractional part. Floats can also be represented using scientific notation (e.g., 2.5e2 is 2.5 x 10^2, which equals 250).

  • Complex (complex): Complex numbers consist of a real part and an imaginary part and can be represented as a + bj or complex(a, b), where both a (real) and b (imaginary) are floats.

We can represent integers using hexadecimal and octal notation:

number = 0xA0F  # Hexadecimal
print(number)  # Output: 2575

number = 0o37  # Octal
print(number)  # Output: 31

Python Number Type Conversion

Sometimes we need to convert between different data types. Python allows type conversion simply by using the type as a function name.

  • int(x): Converts x to an integer.

  • float(x): Converts x to a float.

  • complex(x): Converts x to a complex number with the imaginary part as 0.

  • complex(x, y): Converts x and y to a complex number with x as the real part and y as the imaginary part.

Example:

a = 1.0
print(int(a))  # Output: 1

Python Numerical Operations

The Python interpreter can act as a simple calculator. Enter an expression, and the interpreter will output its value. Here are some basic examples:

print(2 + 2)         # Output: 4
print(50 - 5 * 6)    # Output: 20
print((50 - 5 * 6) / 4)  # Output: 5.0

In integer division, the / operator always returns a float. If you only want the integer result (i.e., discarding the fraction), use the // operator:

print(17 / 3)  # Output: 5.666666666666667
print(17 // 3)  # Output: 5
print(17 % 3)  # Output: 2

Exponentiation in Python

You can use the ** operator to perform exponentiation:

print(5 ** 2)  # Output: 25 (5 squared)
print(2 ** 7)  # Output: 128 (2 raised to the power of 7)

Mathematical Functions

Functions and Return Values (Description)

  • abs(x): Returns the absolute value of a number. For example, abs(-10) returns 10.

  • ceil(x): Returns the smallest integer greater than or equal to x. For example, math.ceil(4.1) returns 5.

  • cmp(x, y): In Python 2, this function returns -1 if x < y, 0 if x == y, and 1 if x > y. In Python 3, this function has been removed and can be replaced by (x > y) - (x < y).

  • exp(x): Returns e raised to the power of x. For example, math.exp(1) returns 2.718281828459045.

  • fabs(x): Returns the absolute value of a floating-point number. For example, math.fabs(-10) returns 10.0.

  • floor(x): Returns the largest integer less than or equal to x. For example, math.floor(4.9) returns 4.

  • log(x): Returns the natural logarithm of x. For example, math.log(math.e) returns 1.0. You can also specify a base, like math.log(100, 10), which returns 2.0.

  • log10(x): Returns the base-10 logarithm of x. For example, math.log10(100) returns 2.0.

  • max(x1, x2,...): Returns the largest of the given arguments. The arguments can be numbers or sequences.

  • min(x1, x2,...): Returns the smallest of the given arguments. The arguments can be numbers or sequences.

  • modf(x): Returns the fractional and integer parts of x as two separate values, both with the same sign as x. The integer part is returned as a float.

  • pow(x, y): Returns the result of x**y, the value of x raised to the power y.

  • round(x [,n]): Rounds x to the nearest integer. If n is specified, x is rounded to n decimal places.

    Technically, rounding retains the value closer to the higher or lower side based on its proximity.

  • sqrt(x): Returns the square root of x.

Random Number Functions

Random numbers can be used in various fields such as mathematics, gaming, security, and algorithms to improve efficiency and security. Python includes the following common random number functions:

  • choice(seq): Randomly selects an element from a sequence. For example, random.choice(range(10)) randomly selects an integer from 0 to 9.

  • randrange([start,] stop [,step]): Returns a randomly selected element from the specified range with a given step size. The default step size is 1.

  • random(): Generates a random floating-point number in the range [0, 1).

  • seed([x]): Changes the seed of the random number generator. If you don't understand how the seed works, you don't need to set it manually; Python will handle it for you.

  • shuffle(lst): Randomly shuffles the elements of a sequence in place.

  • uniform(x, y): Returns a random floating-point number in the range [x, y].

Trigonometric Functions

Python includes the following trigonometric functions:

  • acos(x): Returns the arc cosine of x in radians.

  • asin(x): Returns the arc sine of x in radians.

  • atan(x): Returns the arc tangent of x in radians.

  • atan2(y, x): Returns the arc tangent of y/x in radians, considering the signs of both arguments.

  • cos(x): Returns the cosine of x, where x is in radians.

  • hypot(x, y): Returns the Euclidean norm, sqrt(x*x + y*y).

  • sin(x): Returns the sine of x, where x is in radians.

  • tan(x): Returns the tangent of x, where x is in radians.

  • degrees(x): Converts x from radians to degrees. For example, degrees(math.pi / 2) returns 90.0.

  • radians(x): Converts x from degrees to radians.

Mathematical Constants

  • pi: The mathematical constant pi, approximately 3.14159, represents the ratio of a circle's circumference to its diameter.

  • e: The mathematical constant e, approximately 2.71828, is the base of the natural logarithm.