Python 简明教程

Python - Data Types

Python Data Types

Python data types 实际上是类,并且定义的变量是它们的实例或对象。由于 Python 是动态类型的,因此变量的数据类型是在运行时根据分配的值确定的。

Python data types are actually classes, and the defined variables are their instances or objects. Since Python is dynamically typed, the data type of a variable is determined at runtime based on the assigned value.

通常,数据类型用于定义变量的类型。它表示我们将要存储在变量中的数据类型,并确定可以在其上执行哪些操作。

In general, the data types are used to define the type of a variable. It represents the type of data we are going to store in a variable and determines what operations can be done on it.

每种编程语言都有自己对数据项的分类。有了这些数据类型,我们可以存储不同类型的数据值。

Each programming language has its own classification of data items. With these datatypes, we can store different types of data values.

Types of Data Types in Python

Python 支持以下内置数据类型 −

Python supports the following built-in data types −

data types

1. Python Numeric Data Types

Python 数字数据类型存储数字值。当您给它们赋值时,将创建 Number 对象。例如 −

Python numeric data types store numeric values. Number objects are created when you assign a value to them. For example −

var1 = 1       # int data type
var2 = True    # bool data type
var3 = 10.023  # float data type
var4 = 10+3j   # complex data type

Python 支持四种不同的数字类型,其中每一种在 Python 库中都有内置类,分别称为 int, bool, floatcomplex

Python supports four different numerical types and each of them have built-in classes in Python library, called int, bool, float and complex respectively −

  1. int (signed integers)

  2. float (floating point real values)

  3. complex (complex numbers)

复数由两部分组成 - realimaginary 。它们由 '+' 或 '-' 符号分隔。复数部分以 'j' 为后缀,这是表示复数的虚数。-1 的平方根($\sqrt{-1}$)定义为虚数。Python 中的复数表示为 x+yj,其中 x 是实部,y 是虚部。所以,5+6j 是一个复数。

A complex number is made up of two parts - real and imaginary. They are separated by '+' or '-' signs. The imaginary part is suffixed by 'j' which is the imaginary number. The square root of -1 ($\sqrt{-1}$), is defined as imaginary number. Complex number in Python is represented as x+yj, where x is the real part, and y is the imaginary part. So, 5+6j is a complex number.

>>> type(5+6j)
<class 'complex'>

以下是数字的一些示例 −

Here are some examples of numbers −

Example of Numeric Data Types

以下是一个显示整数、浮点数和复数用法的示例:

Following is an example to show the usage of Integer, Float and Complex numbers:

# integer variable.
a=100
print("The type of variable having value", a, " is ", type(a))

# float variable.
c=20.345
print("The type of variable having value", c, " is ", type(c))

# complex variable.
d=10+3j
print("The type of variable having value", d, " is ", type(d))

2. Python String Data Type

Python string 是一个或多个 Unicode 字符的序列,用单引号、双引号或三单引号(也称为反引号)括起来。Python 字符串是不可变的,这意味着当您对字符串执行操作时,您总是会生成一个相同类型的新字符串对象,而不是改变现有字符串。

Python string is a sequence of one or more Unicode characters, enclosed in single, double or triple quotation marks (also called inverted commas). Python strings are immutable which means when you perform an operation on strings, you always produce a new string object of the same type, rather than mutating an existing string.

只要括起来的是同一个字符序列,单引号还是双引号还是三单引号都没关系。因此,以下字符串表示是等价的。

As long as the same sequence of characters is enclosed, single or double or triple quotes don’t matter. Hence, following string representations are equivalent.

>>> 'TutorialsPoint'
'TutorialsPoint'
>>> "TutorialsPoint"
'TutorialsPoint'
>>> '''TutorialsPoint'''
'TutorialsPoint'

Python 中的字符串是 str 类的对象。它可以通过 type() 函数验证。

A string in Python is an object of str class. It can be verified with type() function.

>>> type("Welcome To TutorialsPoint")
<class 'str'>

