Python Numbers
Python Numbers
Section titled “Python Numbers”Number data types store numeric values. Python supports several types of numbers. They are immutable, meaning operations that change a number’s value actually create a new number object.
Number objects are created simply by assigning a numeric value to a variable:
count = 100 # Integerpi_approx = 3.14 # Floating-point numberscientific = 2.5e2 # Float in scientific notation (2.5 * 10^2 = 250.0)complex_num = 1 + 2j # Complex numberYou can remove the reference to a number object (allowing it to be garbage collected if no other references exist) using the del statement:
del countdel pi_approx, scientific # Delete multiple objectsPython’s Main Numerical Types
Section titled “Python’s Main Numerical Types”int(Integer): Represents positive or negative whole numbers with unlimited precision (arbitrary size). Python automatically handles large integers. Examples:10,-25,0,12345678901234567890.float(Floating-Point Number): Represents real numbers, including those with a decimal point or using exponential notation (eorE). Based on the IEEE 754 standard (typically 64-bit double precision). Examples:3.14,-0.001,1.0,2.5e2(which is 250.0),1.6e-19.complex(Complex Number): Represents numbers with a real and an imaginary part, written asa + bj, wherea(real part) andb(imaginary part) are floats, andj(orJ) represents the square root of -1. Examples:3 + 4j,2j,-5.1 + 0j,1.2 - 3.4J.
Note: The separate long type from Python 2 has been merged into int in Python 3. Integers now automatically handle arbitrary precision.
Examples of Numbers
Section titled “Examples of Numbers”| int | float | complex |
|---|---|---|
10 | 0.0 | 3.14j |
100 | 15.20 | 45.J |
-786 | -21.9 | 9.322e-36j |
0 | 32.3e18 | .876j |
9876543210987654321 | -90. | -.6545+0J |
-500 | -32.54e100 | 3e+26J |
0b101 (Binary 5) | 70.2E-12 | 4.53e-7j |
0o17 (Octal 15) | float('inf') | complex(2, -3) |
0xFF (Hex 255) | float('-inf') | complex('1+2j') |
Number Type Conversion
Section titled “Number Type Conversion”Python automatically converts numbers between types during operations (e.g., int + float results in float). You can also explicitly convert between types using built-in functions:
int(x): Convertsxto an integer. For floats, it truncates towards zero. For strings,xmust represent a whole number (optionally specify base:int('FF', 16)).float(x): Convertsxto a floating-point number. Works for integers and compatible strings.complex(real [,imag]): Creates a complex number.realcan be int, float, or string.imag(optional) must be numeric.complex('1+2j')also works.
print(int(3.9)) # Output: 3print(int("101", 2)) # Output: 5 (binary to int)print(float(5)) # Output: 5.0print(float("-1.5e2")) # Output: -150.0print(complex(3, -4)) # Output: (3-4j)print(complex("5-6j")) # Output: (5-6j)Mathematical Functions (from math module)
Section titled “Mathematical Functions (from math module)”Python’s math module provides access to many common mathematical functions. You need to import it first (import math).
| Function | Description |
|---|---|
math.fabs(x) | Returns the absolute value of x as a float. |
abs(x) | Built-in function, returns absolute value (int if x is int, float if float). |
math.ceil(x) | Returns the ceiling of x (smallest integer >= x). |
math.floor(x) | Returns the floor of x (largest integer <= x). |
math.exp(x) | Returns e raised to the power x (ex). |
math.log(x [, base]) | Returns the logarithm of x to the given base. If base is omitted, returns the natural logarithm (base e). |
math.log10(x) | Returns the base-10 logarithm of x. |
max(x1, x2, ...) | Built-in function, returns the largest of its arguments. |
min(x1, x2, ...) | Built-in function, returns the smallest of its arguments. |
math.modf(x) | Returns the fractional and integer parts of x as a tuple (frac, int). Both parts have the same sign as x. Integer part is returned as a float. |
pow(x, y) | Built-in function, returns x raised to the power y (x**y). More precise than math.pow for integer x. |
math.pow(x, y) | Returns x raised to the power y. Always returns a float. |
round(x [, n]) | Built-in function, rounds x to n decimal places. Rounds to nearest even number for ties (e.g., round(2.5) is 2, round(3.5) is 4). |
math.sqrt(x) | Returns the square root of x (for x >= 0). |
Note: The cmp(x, y) function from Python 2 is removed. Use comparison operators (<, >, ==, etc.) instead.
Random Number Functions (from random module)
Section titled “Random Number Functions (from random module)”The random module provides functions for generating pseudo-random numbers, useful in simulations, games, testing, and sampling.
| Function | Description |
|---|---|
random.choice(seq) | Returns a random element from a non-empty sequence (list, tuple, string). |
random.randrange(stop) or randrange(start, stop [, step]) | Returns a randomly selected element from range(start, stop, step). |
random.random() | Returns a random float r such that 0.0 <= r < 1.0. |
random.seed(a=None, version=2) | Initializes the random number generator. Use this for reproducible results. |
random.shuffle(lst) | Shuffles the items of a list lst in place. Returns None. |
random.uniform(a, b) | Returns a random float r such that a <= r <= b for a <= b or b <= r <= a for b < a. |
random.randint(a, b) | Returns a random integer n such that a <= n <= b. |
Trigonometric Functions (from math module)
Section titled “Trigonometric Functions (from math module)”The math module also includes standard trigonometric functions. Angles are typically expected in radians.
| Function | Description |
|---|---|
math.acos(x) | Return the arc cosine of x, in radians. (x must be -1 to 1). |
math.asin(x) | Return the arc sine of x, in radians. (x must be -1 to 1). |
math.atan(x) | Return the arc tangent of x, in radians. |
math.atan2(y, x) | Return atan(y / x), in radians. Correctly handles quadrants. |
math.cos(x) | Return the cosine of x radians. |
math.hypot(*coordinates) | Return the Euclidean norm, sqrt(x*x + y*y + ...). |
math.sin(x) | Return the sine of x radians. |
math.tan(x) | Return the tangent of x radians. |
math.degrees(x) | Converts angle x from radians to degrees. |
math.radians(x) | Converts angle x from degrees to radians. |
Mathematical Constants (from math module)
Section titled “Mathematical Constants (from math module)”The math module defines important constants:
| Constant | Description |
|---|---|
math.pi | The mathematical constant pi (π ≈ 3.14159…) |
math.e | The mathematical constant e (e ≈ 2.71828…) |
math.tau | The mathematical constant tau (τ = 2π ≈ 6.28318…) |
math.inf | Floating-point positive infinity. |
math.nan | Floating-point ‘Not a Number’. |