Python 3 Numbers
Python 3 Numbers
Python Number data types are used to store numerical values.
Data types are immutable, meaning that changing the value of a number data type will cause memory to be reallocated.
In the following example, a Number object is created when a variable is assigned a value:
var1 = 1
var2 = 10
You can also use the del statement to delete references to number objects.
The syntax of the del statement is:
del var1[,var2[,var3[....,varN]]]
You can use the del statement to delete references to single or multiple objects. For example:
del var
del var_a, var_b
Python supports three different numeric types:
- Integer (Int) – Integers, commonly referred to as integers, are positive or negative whole numbers without decimal points. Python 3 integers have no size restrictions and can be used as long types, so Python 3 lacks the Python 2 long type.
- Floating-point type (float) – A floating-point type consists of an integer part and a decimal part. Floating-point types can also be expressed in scientific notation (2.5e² = 2.5 x 10² = 250).
- Complex number (complex) – A complex number consists of a real part and an imaginary part. It can be expressed as a + bj or complex(a,b). Both the real part a and the imaginary part b of a complex number are floating-point types.
We can use hexadecimal and octal to represent integers:
>>> number = 0xA0F # Hexadecimal
>>> number
2575
>>> number = 0o37 # Octal
>>> number
31
int | float | complex |
---|---|---|
10 | 0.0 | 3.14j |
100 | 15.20 | 45.j |
-786 | -21.9 | 9.322e-36j |
080 | 32.3e+18 | .876j |
-0490 | -90. | -.6545+0J |
-0x260 | -32.54e100 | 3e+26J |
0x69 | 70.2E-12 | 4.53e-7j |
- Python supports complex numbers. Complex numbers consist of real and imaginary parts, which can be represented by a + bj, or complex(a,b),
The real part a and imaginary part b of a complex number are both floating-point types.
Python Number Type Conversion
Sometimes, we need to convert data types to built-in types. To convert data types, you simply use the data type as the function name.
- int(x) Converts x to an integer.
-
float(x) Converts x to a floating-point number.
-
complex(x) Converts x to a complex number with the real part x and the imaginary part 0.
-
complex(x, y) Converts x and y to a complex number, with the real part being x and the imaginary part being y. x and y are numeric expressions.
The following example converts a floating-point variable a to an integer:
>>> a = 1.0
>>> int(a)
1
Python Numerical Operations
The Python interpreter can be used as a simple calculator; you can enter an expression into the interpreter, and it will output the value of the expression.
The syntax for expressions is straightforward: +, -, *, and /, just like in other languages like Pascal or C. For example:
>>> 2 + 2
4
>>> 50 - 5*6
20
>>> (50 - 5*6) / 4
5.0
>>> 8 / 5 # Always returns a floating point number
1.6
Note: The results of floating point operations may vary on different machines.
In integer division, the / operator always returns a floating-point number. If you only want an integer result, discarding any fractional parts, you can use the // operator:
>>> 17 / 3 # Integer division returns a floating-point number
5.6666666666666667
>>>
>>> 17 // 3 # Integer division returns the result after rounding down
5
>>> 17 % 3 # The % operator returns the remainder of the division
2
>>> 5 * 3 + 2
17
Note: The result of // is not necessarily an integer; it depends on the data type of the numerator and denominator.
>>> 7//2
3
>>> 7.0//2
3.0
>>> 7//2.0
3.0
>>>
The equal sign = is used to assign a value to a variable. After the assignment, the interpreter does not display any results except at the next prompt.
>>> width = 20
>>> height = 5*9
>>> width * height
900
Python can use the ** operator to perform exponentiation:
>>> 5 ** 2 # 5 squared
25
>>> 2 ** 7 # 2 to the power of 7
128
Variables must be “defined” (i.e., assigned a value) before use, otherwise an error will occur:
>>> n # Attempt to access an undefined variable
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'n' is not defined
When combining different types of numbers, integers are converted to floating-point numbers:
>>> 3 * 3.75 / 1.5
7.5
>>> 7.0 / 2
3.5
In interactive mode, the result of the expression printed last is assigned to the variable _. For example:
>>> tax = 12.5 / 100
>>> price = 100.50
>>> price * tax
12.5625
>>> price + _
113.0625
>>> round(_, 2)
113.06
Here, the _ variable should be treated as read-only by the user.
Mathematical Functions
Function | Return Value (Description) |
---|---|
abs(x) | Returns the absolute value of a number, e.g., abs(-10) returns 10 |
ceil(x) | Returns the upper bound of a number, e.g., math.ceil(4.1) returns 5 |
cmp(x, y) | Returns -1 if x < y, 0 if x == y, and 1 if x > y. Obsolete in Python 3, use (x>y)-(x |
exp(x) | Returns e raised to the power of x (ex), such as math.exp(1) returns 2.718281828459045 |
fabs(x) | Returns the absolute value of a number, such as math.fabs(-10) returns 10.0 |
floor(x) | Returns the rounded-down integer of a number, such as math.floor(4.9) returns 4 |
log(x) | For example, math.log(math.e) returns 1.0, and math.log(100,10) 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 maximum value of the given argument. The argument can be a sequence. |
min(x1, x2,…) | Returns the minimum value of the given argument. The argument can be a sequence. |
modf(x) | Returns the integer and fractional parts of x. Both parts have the same sign as x, and the integer part is expressed as a floating-point number. |
pow(x, y) | The value after the operation x**y. |
round(x [,n]) |
Returns the rounded value of the floating-point number x. If n is given, it represents the number of decimal places to round to. |
sqrt(x) | Returns the square root of the number x. |
Random Number Functions
Random numbers can be used in mathematics, games, security, and other fields. They are also often embedded in algorithms to improve algorithm efficiency and enhance program security.
Python includes the following commonly used random number functions:
Function | Description |
---|---|
choice(seq) | Randomly select an element from the elements of a sequence, such as random.choice(range(10)), which randomly selects an integer from 0 to 9. |
randrange ([start,] stop [,step]) | Get a random number from the specified range, increasing by the specified base. The default base is 1. |
random() | Generates the next random real number in the range [0,1). |
seed([x]) | Changes the seed of the random number generator. If you don’t understand how this works, you don’t need to specify the seed; Python will choose it for you. |
shuffle(lst) | Shuffle all elements of a sequence. |
uniform(x, y) | Generate the next random real number in the range [x, y]. |
Trigonometric Functions
Python includes the following trigonometric functions:
Function | Description |
---|---|
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 the given x and y coordinates. |
cos(x) | Returns the cosine of x in radians. |
hypot(x, y) | Returns the Euclidean norm sqrt(x*x + y*y). |
sin(x) | Returns the sine of x in radians. |
tan(x) | Returns the tangent of x in radians. |
degrees(x) | Converts radians to degrees, such as degrees(math.pi/2) , which returns 90.0. |
radians(x) | Converts degrees to radians. |
Mathematical Constants
Constant | Description |
---|---|
pi | Mathematical Constant pi (pi, usually denoted as π) |
e | Mathematical Constant e, e is also known as the natural constant. |