字符串是数字数据类型。显然,我们不能对它进行算术运算。但是,可以执行诸如 slicingconcatenation 之类的操作。Python 的 str 类为字符串处理定义了许多有用的方法。可以使用 slice 运算符 ([ ] 和 [:] ) 获取字符串的子集,索引从字符串开头的 0 开始,在结尾处从 -1 开始。

A string is a non-numeric data type. Obviously, we cannot perform arithmetic operations on it. However, operations such as slicing and concatenation can be done. Python’s str class defines a number of useful methods for string processing. Subsets of strings can be taken using the slice operator ([ ] and [:] ) with indexes starting at 0 in the beginning of the string and working their way from -1 at the end.

加号 (+) 是字符串连接运算符,星号 (*) 是 Python 中的重复运算符。

The plus (+) sign is the string concatenation operator and the asterisk (*) is the repetition operator in Python.

Example of String Data Type

str = 'Hello World!'

print (str)          # Prints complete string
print (str[0])       # Prints first character of the string
print (str[2:5])     # Prints characters starting from 3rd to 5th
print (str[2:])      # Prints string starting from 3rd character
print (str * 2)      # Prints string two times
print (str + "TEST") # Prints concatenated string

这会产生以下结果 −

This will produce the following result −

Hello World!
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST

3. Python Sequence Data Types

序列是集合数据类型。它是有序的项集合。序列中的项具有从 0 开始的位置索引。它在概念上类似于 C 或 C++ 中的数组。Python 中定义了以下三个序列数据类型。

Sequence is a collection data type. It is an ordered collection of items. Items in the sequence have a positional index starting with 0. It is conceptually similar to an array in C or C++. There are following three sequence data types defined in Python.

  1. List Data Type

  2. Tuple Data Type

  3. Range Data Type

Python 序列是有界的和可迭代的 - 每当我们在 Python 中说出可迭代序列时,它就表示一个序列数据类型(例如,一个列表)。

Python sequences are bounded and iterable - Whenever we say an iterable in Python, it means a sequence data type (for example, a list).

(a) Python List Data Type

Python Lists 是最通用的复合数据类型。Python 列表包含用逗号分隔并用方括号([])括起来的项。在某种程度上,Python 列表类似于 C 中的数组。它们之间的区别之一在于,属于 Python 列表的所有项都可以是不同的数据类型,而 C 数组可以存储与特定数据类型相关的元素。

Python Lists are the most versatile compound data types. A Python list contains items separated by commas and enclosed within square brackets ([]). To some extent, Python lists are similar to arrays in C. One difference between them is that all the items belonging to a Python list can be of different data type where as C array can store elements related to a particular data type.

>>> [2023, "Python", 3.11, 5+6j, 1.23E-4]

Python 中的列表是 list 类的对象。我们可以使用 type() 函数检查它。

A list in Python is an object of list class. We can check it with type() function.

>>> type([2023, "Python", 3.11, 5+6j, 1.23E-4])
<class 'list'>

如前所述,列表中的项可以是任何数据类型。这意味着列表对象也可以是另一个列表中的项。在这种情况下,它将变成一个嵌套列表。

As mentioned, an item in the list may be of any data type. It means that a list object can also be an item in another list. In that case, it becomes a nested list.

>>> [['One', 'Two', 'Three'], [1,2,3], [1.0, 2.0, 3.0]]

一个列表可以具有简单的数字、字符串、元组、字典、集合或用户定义类的对象作为其项。

A list can have items which are simple numbers, strings, tuple, dictionary, set or object of user defined class also.

Python 列表中存储的值可以使用切片运算符 ([ ] 和 [:]) 访问,索引从列表开头处的 0 开始,一直到末尾 -1。加号 (+) 是列表连接运算符,星号 (*) 是重复运算符。

The values stored in a Python list can be accessed using the slice operator ([ ] and [:]) with indexes starting at 0 in the beginning of the list and working their way to end -1. The plus (+) sign is the list concatenation operator, and the asterisk (*) is the repetition operator.

Example of List Data Type

list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tinylist = [123, 'john']

