Python入门教程 | Python 数字(Number)

Python3 数字(Number)

Python 数字数据类型用于存储数值。

数据类型是不允许改变的,这就意味着如果改变数字数据类型的值,将重新分配内存空间。

以下实例在变量赋值时 Number 对象将被创建:

var1 = 1
var2 = 10

您也可以使用del语句删除一些数字对象的引用。

del语句的语法是:

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

您可以通过使用del语句删除单个或多个对象的引用,例如:

del var
del var_a, var_b

Python 支持三种不同的数值类型:

  • 整型(int) - 通常被称为是整型或整数,是正或负整数,不带小数点。Python3 整型是没有限制大小的,可以当作 Long 类型使用,所以 Python3 没有 Python2 的 Long 类型。布尔(bool)是整型的子类型。

  • 浮点型(float) - 浮点型由整数部分与小数部分组成,浮点型也可以使用科学计数法表示(2.5e2 = 2.5 x 102 = 250)

  • 复数( (complex)) - 复数由实数部分和虚数部分构成,可以用a + bj,或者complex(a,b)表示, 复数的实部a和虚部b都是浮点型。

我们可以使用十六进制和八进制来代表整数:

C:\Users\Lenovo>python
Python 3.11.4 (tags/v3.11.4:d2340ef, Jun  7 2023, 05:45:37) [MSC v.1934 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> 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支持复数,复数由实数部分和虚数部分构成,可以用a + bj,或者complex(a,b)表示, 复数的实部a和虚部b都是浮点型。

Python 数字类型转换

有时候,我们需要对数据内置的类型进行转换,数据类型的转换,你只需要将数据类型作为函数名即可。

  • int(x) 将x转换为一个整数。

  • float(x) 将x转换到一个浮点数。

  • complex(x) 将x转换到一个复数,实数部分为 x,虚数部分为 0。

  • complex(x, y) converts x and y to a complex number with real part x and imaginary part y. x and y are numeric expressions.

The following example converts the floating-point variable a to an integer:

a = 1.0
int(a)
#输出结果为1

Python number crunching

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 of expressions is straightforward: +, -, * and /, 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 : The results of floating-point operations may vary on different machines.
In integer division, division / always returns a floating-point number. If you only want the integer result and discard possible fractional parts, you can use the operator // :

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

Note : // The number obtained is not necessarily an integer type, it is related to the data type of the denominator and numerator.

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

The equals sign = is used to assign values ​​to variables. After the assignment, the interpreter will not display any results except at the next prompt.

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

Python can perform exponentiation using the ** operator:

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

A variable must be "defined" (that is, assigned a value) before it can be used, otherwise an error will occur:

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

When mixing numbers of different types, integers are converted to floating-point numbers:

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

In interactive mode , the last output expression result 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

In Python, the variable _ is a special variable name. It is often used as a placeholder variable for temporary values ​​that are not needed or for results that are not of interest. In an interactive environment, the variable _ holds the result of the previous expression. The first variable_value is 12.5625, the second variable_value is 113.0625, and the third variable_value is 113.06.

math function

function return value (description)
abs(x) Returns the absolute value of a number, such as abs(-10) returns 10
ceil(x) Returns the upper integer of the number, such as math.ceil(4.1) returns 5
cmp(x, y) Returns -1 if x < y, 0 if x == y, and 1 if x > y. Deprecated in Python 3, use (x>y)-(x<y) instead.
exp(x) Returns the x power of e (ex), such as math.exp(1) returns 2.718281828459045
fabs(x) Returns the absolute value of a number as a floating point number, such as math.fabs(-10) returns 10.0
floor(x) Returns the rounded integer of a number, such as math.floor(4.9) returns 4
log(x) Such as math.log(math.e) returns 1.0, math.log(100,10) returns 2.0
log10(x) Returns the logarithm of x in base 10, such as math.log10(100) returns 2.0
max(x1, x2,…) Returns the maximum value of the given argument, which can be a sequence.
min(x1, x2,…) Returns the minimum value of the given argument, which can be a sequence.
modf(x) Returns the integer part and fractional part of x. The numerical signs of the two parts are the same as x, and the integer part is represented by floating point.
pow(x, y) The value after x**y operation.
round(x [,n]) Returns the rounded value of the floating-point number x, or, if n is given, the number of digits rounded to the decimal point. In fact, it is accurate to say that the reserved value will be reserved to the end closer to the previous one.
sqrt(x) Returns the square root of the number x.

Code example:

>>> abs(-3.14)
3.14
>>> import math
>>> math.exp(1)
2.718281828459045
>>> math.floor(4.9)
4
>>> round(3.1415926,2)
3.14
>>> math.sqrt(4)
2.0

random number function

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

Python includes the following commonly used random number functions:

function describe
choice(seq) Randomly picks an element from the elements of the sequence, such as random.choice(range(10)), randomly picks an integer from 0 to 9.
randrange ([start,] stop [,step]) Obtain a random number from the set within the specified range and incremented by the specified radix, the default value of the radix is ​​1
random() Randomly generate the next real number, which is in the range [0,1).
seed([x]) Change the seed of the random number generator. If you don't understand its principle, you don't have to set the seed specifically, Python will help you choose the seed.
shuffle(lst) randomize all elements of a sequence
uniform(x, y) Randomly generate the next real number in the range [x,y].

Code example:

>>> import random
>>> random.random()
0.2706490710582149
>>> random.random()
0.86297192521551
>>> random.uniform(1, 10)
2.720386640900577
>>> random.uniform(1, 10)
7.854237135368386

Trigonometric functions

Python includes the following trigonometric functions:

function describe
acos(x) Returns the arccosine radian value of x.
asin(x) Returns the arcsine of x in radians.
time(x) Returns the arctangent of x in radians.
atan2(y, x) Returns the arctangent 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) Convert radians to angles, such as degrees(math.pi/2), return 90.0
radians(x) Convert angles to radians

Code example:

>>> import random
>>> random.random()
0.2706490710582149
>>> random.random()
0.86297192521551
>>> random.uniform(1, 10)
2.720386640900577
>>> random.uniform(1, 10)
7.854237135368386

Code example:

>>> import math
>>>
>>> # Define a variable for the argument of acos
>>> argument = 0.5
>>>
>>> # Calculate the value of acos using the argument
>>> result = math.acos(argument)
>>>
>>> print(result)
1.0471975511965979
>>> math.asin(argument)
0.5235987755982989
>>> math.atan(argument)
0.4636476090008061

mathematical constant

constant describe
pi The mathematical constant pi (pi, generally expressed in π)
e The mathematical constant e, e is the natural constant (natural constant)

Code example:

>>> import math
>>> math.pi
3.141592653589793
>>> math.e
2.718281828459045

Guess you like

Origin blog.csdn.net/weixin_40986713/article/details/132580124