search
HomeBackend DevelopmentPython TutorialDetailed summary of Python data types and operators (code examples)

This article brings you a detailed summary (code example) of Python data types and operators. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

The previous article talked about Python’s input, output and variables. This section will explore Python’s data types and the calculation methods between data!

1. Python data types

The previous section clarified variables. In fact, the values ​​pointed to by variables have their own unique data types. These data types may represent different data. In In Python, there are mainly the following data types:

Integer (int)

In computers, the number of digits in integers actually has a range, and is not infinite as we imagine. Moreover, the number of digits in the integer may be different on different machines. For example:

32-bit system: the number of digits in the integer is 32 bits, and the addressing range is: -231 ~ 231-1, that is -2147483648 ~ 2147483647

64-bit system: the number of digits in the integer is 64 bits, and the addressing range is: -263 ~ 263-1, that is -9223372036854775808 ~ 9223372036854775807

Long integer (long)

In Python, long integer does not specify the number of digits, that is to say , the long integer can be infinitely large, but due to the limitations of the machine itself, it often cannot be infinitely large, and it will not work within a certain range.

Float type (float)

The above two data types are all integers, but in reality they cannot all be integers, there are also decimals, so the floating point type came into being. , to put it bluntly, floating point type is a decimal, and scientific notation can be used. In computers, multiples of 10 in scientific notation are replaced by e. For example: 5.21x105 is written as 5.21e9, or 521e7

Complex (complex)

The above three data types combined are real numbers. In fact, complex numbers are often used in scientific calculations. In Python, there are complex data types, the general form is: x yj, In the formula, x and y are both real numbers, for example: 5 6j

Boolean value (True, False)

There are only two Boolean values: true and false. In Python, they are represented by True and False, which must be Pay attention to capitalizing the first letter. Python is case-sensitive, so be sure to pay attention.

In [77]: 5==6
Out[77]: False
In [78]: 3>2
Out[78]: True
In [79]: True == True
Out[79]: True
In [80]: True == False
Out[80]: False

None value (None)

There is only one null value: None. This null value is very interesting. None cannot be understood as 0, because 0 is not a null value, just like the temperature is 0 degrees Celsius, 0 degrees Celsius has a temperature ( ̄▽ ̄)"

String (str)

The string may be written The most commonly used data type in Python is a string as long as it is enclosed in quotes. Python does not distinguish between single quotes, double quotes and triple quotes. They are the same:

In [81]: 'Hello,world!'
Out[81]: 'Hello,world!'
In [82]: "Hello,world!"
Out[82]: 'Hello,world!'
In [83]: '''Hello,world'''
Out[83]: 'Hello,world'

There will definitely be newbies who will ask, what are you doing with so many things? If you can’t just use one, I’ll just smile silently and say nothing:

In [84]: 'i'm MinuteSheep'
  File "<ipython-input-84-a2a810ee38cb>", line 1
    &#39;i&#39;m MinuteSheep&#39;
       ^
SyntaxError: invalid syntax

Look! An error is reported. Why? Because Python will automatically match the nearest symbol and close it, so the above situation will occur. Make the following modifications:

In [85]: "i&#39;m MinuteSheep"
Out[85]: "i&#39;m MinuteSheep"

(Mengxin: You bad old man is very bad ╰(‵□′)╯)

Similarly, three quotation marks are used for multiple lines, or when the content symbols are confusing:

In [87]: &#39;&#39;&#39;i&#39;m MinuteSheep,i said:"i&#39;m the best man in the world!"&#39;&#39;&#39;
Out[87]: &#39;i\&#39;m MinuteSheep,i said:"i\&#39;m the best man in the world!"&#39;
In [86]: &#39;&#39;&#39;
    ...: i&#39;m MinuteSheep,
    ...: i said:
    ...: "i&#39;m the best man in the world!"
    ...: &#39;&#39;&#39;
Out[86]: &#39;\ni\&#39;m MinuteSheep,\ni said:\n"i\&#39;m the best man in the world!"\n&#39;

Perfect solution, do you remember what \n is? It means line break. Similarly, you will find that i'm becomes i\'m. This is actually It is the display of escape. I will talk about escaping later.

There is a newbie coming out again. Didn’t you say in the previous section that three quotes are multi-line comments? How did it become this section? String?