print (list)            # Prints complete list
print (list[0])         # Prints first element of the list
print (list[1:3])       # Prints elements starting from 2nd till 3rd
print (list[2:])        # Prints elements starting from 3rd element
print (tinylist * 2)    # Prints list two times
print (list + tinylist) # Prints concatenated lists

这产生了以下结果 -

This produce the following result −

['abcd', 786, 2.23, 'john', 70.2]
abcd
[786, 2.23]
[2.23, 'john', 70.2]
[123, 'john', 123, 'john']
['abcd', 786, 2.23, 'john', 70.2, 123, 'john']

(b) Python Tuple Data Type

Python tuple 是另一个类似于列表的序列数据类型。Python 元组由逗号分隔的多个值组成。然而,与列表不同的是,元组用圆括号 (…​) 括起来。

Python tuple is another sequence data type that is similar to a list. A Python tuple consists of a number of values separated by commas. Unlike lists, however, tuples are enclosed within parentheses (…​).

元组也是一个序列,因此元组中的每个项都有一个索引,表示其在集合中的位置。索引从 0 开始。

A tuple is also a sequence, hence each item in the tuple has an index referring to its position in the collection. The index starts from 0.

>>> (2023, "Python", 3.11, 5+6j, 1.23E-4)

在 Python 中,元组是 tuple 类的对象。我们可以使用 type() 函数检查它。

In Python, a tuple is an object of tuple class. We can check it with the type() function.

>>> type((2023, "Python", 3.11, 5+6j, 1.23E-4))
<class 'tuple'>

与列表一样,元组中的项也可以是一个列表、一个元组本身或任何其他 Python 类的对象。

As in case of a list, an item in the tuple may also be a list, a tuple itself or an object of any other Python class.

>>> (['One', 'Two', 'Three'], 1,2.0,3, (1.0, 2.0, 3.0))

要形成元组,可以使用圆括号,但不强制要求。默认情况下,逗号分隔而不带任何包围符号的数据项被视为元组。

To form a tuple, use of parentheses is optional. Data items separated by comma without any enclosing symbols are treated as a tuple by default.

>>> 2023, "Python", 3.11, 5+6j, 1.23E-4
(2023, 'Python', 3.11, (5+6j), 0.000123)

Example of Tuple data Type

tuple = ( 'abcd', 786 , 2.23, 'john', 70.2  )
tinytuple = (123, 'john')

print (tuple)               # Prints the complete tuple
print (tuple[0])            # Prints first element of the tuple
print (tuple[1:3])          # Prints elements of the tuple starting from 2nd till 3rd
print (tuple[2:])           # Prints elements of the tuple starting from 3rd element
print (tinytuple * 2)       # Prints the contents of the tuple twice
print (tuple + tinytuple)   # Prints concatenated tuples

这产生了以下结果 -

This produce the following result −

('abcd', 786, 2.23, 'john', 70.2)
abcd
(786, 2.23)
(2.23, 'john', 70.2)
(123, 'john', 123, 'john')
('abcd', 786, 2.23, 'john', 70.2, 123, 'john')

列表和元组之间的主要区别是:列表用方括号 ([ ]) 括起来,并且它们的元素和大小可以更改,即列表是可变的,而元组用圆括号 括起来,并且不能更新(不可变)。可以将元组视为 read-only 列表。

The main differences between lists and tuples are: Lists are enclosed in brackets ( [ ] ) and their elements and size can be changed i.e. lists are mutable, while tuples are enclosed in parentheses ( ( ) ) and cannot be updated (immutable). Tuples can be thought of as read-only lists.

以下代码对于元组来说无效,因为我们尝试更新元组,这是不允许的。列表中也可能发生类似的情况 -

The following code is invalid with tuple, because we attempted to update a tuple, which is not allowed. Similar case is possible with lists −

tuple = ( 'abcd', 786 , 2.23, 'john', 70.2  )
list = [ 'abcd', 786 , 2.23, 'john', 70.2  ]
tuple[2] = 1000    # Invalid syntax with tuple
list[2] = 1000     # Valid syntax with list

(c) Python Range Data Type

