Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python3 Numbers (Number)

Python3 Numbers (Number)

The Python number data type is used to store numeric values.

Number data types are immutable, which means that changing the value of a number data type reallocates memory.

In the following example, Number objects are created when variables are assigned:


var1 = 1
var2 = 10

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

The syntax of the del statement is:


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

You can use the del statement to delete references to a single object or multiple objects, for example:


del var
del var_a, var_b

Python supports three different numeric types:

We can use hexadecimal and octal notation to represent integers:


>>> number = 0xA0F # 十六进制
>>> number
2575

>>> number=0o37 # 八进制
>>> 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 number type conversion

Sometimes we need to convert built-in data types; to convert a data type you simply use the type as a function name.

The following example converts a float variable a to an integer:


>>> a = 1.0
>>> int(a)
1

Python Number Operations

The Python interpreter can be used as a simple calculator: you enter an expression and it outputs the value of the expression.

The syntax of expressions is straightforward: +, -, * and /, just as in other languages (such as Pascal or C). For example:


>>> 2 + 2
4
>>> 50 - 5*6
20
>>> (50 - 5*6) / 4
5.0
>>> 8 / 5  # 总是返回一个浮点数
1.6

**Note:** Floating-point results may differ on different machines.

In integer division, / always returns a float; if you only want an integer result and want to discard any fractional part, use the // operator:


>>> 17 / 3  # 整数除法返回浮点型
5.666666666666667
>>>
>>> 17 // 3  # 整数除法返回向下取整后的结果
5
>>> 17 % 3  # %操作符返回除法的余数
2
>>> 5 * 3 + 2 
17

Note:The result of // is not necessarily of integer type; it depends on the data types of the numerator and denominator.

>>> 7//2
3
>>> 7.0//2
3.0
>>> 7//2.0
3.0
>>> 

The equals sign = is used to assign a value to a variable. After an assignment, the interpreter displays nothing except the next prompt.


>>> width = 20
>>> height = 5*9
>>> width * height
900

Python can use the ** operator for exponentiation:


>>> 5 ** 2  # 5 的平方
25
>>> 2 ** 7  # 2的7次方
128

A variable must be "defined" (that is, given a value) before use, otherwise an error occurs:


>>> n   # 尝试访问一个未定义的变量
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'n' is not defined

When mixing numbers of different types in an operation, integers are converted to floats:


>>> 3 * 3.75 / 1.5
7.5
>>> 7.0 / 2
3.5

In interactive mode, the result of the last printed expression 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 by the user as read-only.


Mathematical functions

function Return value ( description )
abs(x) Return the absolute value of a number, e.g. abs(-10) returns 10
ceil(x) Return the ceiling of a number, e.g. math.ceil(4.1) returns 5

cmp(x, y)

If x < y returns -1, if x == y returns 0, if x > y returns 1. Deprecated in Python 3, use (x>y)-(x.
exp(x) Return e raised to the power x (ex), e.g. math.exp(1) returns 2.718281828459045
fabs(x) Return the absolute value of a number as a float, e.g. math.fabs(-10) returns 10.0
floor(x) Return the floor of a number, e.g. math.floor(4.9) returns 4
log(x) e.g. math.log(math.e) returns 1.0 and math.log(100,10) returns 2.0
log10(x) Return the base-10 logarithm of x, e.g. math.log10(100) returns 2.0
max(x1, x2,...) Return the maximum of the given arguments; the argument can be a sequence.
min(x1, x2,...) Return the minimum of the given arguments; the argument can be a sequence.
modf(x) Return the integer and fractional parts of x; both have the same sign as x, and the integer part is returned as a float.
pow(x, y) The value of x**y.
round(x [,n])

Return the rounded value of the float x; if n is given, it means the number of digits after the decimal point.

To be precise, the retained value is rounded to the end closer to the previous digit.

sqrt(x) Returns the square root of a number x.

Random number functions

Random numbers are used in mathematics, games, security and other fields, and are often embedded into algorithms to improve efficiency and program security.

Python includes the following common random number functions:

function Description
choice(seq) Randomly pick an element from a sequence, e.g. random.choice(range(10)) picks a random integer from 0 to 9.
randrange ([start,] stop [,step]) Get a random number from a collection in a specified range increasing by a specified base; the base defaults to 1
random() Randomly generate the next real number in the range [0,1).
seed([x]) Change the seed of the random number generator. If you do not understand how it works, you need not set the seed yourself; Python will choose it for you.
shuffle(lst) Randomly shuffle all elements of a sequence
uniform(x, y) Randomly generate the next 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 coordinate values.
cos(x) Returns the cosine of x radians.
hypot(x, y) Returns the Euclidean norm sqrt(xx + yy)。
sin(x) Returns the sine of x radians.
tan(x) Return the tangent of x radians.
degrees(x) Convert radians to degrees, e.g. degrees(math.pi/2) returns 90.0
radians(x) Convert degrees to radians

Mathematical constants

Constant Description
pi The mathematical constant pi (the ratio of a circle's circumference to its diameter, usually denoted by pi)
e The mathematical constant e, that is, the natural constant (Euler's number).