This is a good question! Look at my explanation, there are pictures and the truth:

The content in direct quotation marks is a comment, as long as Assign the content in triple quotes to a variable, which is a string.

There are many methods for strings. There will be a special section to explain the methods of strings in detail later.

List (list)

Newbies may be unfamiliar with lists. You can temporarily understand them as one-dimensional arrays. Lists are used quite a lot in Python and are a data type that must be mastered in addition to strings. Let’s take a look at what the list looks like:

In [88]: [&#39;MinuteSheep&#39;, &#39;LiMing&#39;, &#39;123&#39;, 123]
Out[88]: [&#39;MinuteSheep&#39;, &#39;LiMing&#39;, &#39;123&#39;, 123]

As you can see, the data enclosed by a pair of square brackets is a list, and there can be other data types in the Liu table. The above list includes: strings and integers. Of course, lists can contain lists, which is called nesting of lists:

In [89]: [&#39;MinuteSheep&#39;, [&#39;LiMing&#39;, 123]]
Out[89]: [&#39;MinuteSheep&#39;, [&#39;LiMing&#39;, 123]]

There are many more about lists The specific methods will not be introduced one by one here. There will be a special section explaining the list method later.

Tuple (tuple)

Tuples may be even more unfamiliar. In fact, tuples It is an immutable list. The list is enclosed by a set of square brackets, and the tuple is enclosed by a pair of round brackets. The list can be manipulated (such as adding, deleting, modifying, and searching), but the tuple cannot, and the tuple cannot. has been changed, let’s see what the tuple looks like:

In [90]: (&#39;MinuteSheep&#39;,&#39;LiMing&#39;,123)
Out[90]: (&#39;MinuteSheep&#39;, &#39;LiMing&#39;, 123)

字典(dict)

字典是Python的一种非常强大的数据类型,通过键值对的形式将数据保存下来,提高了数据增、删、改、查的速度,通常作为数据存储的格式,也来看看字典长啥样哇:

In [91]: {&#39;name&#39;: &#39;MinuteSheep&#39;, &#39;gender&#39; : &#39;male&#39;, &#39;age&#39;: 99}
Out[91]: {&#39;age&#39;: 99, &#39;gender&#39;: &#39;male&#39;, &#39;name&#39;: &#39;MinuteSheep&#39;}

可以看到,字典是用一对花括号括起来的,并且以 'key' : 'value' 的形式存储,同样,字典里面可以包含其他数据类型,上面的字典包括:字符串、整型。当然,字典也可以嵌套:

In [92]: {&#39;name&#39; : &#39;MinuteSheep&#39;, &#39;age&#39;: {&#39;young&#39; : 15, &#39;old&#39; : 99}}
Out[92]: {&#39;age&#39;: {&#39;old&#39;: 99, &#39;young&#39;: 15}, &#39;name&#39;: &#39;MinuteSheep&#39;}

字典也会有专门的一节去讲解它的方法。

二、Python数据运算

说完了Python的数据类型,就该数据运算了,养兵千日,用在一时嘛

算数运算

加 +

In [93]: 1+2
Out[93]: 3

减 -

In [95]: 1-2O
ut[95]: -1

乘 *

In [96]: 1*2
Out[96]: 2

除 /

In [97]: 5/2Out[97]: 2.5

取模 %  (就是取余数)

In [98]: 5%2
Out[98]: 1

取整 //

In [99]: 5//2
Out[99]: 2

幂 **

In [100]: 5**2
Out[100]: 25

赋值运算

简单赋值 =

In [102]: a=5
In [103]: b=6
In [104]: c=a+b
In [105]: c
Out[105]: 11

加法赋值 +=   (b+=a,相当于b=b+a)

In [106]: a=5
In [107]: b=6
In [108]: b+=a
In [109]: b
Out[109]: 11

减法赋值 -=   (b-=a,相当于b=b-a)

In [111]: a=5
In [112]: b=6
In [113]: b-=a
In [114]: b
Out[114]: 1

乘法赋值 *=   (b*=a,相当于b=b*a)

In [115]: a=5
In [116]: b=6
In [117]: b*=a
In [118]: b
Out[118]: 30

除法赋值 /=   (b/=a,相当于b=b/a)

In [119]: a=5
In [120]: b=6
In [121]: b/=a
In [122]: b
Out[122]: 1.2

取模赋值 %=   (b%=a,相当于b=b%a)

In [123]: a=5
In [124]: b=6
In [125]: b%=a
In [126]: b
Out[126]: 1

取整赋值 //=   (b//=a,相当于b=b//a)

In [127]: a=5
In [128]: b=6
In [129]: b//=a
In [130]: b
Out[130]: 1

幂赋值 **=   (b**=a,相当于b=b**a)

In [131]: a=5
In [132]: b=6
In [133]: b**=a
In [134]: b
Out[134]: 7776

比较运算

测试相等 ==

In [136]: 1==1
Out[136]: True
In [137]: 1==2
Out[137]: False

不等于 !=

In [144]: 1!=1
Out[144]: False
In [145]: 1!=2
Out[145]: True

大于 >

In [146]: 1>1
Out[146]: False
In [147]: 2>1
Out[147]: True

大于等于 >=

In [149]: 1>=1
Out[149]: True
In [150]: 2>=1
Out[150]: True

小于

In [151]: 6<6
Out[151]: False
In [152]: 6<7
Out[152]: True

小于等于

In [153]: 6<=6
Out[153]: True
In [154]: 6<=7
Out[154]: True

逻辑运算

布尔'与' and   (有假为假,全真为真)

In [156]: True and False
Out[156]: False
In [157]: True and True
Out[157]: True
In [158]: False and False
Out[158]: False

布尔'或' or   (有真为真,全假为假)

In [159]: True or True
Out[159]: True
In [160]: True or False
Out[160]: True
In [161]: False and False
Out[161]: False

布尔'非' not   (取相反)

In [162]: not True
Out[162]: False
In [163]: not False
Out[163]: True

身份运算

判断两个标识符是否引用自同一个对象 is

In [167]: a=b=3

In [168]: a is b
Out[168]: True

In [169]: a=3

In [170]: b=5

In [171]: a is b
Out[171]: False

判断两个标识符是否引用自不同对象 is not

In [177]: a=3
In [178]: b=5
In [179]: a is not b
Out[179]: True

== 与 is 的区别:

看到这里,很多小伙伴已经晕了,== 和 is 好像一样啊,看起来一样,其实是不一样的,来看下面的这段代码:

In [180]: a = 600
In [181]: b = 600
In [182]: a == b
Out[182]: True
In [183]: a is b
Out[183]: False

其实啊,== 比较的是值,is比较的地址,让我们用 id() 这个函数查看一下变量的地址:

In [184]: id(a)
Out[184]: 2155434581648
In [185]: id(b)
Out[185]: 2155434581904

可以看到,a和b俩个变量的值虽然相同,但地址却不一样,所以使用 == 和 is 的结果自然就不一样。那我们再来看一段代码:

In [187]: a = 10
In [188]: b = 10
In [189]: a == b
Out[189]: True
In [190]: a is b
Out[190]: True
In [191]: id(a)
Out[191]: 1529742064
In [192]: id(b)
Out[192]: 1529742064

萌新是不是莫不着头脑了,用600的时候 is 输出False,用10的时候怎么地址一样了啊,(快回头,有鬼~)其实啊,Python有一个叫做小整数对象池的东西,只要是[-5, 256]之间的整数都会使用同一份地址,这下萌新明白了哇。

位运算

重点说明:位运算针对的是二进制数

按位与 &

In [193]: a = 15   # 15 = 0000 1111
In [194]: b = 30   # 30 = 0001 1110
In [195]: c = a&b  # 14 = 0000 1110
In [196]: c
Out[196]: 14

按位或 |

In [193]: a = 15   # 15 = 0000 1111
In [194]: b = 30   # 30 = 0001 1110
In [197]: c = a|b  # 31 = 0001 1111
In [198]: c
Out[198]: 31

按位异或 ^

In [193]: a = 15   # 15 = 0000 1111
In [194]: b = 30   # 30 = 0001 1110
In [200]: c = a^b  # 17 = 0001 0001
In [201]: c
Out[201]: 17

按位取反 ~

In [210]: a = 60   # 60 = 0011 1100
In [211]: c = ~a  # -61 = 1100 0011
In [212]: c
Out[212]: -61

左移

In [213]: a = 15   # 15 = 0000 1111
In [214]: c = a<<2 # 60 = 0011 1100
In [215]: c
Out[215]: 60#左移后面要加位数

右移 >>

In [213]: a = 15     # 15 = 0000 1111
In [218]: c = a>>2    # 3 = 0000 0011 
In [219]: c
Out[219]: 3#右移后面要加位数

Python运算符优先级(从高到底依次排列)

**                 # 指数 (最高优先级)
~ + -              # 按位翻转, 一元加号和减号 (最后两个的方法名为 +@ 和 -@)
* / % //           # 乘,除,取模和取整除
+ -                # 加法减法
>> <<              # 右移,左移运算符
&                  # 位 &#39;AND&#39;
^ |                # 位运算符
<= < > >=          # 比较运算符
<> == !=           # 等于运算符
= %= /= //= -= += *= **=    # 赋值运算符
is is not          # 身份运算符
in not in          # 成员运算符
not and or         # 逻辑运算符

The above is the detailed content of Detailed summary of Python data types and operators (code examples). For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:博客园. If there is any infringement, please contact admin@php.cn delete
Merging Lists in Python: Choosing the Right MethodMerging Lists in Python: Choosing the Right MethodMay 14, 2025 am 12:11 AM

TomergelistsinPython,youcanusethe operator,extendmethod,listcomprehension,oritertools.chain,eachwithspecificadvantages:1)The operatorissimplebutlessefficientforlargelists;2)extendismemory-efficientbutmodifiestheoriginallist;3)listcomprehensionoffersf

How to concatenate two lists in python 3?How to concatenate two lists in python 3?May 14, 2025 am 12:09 AM

In Python 3, two lists can be connected through a variety of methods: 1) Use operator, which is suitable for small lists, but is inefficient for large lists; 2) Use extend method, which is suitable for large lists, with high memory efficiency, but will modify the original list; 3) Use * operator, which is suitable for merging multiple lists, without modifying the original list; 4) Use itertools.chain, which is suitable for large data sets, with high memory efficiency.

Python concatenate list stringsPython concatenate list stringsMay 14, 2025 am 12:08 AM

Using the join() method is the most efficient way to connect strings from lists in Python. 1) Use the join() method to be efficient and easy to read. 2) The cycle uses operators inefficiently for large lists. 3) The combination of list comprehension and join() is suitable for scenarios that require conversion. 4) The reduce() method is suitable for other types of reductions, but is inefficient for string concatenation. The complete sentence ends.