Python 范围是一个不可变的数字序列,它通常用于遍历特定数量的项。

A Python range is an immutable sequence of numbers which is typically used to iterate through a specific number of items.

它由 Range 类表示。此类的构造函数接受从 0 开始并递增到 1 的数字序列,直到达到指定数字。以下是函数的语法 -

It is represented by the Range class. The constructor of this class accepts a sequence of numbers starting from 0 and increments to 1 until it reaches a specified number. Following is the syntax of the function −

range(start, stop, step)

以下是所用参数的说明 -

Here is the description of the parameters used −

  1. start: Integer number to specify starting position, (Its optional, Default: 0)

  2. stop: Integer number to specify ending position (It’s mandatory)

  3. step: Integer number to specify increment, (Its optional, Default: 1)

Example of Range Data Type

以下是一个使用 for 循环来打印从 0 到 4 的数字的程序 -

Following is a program which uses for loop to print number from 0 to 4 −

for i in range(5):
  print(i)

这产生了以下结果 -

This produce the following result −

0
1
2
3
4

现在让我们修改上述程序,以从 2 而非 0 开始打印数字 -

Now let’s modify above program to print the number starting from 2 instead of 0 −

for i in range(2, 5):
  print(i)

这产生了以下结果 -

This produce the following result −

2
3
4

同样,让我们修改程序,从 1 开始打印数字,但以 2 而不是 1 为增量:

Again, let’s modify the program to print the number starting from 1 but with an increment of 2 instead of 1:

for i in range(1, 5, 2):
  print(i)

这产生了以下结果 -

This produce the following result −

1
3

4. Python Binary Data Types

Python 中的二进制数据类型是一种将数据表示为一系列二进制数字(即 0 和 1)的方式。它就像一门计算机理解的特殊语言,可以有效地存储和处理信息。

A binary data type in Python is a way to represent data as a series of binary digits, which are 0’s and 1’s. It is like a special language computers understand to store and process information efficiently.

此种类型的数据通常在处理诸如文件、图像或任何可使用仅两个可能值来表示的内容中使用。因此,二进制数据类型不使用常规数字或字母,而是使用 0 和 1 的组合来表示信息。

This type of data is commonly used when dealing with things like files, images, or anything that can be represented using just two possible values. So, instead of using regular numbers or letters, binary sequence data types use a combination of 0s and 1s to represent information.

Python 提供了三种不同的方式来表示二进制数据。如下所示 −

Python provides three different ways to represent binary data. They are as follows −

  1. bytes

  2. bytearray

  3. memoryview

让我们分别讨论这些数据类型 −

Let us discuss each of these data types individually −

(a) Python Bytes Data Type

Python 中的字节数据类型表示一系列字节。每个字节是 0 至 255 之间的整数值。通常用于存储二进制数据,例如图像、文件或网络数据包。

The byte data type in Python represents a sequence of bytes. Each byte is an integer value between 0 and 255. It is commonly used to store binary data, such as images, files, or network packets.

我们可以在 Python 中使用内置 bytes() function 或通过给一系列数字加上 b 前缀创建字节。

We can create bytes in Python using the built-in bytes() function or by prefixing a sequence of numbers with b.

Example of Bytes Data Type

在以下示例中,我们使用内置 bytes() 函数显式指定表示 ASCII 值的一系列数字 −

In the following example, we are using the built-in bytes() function to explicitly specify a sequence of numbers representing ASCII values −

# Using bytes() function to create bytes
b1 = bytes([65, 66, 67, 68, 69])
print(b1)

获得的结果如下 −

The result obtained is as follows −

b'ABCDE'

此处,我们使用字符串前的“b”前缀自动创建一个字节对象 −

In here, we are using the "b" prefix before a string to automatically create a bytes object −

# Using prefix 'b' to create bytes
b2 = b'Hello'
print(b2)

以下是上面代码的输出: -

Following is the output of the above code −

b'Hello'

(b) Python Bytearray Data Type

Python 中的字节数组数据类型与字节数据类型非常相似,但有一个关键区别:它是可变的,这意味着您可以在创建后修改其中存储的值。

