python numeric types

Aug 07, 2017 pm 12:28 PM
python number type

The following editor will bring you a brief discussion of digital types and processing tools in Python. The editor thinks it’s pretty good, so I’ll share it with you now and give it as a reference. Let’s follow the editor and take a look

Number type tools in python

Python provides a lot of advanced numerical programming for more advanced work Support and objects, including complete tools for numeric types:

1. Integers and floating point types,

2. Complex numbers,

3. Fixed-precision decimal numbers,

4. Rational fractions,

5. Sets,

6. Boolean type

7. Infinite integer precision

8. Various digital built-in functions and modules.

Basic number types

Python provides two basic types: integers (positive integers, negative integers) and floating point numbers (Note: Numbers with decimal parts), where in python we can use integers in multiple bases. And integers can be used with infinite precision.

The integer is expressed in decimal number string writing, and the floating point number is represented by a decimal point or scientific notation e. In the python2 version, integers are also divided into general integers (32 bits) and long integers (infinite precision). Long integers end with l. With python3, integers have only one form, with infinite precision.

Of course, integers in Python also appear in binary (0bxxxxxxxx), octal (0oxxxxxxxx), and hexadecimal (0x xxxxxxxx) forms.

Conversion between decimal numbers and other bases:


s=16
print(bin(s))
print(oct(s))
print(hex(s))

运行结果:
0b10000
0o20
0x10
Copy after login


print('{0:o},{1:x},{2:b}'.format(16,16,16))
print('%o,%x,%X'%(16,16,16))
运行结果:
20,10,10000
20,10,10
Copy after login

Conversion of other bases into decimal:


a=int('0b10000',2)
b=int('0o20',8)
c=int('0x10',16)
print(a)
print(b)
print(c)
运行结果:
16
16
16
Copy after login


print(eval('16'))
print(eval('0b10000'))
print(eval('0o20'))
print(eval('0x10'))
运行结果:
16
16
16
16
Copy after login

python expression operator

The expression is Mathematical symbols and operation symbols are written. The following table shows python expression operators and procedures:

##x&ybit and, set intersection##x<>y##x+y,x-yAddition, subtraction, merge and deletex*y,x%y,x/y,x//yMultiplication, remainder, division, floor division-x,+xUnary subtraction~xBitwise complement (reverse)x**yPower operationx[i]Index, function callx[i:j:k]Shardingx(...)Calling functionx.attrCalling attributes(...)Tuple, expression, generator[...]List, list parsing{...}Dictionary ,sets,sets and dictionary parsing

:操作符在python2和python3中略有不同,python2中不等于用!=或》<>来表示,在python3中<>方法被取消,不等于就用!=来表示。

x

在python2中可以使用混合类型,在python3中比较混合类型大小是会报错的,


python2
a = 1 > &#39;a&#39;
print a
运行结果:
False
Copy after login


python3<br>a=1 > &#39;a&#39;
print(a)
运行结果:
Traceback (most recent call last):
 File "C:/Users/jeff/PycharmProjects/python_file/practice/prac2.py", line 92, in <module>
 a=1 > &#39;a&#39;
TypeError: unorderable types: int() > str()
Copy after login

上面的表格也是程序运行的优先级表格,自上而下,优先级越来越高,当然如果想要改变优先级,要是用括号来做。括号在python数字操作中经常会使用到,他不仅强制程序按照你想要的顺序运行,同时也增加了程序的可读性。

混合类型

这里指的是混合数字类型,比如整数和浮点数相加的结果是什么呢?

其实在python中首先将备操作对象转换成其中最复杂的操作对象的类型,然后再进行相同类型的对象进行数学运算。


print(1+0.2)

运行结果:
1.2
Copy after login

注:除此之外,在python中还存在着运算符重载功能比如‘+',除了做数字加法运算,在字符串拼接时也适用‘+'。

数字显示格式

由于一些硬件限制,数字显示有时看起来会很奇怪,例如:


在命令行中操作
>>>num = 1 / 3.0
>>>num
0.333333333333333333331
在pycharm中print操作
num = 1/3.0
print(num)
运行结果:
0.3333333333333333
num = 1/3.0
print(&#39;{0:4.2f}&#39;.format(num))#4是前面空格格数,2是保留小数位
运行结果:
0.33
Copy after login

在命令行中显示的形式叫做默认的交互式回显,而print打印的叫做友好式回显,与reper和str的显示是一致的:


>>>num = 1/3.0
>>>repr(num)
0.333333333333333333331
>>>str(num)
0.3333333333333333
Copy after login

除法:传统除法,floor除法,真除法和截断除法

除法是python2与python3之间非常重要的一个变化。

一、除法操作符

python有两种除法操作符‘x/y'与‘x//y',其中‘/'在python2中是传统除法,即省略浮点数小数部分,然而显示整数,在python3中,除法就是真除法,即无论什么类型都会保留小数部分;‘//'也叫作floor除法,在python3中省略小数部分,剩下最小的能整除的整数部分,操作数如果是浮点数则结果显示浮点数,python2中整数截取整数,浮点数执行保留浮点数。

例:在python2中:

在python3中:

在python2中若是想要使用python3中的'/'则需要调用模块来完成,在python2中调用pision模块:

截断除法与floor除法一样都是取最接近整数向下取整,这使得在负数时也生效,即-2.5则为-3,而不是-2,想要得到真正的截取需要调用math模块:

python还支持复数的计算:

还支持compliex(real,imag)来创建复数。

更多复数计算参考模块cmath的参考手册。

位操作


x=1
print(x<<2)
print(x|2)
print(x&2)
print(x^2)
运行结果:
3
3
Copy after login

python3中使用bit_length查看二进制位数:


x=99
print(bin(x))
print(x.bit_length())
print(len(bin(x))-2)
运行结果:
0b1100011
7
7
Copy after login

内置数学工具

math模块


import math
print(math.pi)
print(math.e)
print(math.sin(110))
print(math.sqrt(144))
print(pow(2,3))
print(abs(-50))
print(sum((1,2,3)))
print(max(1,2,3))
print(min(1,2,3))
运行结果:
3.141592653589793
2.718281828459045
-0.044242678085070965
12.0
8
50
6
3
1
Copy after login

对于截取浮点数的操作有四种方式:


print(math.floor(2.577))
print(math.trunc(2.577))
print(round(2.577))
print(int(2.577))
运行结果:
2
2
3
2
Copy after login

random模块

获取随机数


import random
print(random.random())
print(random.randint(1,100))
运行结果:
0.9534845221467178
79
Copy after login

其他数字类型介绍

除了常见的整型与浮点数,还有一些其他较为常见的数字类型。

一、小数数字

虽然学习python有一段时间了,但是确实没有太明白浮点数与小数的区别,其实小数在某种程度上就是浮点数,只不过他有固定的位数和小数点,在python中有专门的模块导入小数,from decimal import Decimal。

注:浮点数缺乏精确性。


print(0.1+0.1+0.1-0.3)
输出结果:
5.551115123125783e-17
Copy after login

我想看到这里的兄弟可能已经慌了,然后使用python解释器试了一下,果然结果就是5.551115123125783e-17虽然很接近0,但是不是0。所以说浮点型本质是缺乏精确性。要精确就需要调用from decimal import Decimal。


from decimal import Decimal
print(Decimal(&#39;0.1&#39;)+Decimal(&#39;0.10&#39;)+Decimal(&#39;0.10&#39;)-Decimal(&#39;0.30&#39;))
运行结果:
0.00
Copy after login

可以看出来小数相加也是自动升级为位数最多的。

注:浮点数创建小数对象,由于浮点数本身可能就不精确所以转换会产生较多的位数。


from decimal import Decimal
print(Decimal.from_float(1.88))
print(Decimal.from_float(1.25))
输出结果:
1.87999999999999989341858963598497211933135986328125
1.25
Copy after login

二、分数

分数类型与小数极为相似,他们都是通过固定小数位数和指定舍入或截取策略控制精度。分数使用Fraction模块导入。


from fractions import Fraction
x=Fraction(1,3)
y=Fraction(2,3)
print(x+y)
输出结果:
1
Copy after login

注:对于内存给定有限位数无法精确表示的值,浮点数的局限尤为明显。分数和小数都比浮点数更为准确。

三、集合

集合是无序元素组成,打印时顺序也是无序的,但是集合中没有重复的元素,所以我们常使用集合去重,尤其是在涉及数字和数据库的工作中。

我们有两个集合a与b:

a与b的交集为a.intersection(b)或者a & b。

a与b的差集为a.difference(b)或者a-b。

a与b的并集为a.union(b)或者a|b。

反向差集与对称差集(并集减去交集)为a.symmetric_difference(b)或者a^b。

合并为a.update(b),a.difference_update(b)求差集并赋值给a集合

删除元素可用discard(元素)或者remove(元素),pop()是随机删除一个元素,add插入一个项目。

注:set是可变数据类型,但是set里面的元素一定是不可变数据类型。


x={&#39;a&#39;,&#39;c&#39;,&#39;b&#39;}
y={&#39;a&#39;,&#39;g&#39;,&#39;b&#39;}
z={&#39;a&#39;}
print(&#39;a&#39; in x)
print(x-y)
print(x|y)
print(x&y)
print(x^y)
print(z<y)
Copy after login


x={&#39;a&#39;,&#39;c&#39;,&#39;b&#39;}
y={&#39;a&#39;,&#39;g&#39;,&#39;b&#39;}
z={&#39;a&#39;}
print(x.intersection(y))
print(x.union(y))
x.add(&#39;s&#39;)
print(x)
print(x.pop())
x.update({&#39;w&#39;,&#39;e&#39;,&#39;o&#39;})
print(x)
print(x)
运行结果:
{&#39;a&#39;, &#39;b&#39;}
{&#39;c&#39;, &#39;a&#39;, &#39;b&#39;, &#39;g&#39;}
{&#39;a&#39;, &#39;b&#39;, &#39;c&#39;, &#39;s&#39;}
a
{&#39;o&#39;, &#39;c&#39;, &#39;s&#39;, &#39;w&#39;, &#39;b&#39;, &#39;e&#39;}
{&#39;o&#39;, &#39;c&#39;, &#39;s&#39;, &#39;w&#39;, &#39;b&#39;, &#39;e&#39;}
Copy after login

注:在python中{}是空字典,如果想要定义空集合要用set()。

集合要是添加列表等可变类型则会报错。


x={&#39;a&#39;,&#39;c&#39;,&#39;b&#39;}
l=[1,2,3]
x.add(l)
print(x)
运行结果:
Traceback (most recent call last):
 File "C:/Users/jeff/PycharmProjects/python_file/practice/prac2.py", line 111, in <module>
 print(x.add(l))
TypeError: unhashable type: &#39;list&#39;
Copy after login

正确的添加序列方式为添加元组。


x={&#39;a&#39;,&#39;c&#39;,&#39;b&#39;}
l=(1,2,3)
x.add(l)
print(x)
运行结果:
{&#39;c&#39;, &#39;b&#39;, &#39;a&#39;, (1, 2, 3)}
Copy after login

定义不可操作的集合使用frozenset定义集合。

字典解析:

与列表解析相类似,集合也是可迭代对象,所以可以使用for循环遍历。


x={1,2,3}
print({i ** 2 for i in x})
运行结果:
{1, 9, 4}
Copy after login

四、布尔值

python的一个数据类型,有两个值Ture 与 False。


print(type(True))
print(True == 1)
print(True is 1)
print(True + 1)
运行结果:
<class &#39;bool&#39;>
True
False
2
Copy after login

集合和bool值,还是比较常见的类型,在基础学习里也有涉及,在这里就不多写了。

python中的数字在程序编写时广泛使用,今后还会更深层次的学习python的扩展库。

The above is the detailed content of python numeric types. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

How to run programs in terminal vscode How to run programs in terminal vscode Apr 15, 2025 pm 06:42 PM

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Golang vs. Python: Concurrency and Multithreading Golang vs. Python: Concurrency and Multithreading Apr 17, 2025 am 12:20 AM

Golang is more suitable for high concurrency tasks, while Python has more advantages in flexibility. 1.Golang efficiently handles concurrency through goroutine and channel. 2. Python relies on threading and asyncio, which is affected by GIL, but provides multiple concurrency methods. The choice should be based on specific needs.

What is vscode What is vscode for? What is vscode What is vscode for? Apr 15, 2025 pm 06:45 PM

VS Code is the full name Visual Studio Code, which is a free and open source cross-platform code editor and development environment developed by Microsoft. It supports a wide range of programming languages ​​and provides syntax highlighting, code automatic completion, code snippets and smart prompts to improve development efficiency. Through a rich extension ecosystem, users can add extensions to specific needs and languages, such as debuggers, code formatting tools, and Git integrations. VS Code also includes an intuitive debugger that helps quickly find and resolve bugs in your code.

Can vscode run ipynb Can vscode run ipynb Apr 15, 2025 pm 07:30 PM

The key to running Jupyter Notebook in VS Code is to ensure that the Python environment is properly configured, understand that the code execution order is consistent with the cell order, and be aware of large files or external libraries that may affect performance. The code completion and debugging functions provided by VS Code can greatly improve coding efficiency and reduce errors.

See all articles
OperatorDescription
yieldGenerator function sending protocol
lambda args:expressionGenerate anonymous function
x if y else zTernary expression
x or yLogical OR (there is a short-circuit algorithm)
x and yLogical AND (there is a short-circuit algorithm)
not xLogical NOT
x in y , x not in yMember relationship
x is y ,x is not yObject entity test
xy,x>=y,x==y,x!=yCompare sizes
x|yBitwise OR, set union
x^ybit XOR, set symmetric difference
Shift left or right by y bits