Python execution, what is that?Python execution, what is that?May 14, 2025 am 12:06 AM

PythonexecutionistheprocessoftransformingPythoncodeintoexecutableinstructions.1)Theinterpreterreadsthecode,convertingitintobytecode,whichthePythonVirtualMachine(PVM)executes.2)TheGlobalInterpreterLock(GIL)managesthreadexecution,potentiallylimitingmul

Python: what are the key featuresPython: what are the key featuresMay 14, 2025 am 12:02 AM

Key features of Python include: 1. The syntax is concise and easy to understand, suitable for beginners; 2. Dynamic type system, improving development speed; 3. Rich standard library, supporting multiple tasks; 4. Strong community and ecosystem, providing extensive support; 5. Interpretation, suitable for scripting and rapid prototyping; 6. Multi-paradigm support, suitable for various programming styles.

Python: compiler or Interpreter?Python: compiler or Interpreter?May 13, 2025 am 12:10 AM

Python is an interpreted language, but it also includes the compilation process. 1) Python code is first compiled into bytecode. 2) Bytecode is interpreted and executed by Python virtual machine. 3) This hybrid mechanism makes Python both flexible and efficient, but not as fast as a fully compiled language.

Python For Loop vs While Loop: When to Use Which?Python For Loop vs While Loop: When to Use Which?May 13, 2025 am 12:07 AM

Useaforloopwheniteratingoverasequenceorforaspecificnumberoftimes;useawhileloopwhencontinuinguntilaconditionismet.Forloopsareidealforknownsequences,whilewhileloopssuitsituationswithundeterminediterations.

Python loops: The most common errorsPython loops: The most common errorsMay 13, 2025 am 12:07 AM

Pythonloopscanleadtoerrorslikeinfiniteloops,modifyinglistsduringiteration,off-by-oneerrors,zero-indexingissues,andnestedloopinefficiencies.Toavoidthese:1)Use'i

See all articles

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 Article

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.