The bytearray data type in Python is quite similar to the bytes data type, but with one key difference: it is mutable, meaning you can modify the values stored in it after it is created.

您可以使用多种方法创建字节数组,包括传递表示字节值的整数迭代器、编码一个字符串或转换现有的字节或字节数组对象。为此,我们使用 bytearray() function

You can create a bytearray using various methods, including by passing an iterable of integers representing byte values, by encoding a string, or by converting an existing bytes or bytearray object. For this, we use bytearray() function.

Example of Bytearray Data Type

在下面的示例中,我们通过传递表示字节值的整数迭代器来创建字节数组 −

In the example below, we are creating a bytearray by passing an iterable of integers representing byte values −

# Creating a bytearray from an iterable of integers
value = bytearray([72, 101, 108, 108, 111])
print(value)

获得的输出如下所示 −

The output obtained is as shown below −

bytearray(b'Hello')

现在,我们通过使用“UTF-8”编码对一个字符串进行编码来创建一个字节数组 −

Now, we are creating a bytearray by encoding a string using a "UTF-8" encoding −

# Creating a bytearray by encoding a string
val = bytearray("Hello", 'utf-8')
print(val)

产生的结果如下 −

The result produced is as follows −

bytearray(b'Hello')

(c) Python Memoryview Data Type

在 Python 中,内存视图是一个内置对象,可提供对原始对象内存的视图,通常为支持缓冲区协议的对象,例如字节数组 (bytearray) 和字节 (bytes)。它允许您访问原始对象的底层数据而不进行复制,为大型数据集提供高效的内存访问。

In Python, a memoryview is a built-in object that provides a view into the memory of the original object, generally objects that support the buffer protocol, such as byte arrays (bytearray) and bytes (bytes). It allows you to access the underlying data of the original object without copying it, providing efficient memory access for large datasets.

您可以使用多种方法创建内存视图。这些方法包括使用 memoryview() 构造函数、对字节或字节数组对象进行分片、从数组对象中提取,或在从文件中读取时使用 open() 等内置函数。

You can create a memoryview using various methods. These methods include using the memoryview() constructor, slicing bytes or bytearray objects, extracting from array objects, or using built-in functions like open() when reading from files.

Example of Memoryview Data Type

在给定的示例中,我们直接通过将受支持对象传递给 memoryview() 构造函数来创建一个 memoryview 对象。受支持的对象通常包括字节数组 (bytearray)、字节 (bytes) 以及支持缓冲区协议的其他对象 −

In the given example, we are creating a memoryview object directly by passing a supported object to the memoryview() constructor. The supported objects generally include byte arrays (bytearray), bytes (bytes), and other objects that support the buffer protocol −

data = bytearray(b'Hello, world!')
view = memoryview(data)
print(view)

以下是上面代码的输出: -

Following is the output of the above code −

<memory at 0x00000186FFAA3580>

如果您有一个数组对象,您可以使用缓冲区接口创建一个 memoryview,如下所示 −

If you have an array object, you can create a memoryview using the buffer interface as shown below −

import array
arr = array.array('i', [1, 2, 3, 4, 5])
view = memoryview(arr)
print(view)

获得的输出如下所示 −

The output obtained is as shown below −

<memory at 0x0000017963CD3580>

您还可以通过对字节或字节数组对象进行分片来创建一个 memoryview −

You can also create a memoryview by slicing a bytes or bytearray object −

data = b'Hello, world!'
# Creating a view of the last part of the data
view = memoryview(data[7:])
print(view)

获得的结果如下 −

The result obtained is as follows −

<memory at 0x00000200D9AA3580>

5. Python Dictionary Data Type

Python dictionaries 是哈希表类型。字典键可以是几乎任何 Python 类型,但通常是数字或字符串。另一方面,值可以是任何任意的 Python 对象。

Python dictionaries are kind of hash table type. A dictionary key can be almost any Python type, but are usually numbers or strings. Values, on the other hand, can be any arbitrary Python object.

Python 字典类似于 Perl 中的关联数组或散列,由 key:value 对组成。这些对用逗号分隔,并置于花括号 {} 中。要在键和值之间建立映射,则在两者之间放置分号“:”符号。

Python dictionary is like associative arrays or hashes found in Perl and consist of key:value pairs. The pairs are separated by comma and put inside curly brackets {}. To establish mapping between key and value, the semicolon':' symbol is put between the two.

>>> {1:'one', 2:'two', 3:'three'}

在 Python 中,字典是内置 dict 类的对象。我们可以使用 type() 函数检查它。

In Python, dictionary is an object of the built-in dict class. We can check it with the type() function.

>>> type({1:'one', 2:'two', 3:'three'})
<class 'dict'>

字典用大括号 ({ }) 括起来,可以使用方括号 ([]) 来赋值和访问值。

Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed using square braces ([]).

Example of Dictionary Data Type

dict = {}
dict['one'] = "This is one"
dict[2]     = "This is two"

tinydict = {'name': 'john','code':6734, 'dept': 'sales'}


print (dict['one'])       # Prints value for 'one' key
print (dict[2])           # Prints value for 2 key
print (tinydict)          # Prints complete dictionary
print (tinydict.keys())   # Prints all the keys
print (tinydict.values()) # Prints all the values

这产生了以下结果 -

This produce the following result −

This is one
This is two
{'dept': 'sales', 'code': 6734, 'name': 'john'}
['dept', 'code', 'name']
['sales', 6734, 'john']

Python 的字典不是序列。它是一个项的集合,但每个项(键值对)不像字符串、列表或元组那样,由位置索引标识。因此,无法对字典执行切片操作。字典是一个可变对象,因此可以执行添加、修改或删除操作,其对应的功能在 dict 类中定义。将在后续章节中说明这些操作。

Python’s dictionary is not a sequence. It is a collection of items but each item (key:value pair) is not identified by positional index as in string, list or tuple. Hence, slicing operation cannot be done on a dictionary. Dictionary is a mutable object, so it is possible to perform add, modify or delete actions with corresponding functionality defined in dict class. These operations will be explained in a subsequent chapter.

6. Python Set Data Type

Set 是数学中定义的集合的 Python 实现。Python 中的集合是一个集合,但不是像字符串、列表或元组那样的索引或有序集合。一个对象不能在集合中出现多次,而列表和元组中的相同对象可以出现多次。

Set is a Python implementation of set as defined in Mathematics. A set in Python is a collection, but is not an indexed or ordered collection as string, list or tuple. An object cannot appear more than once in a set, whereas in List and Tuple, same object can appear more than once.

集合中用逗号分隔的项置于花括号或大括号 {} 中。集合集合中的项可以是不同的数据类型。

Comma separated items in a set are put inside curly brackets or braces {}. Items in the set collection can be of different data types.

>>> {2023, "Python", 3.11, 5+6j, 1.23E-4}
{(5+6j), 3.11, 0.000123, 'Python', 2023}

请注意,集合集合中的项可能不会按照它们输入的顺序出现。Python 根据数学定义对项的位置进行优化,以便对集合执行操作。

Note that items in the set collection may not follow the same order in which they are entered. The position of items is optimized by Python to perform operations over set as defined in mathematics.

Python 的集合是内置 set 类的对象,可以使用 type() 函数检查。

Python’s Set is an object of built-in set class, as can be checked with the type() function.

>>> type({2023, "Python", 3.11, 5+6j, 1.23E-4})
<class 'set'>

集合只能储存 immutable 对象,例如数字(int、float、complex 或 bool)、字符串或元组。如果您尝试把列表或字典放入集合集合中,Python 就会引发 TypeError

A set can store only immutable objects such as number (int, float, complex or bool), string or tuple. If you try to put a list or a dictionary in the set collection, Python raises a TypeError.

>>> {['One', 'Two', 'Three'], 1,2,3, (1.0, 2.0, 3.0)}
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'

Hashing 是计算机科学中的一种机制,它可以更快地搜索计算机内存中的对象。 Only immutable objects are hashable

Hashing is a mechanism in computer science which enables quicker searching of objects in computer’s memory. Only immutable objects are hashable.

即使集合不允许可变项,但它本身是可变的。因此,可以使用内置 set 类中的方法对集合对象执行添加/删除/更新操作。Python 还有一组运算符来执行集合操作。将在后面的章节中说明这些方法和运算符

Even if a set doesn’t allow mutable items, the set itself is mutable. Hence, add/delete/update operations are permitted on a set object, using the methods in built-in set class. Python also has a set of operators to perform set manipulation. The methods and operators are explained in latter chapters

Example of Set

set1 = {123, 452, 5, 6}
set2 = {'Java', 'Python', 'JavaScript'}

print(set1)
print(set2)

这会产生以下输出 −

This will generate the following output −

{123, 452, 5, 6}
{'Python', 'JavaScript', 'Java'}

7. Python Boolean Data Type

Python boolean 类型是内置数据类型之一,它表示两个值之一,即 TrueFalse 。Python bool() 函数允许您评估任何表达式的值,并根据表达式返回 True 或 False。

Python boolean type is one of built-in data types which represents one of the two values either True or False. Python bool() function allows you to evaluate the value of any expression and returns either True or False based on the expression.

布尔数只有两个可能的值,分别由关键字 TrueFalse 表示。它们分别对应于整数 1 和 0。

A Boolean number has only two possible values, as represented by the keywords, True and False. They correspond to integer 1 and 0 respectively.

>>> type (True)
<class 'bool'>
>>> type(False)
<class 'bool'>

Example of Boolean Data Type

以下是打印布尔变量 a 和 b 值的程序 −

Following is a program which prints the value of boolean variables a and b −

a = True
# display the value of a
print(a)

# display the data type of a
print(type(a))

这会产生以下结果 −

This will produce the following result −

true
<class 'bool'>

以下程序是评估表达式并打印返回值的另一个程序 −

Following is another program which evaluates the expressions and prints the return values −

# Returns false as a is not equal to b
a = 2
b = 4
print(bool(a==b))

# Following also prints the same
print(a==b)

# Returns False as a is None
a = None
print(bool(a))

# Returns false as a is an empty sequence
a = ()
print(bool(a))

# Returns false as a is 0
a = 0.0
print(bool(a))

# Returns false as a is 10
a = 10
print(bool(a))

这产生了以下结果 -

This produce the following result −

False
False
False
False
False
True

8. Python None Type

Python 的 None 类型由“nonetype."表示。它是其自身数据类型的对象。非类型表示值的空类型或值不存在。

Python’s none type is represented by the "nonetype."  It is an object of its own data type. The nonetype represents the null type of values or absence of a value.

Example of None Type

在下面的示例中,我们把 None 赋值给变量 x 并打印它的类型,它将是非类型 −

In the following example, we are assigning None to a variable x and printing its type, which will be nonetyoe −

# Declaring a variable
# And, assigning a Null value (None)

x = None

# Printing its value and type
print("x = ", x)
print("type of x = ", type(x))

这产生了以下结果 -

This produce the following result −

x =  None
type of x =  <class 'NoneType'>

Getting Data Type

要获取 Python 中的数据类型,您可以使用 type() 函数。 type() 是一个返回给定对象类的内置函数。

To get the data types in Python, you can use the type() function. The type() is a built-in function that returns the class of the given object.

Example

在以下示例中,我们获取值的类型和变量 −

In the following example, we are getting the type of the values and variables −

# Getting type of values
print(type(123))
print(type(9.99))

# Getting type of variables
a = 10
b = 2.12
c = "Hello"
d = (10, 20, 30)
e = [10, 20, 30]

print(type(a))
print(type(b))
print(type(c))
print(type(d))
print(type(e))

这产生了以下结果 -

This produce the following result −

<class 'int'>
<class 'float'>
<class 'int'>
<class 'float'>
<class 'str'>
<class 'tuple'>
<class 'list'>

Setting Data Type

在 Python 中,在声明变量或对象时,您不需要设置数据类型。数据类型将自动根据分配的值设置。

In Python, during declaring a variable or an object, you don’t need to set the data types. Data type is set automatically based on the assigned value.

Example

以下示例说明了如何根据给定的值设置变量的数据类型 −

The following example, demonstrating how a variable’s data type is set based on the given value −

# Declaring a variable
# And, assigning an integer value

x = 10

# Printing its value and type
print("x = ", x)
print("type of x = ", type(x))

# Now, assigning string value to
# the same variable
x = "Hello World!"

# Printing its value and type
print("x = ", x)
print("type of x = ", type(x))

这产生了以下结果 -

This produce the following result −

x =  10
type of x =  <class 'int'>
x =  Hello World!
type of x =  <class 'str'>

Primitive and Non-primitive Data Types

上面解释的数据类型还可以分为原始数据类型和非原始数据类型。

The above-explained data types can also be categorized as primitive and non-primitive.

1. Primitive Types

原始数据类型是用于创建复杂数据类型(有时称为复杂数据结构)的基本数据类型。主要有四种原始数据类型,分别是 −

The primitive data types are the fundamental data types that are used to create complex data types (sometimes called complex data structures). There are mainly four primitive data types, which are −

  1. Integers

  2. Floats

  3. Booleans, and

  4. Strings

2. Non-primitive Types

非原始数据类型存储值或值集合。主要有四种非原始类型,分别是 −

The non-primitive data types store values or collections of values. There are mainly four types of non-primitive types, which are −

  1. Lists

  2. Tuples

  3. Dictionaries, and

  4. Sets

Python Data Type Conversion

有时,您可能需要在内置数据类型之间执行转换。若要在不同的 Python 数据类型之间转换数据,您只需将类型名称用作函数即可。

Sometimes, you may need to perform conversions between the built-in data types. To convert data between different Python data types, you simply use the type name as a function.

Example

以下是将不同值分别转换为整数、浮点数和字符串值的示例 −

Following is an example which converts different values to integer, floating point and string values respectively −

print("Conversion to integer data type")
a = int(1)     # a will be 1
b = int(2.2)   # b will be 2
c = int("3.3")   # c will be 3

print (a)
print (b)
print (c)

print("Conversion to floating point number")
a = float(1)     # a will be 1.0
b = float(2.2)   # b will be 2.2
c = float("3.3") # c will be 3.3

print (a)
print (b)
print (c)

print("Conversion to string")
a = str(1)     # a will be "1"
b = str(2.2)   # b will be "2.2"
c = str("3.3") # c will be "3.3"

print (a)
print (b)
print (c)

这产生了以下结果 -

This produce the following result −

Conversion to integer data type
1
2
3
Conversion to floating point number
1.0
2.2
3.3
Conversion to string
1
2.2
3.3

Data Type Conversion Functions

有几个 built-in functions 用于执行从一种数据类型到另一种数据类型的转换。这些函数返回表示转换后的值的新对象。

There are several built-in functions to perform conversion from one data type to another. These functions return a new object representing the converted value.

Sr.No.

Function & Description

1

Python int() functionConverts x to an integer. base specifies the base if x is a string.

2

Python long() functionConverts x to a long integer. base specifies the base if x is a string. This function has been deprecated.

3

Python float() functionConverts x to a floating-point number.

4

Python complex() functionCreates a complex number.

5

Python str() functionConverts object x to a string representation.

6

Python repr() functionConverts object x to an expression string.

7

Python eval() functionEvaluates a string and returns an object.

8

Python tuple() functionConverts s to a tuple.

9

Python list() functionConverts s to a list.

10

Python set() functionConverts s to a set.

11

Python dict() functionCreates a dictionary. d must be a sequence of (key,value) tuples.

12

Python frozenset() functionConverts s to a frozen set.

13

Python chr() functionConverts an integer to a character.

14

Python unichr() functionConverts an integer to a Unicode character.

15

Python ord() functionConverts a single character to its integer value.

16

Python hex() functionConverts an integer to a hexadecimal string.

17

Python oct() functionConverts an integer to an octal string.