200字范文,内容丰富有趣,生活中的好帮手!
200字范文 > 基本数据类型python_Python中的基本数据类型

基本数据类型python_Python中的基本数据类型

时间:2024-01-29 22:12:27

相关推荐

基本数据类型python_Python中的基本数据类型

基本数据类型python

Now you know how to interact with the Python interpreter and execute Python code. It’s time to dig into the Python language. First up is a discussion of the basic data types that are built into Python.

现在,您知道如何与Python解释器进行交互并执行Python代码 。 现在是时候深入研究Python语言了。 首先是对Python内置的基本数据类型的讨论。

Here’s what you’ll learn in this tutorial:

这是您将在本教程中学到的内容:

You’ll learn about several basicnumeric, string, andBooleantypes that are built into Python. By the end of this tutorial, you’ll be familiar with what objects of these types look like, and how to represent them.You’ll also get an overview of Python’s built-infunctions.These are pre-written chunks of code you can call to do useful things. You have already seen the built-inprint()function, but there are many others. 您将了解Python内置的几种基本数字,字符串布尔类型。 在本教程结束时,您将熟悉这些类型的对象的外观以及如何表示它们。 您还将获得Python内置函数的概述这些是预先编写的代码块,您可以调用它们来做有用的事情。 您已经看过内置的print()函数,但还有许多其他功能。

Get Notified:Don’t miss the follow up to this tutorial—Click here to join the Real Python Newsletter and you’ll know when the next instalment comes out.

通知您:不要错过本教程的后续内容- 单击此处加入Real Python Newslet ,您将知道下一期的发行时间。

整数 (Integers)

In Python 3, there is effectively no limit to how long an integer value can be. Of course, it is constrained by the amount of memory your system has, as are all things, but beyond that an integer can be as long as you need it to be:

在Python 3中,整数值的有效长度实际上没有限制。 当然,它受系统以及所有事物的内存量的限制,但除此之外,整数可以是您需要的整数,只要它是:

>>> >>> printprint (( 123123123123123123123123123123123123123123123123 123123123123123123123123123123123123123123123123 + + 11 ))123123123123123123123123123123123123123123123124123123123123123123123123123123123123123123123124

Python interprets a sequence of decimal digits without any prefix to be a decimal number:

Python将不含任何前缀的十进制数字序列解释为十进制数字:

The following strings can be prepended to an integer value to indicate a base other than 10:

可以将以下字符串添加为整数值,以表示除10以外的底数:

For example:

例如:

>>> >>> printprint (( 00 o10o10 ))88>>> >>> printprint (( 0x100x10 ))1616>>> >>> printprint (( 0b100b10 ))22

For more information on integer values with non-decimal bases, see the following Wikipedia sites: Binary, Octal, and Hexadecimal.

有关具有非十进制基数的整数值的更多信息,请参见以下Wikipedia网站: Binary , Octal和Hexadecimal 。

The underlying type of a Python integer, irrespective of the base used to specify it, is calledint:

不管用来指定它的基数如何,Python整数的基础类型都称为int

Note:This is a good time to mention that if you want to display a value while in a REPL session, you don’t need to use theprint()function. Just typing the value at the>>>prompt and hittingEnterwill display it:

注意:这是提提您在REPL会话中显示值的好时机,不需要使用print()函数。 只需在>>>提示符下键入值,然后按Enter即可显示它:

>>> >>> 10101010>>> >>> 0x100x101616>>> >>> 0b100b1022

Many of the examples in this tutorial series will use this feature.

本教程系列中的许多示例都将使用此功能。

Note that this does not work inside a script file. A value appearing on a line by itself in a script file will not do anything.

请注意,这在脚本文件中不起作用。 脚本文件中一行单独显示的值不会执行任何操作。

浮点数字 (Floating-Point Numbers)

Thefloattype in Python designates a floating-point number.floatvalues are specified with a decimal point. Optionally, the charactereorEfollowed by a positive or negative integer may be appended to specify scientific notation:

Python中的float类型指定浮点数。float值用小数点指定。 可选地,可以在字符eE后跟一个正整数或负整数,以指定科学计数法 :

侧边栏:浮点表示 (Sidebar: Floating-Point Representation)

The following is a bit more in-depth information on how Python represents floating-point numbers internally. You can readily use floating-point numbers in Python without understanding them to this level, so don’t worry if this seems overly complicated. The information is presented here in case you are curious.

以下是有关Python如何在内部表示浮点数的更深入的信息。 您可以很容易地在Python中使用浮点数,而无需了解它们到这个水平,因此如果这看起来过于复杂,请不要担心。 如果您感到好奇,请在此处显示信息。

Almost all platforms represent Pythonfloatvalues as 64-bit “double-precision” values, according to the IEEE 754 standard. In that case, the maximum value a floating-point number can have is approximately 1.8 ⨉ 10308. Python will indicate a number greater than that by the stringinf:

根据IEEE 754标准,几乎所有平台都将Pythonfloat值表示为64位“双精度”值。 在这种情况下,浮点数可以具有的最大值约为1.8×10 308 。 Python将通过字符串inf指示大于该数字的数字:

1.79e3081.79e3081.79e+3081.79e+3081.8e3081.8e308infinf

The closest a nonzero number can be to zero is approximately 5.0 ⨉ 10-324. Anything closer to zero than that is effectively zero:

一个非零数字可以最接近零的近似值是5.0×10 -324 。 接近零的任何东西实际上都是零:

5e-3245e-3245e-3245e-3241e-3251e-3250.00.0

Floating point numbers are represented internally as binary (base-2) fractions. Most decimal fractions cannot be represented exactly as binary fractions, so in most cases the internal representation of a floating-point number is an approximation of the actual value. In practice, the difference between the actual value and the represented value is very small and should not usually cause significant problems.

浮点数在内部以二进制(基2)分数表示。 大多数十进制小数不能完全表示为二进制小数,因此在大多数情况下,浮点数的内部表示是实际值的近似值。 在实践中,实际值与代表值之间的差异很小,通常不应引起重大问题。

Further Reading:For additional information on floating-point representation in Python and the potential pitfalls involved, see Floating Point Arithmetic: Issues and Limitations in the Python documentation.

进一步阅读:有关Python中浮点表示形式以及涉及的潜在陷阱的更多信息,请参见Python文档中的浮点算法:问题和局限性 。

复数 (Complex Numbers)

Complex numbers are specified as<real part>+<imaginary part>j. For example:

复数指定为<real part>+<imaginary part>j。 例如:

>>> >>> 22 ++ 3j3j(2+3j)(2+3j)>>> >>> typetype (( 22 ++ 3j3j ))<class 'complex'><class 'complex'>

弦乐 (Strings)

Strings are sequences of character data. The string type in Python is calledstr.

字符串是字符数据的序列。 Python中的字符串类型称为str

String literals may be delimited using either single or double quotes. All the characters between the opening delimiter and matching closing delimiter are part of the string:

字符串文字可以使用单引号或双引号分隔。 开头定界符和匹配的结束定界符之间的所有字符都是字符串的一部分:

A string in Python can contain as many characters as you wish. The only limit is your machine’s memory resources. A string can also be empty:

Python中的字符串可以包含任意多个字符。 唯一的限制是计算机的内存资源。 字符串也可以为空:

>>> >>> ''''''''

What if you want to include a quote character as part of the string itself? Your first impulse might be to try something like this:

如果要在字符串本身中包含引号字符怎么办? 您的第一冲动可能是尝试这样的事情:

As you can see, that doesn’t work so well. The string in this example opens with a single quote, so Python assumes the next single quote, the one in parentheses which was intended to be part of the string, is the closing delimiter. The final single quote is then a stray and causes the syntax error shown.

如您所见,这并不是很好。 此示例中的字符串以单引号引起来,因此Python假定下一个单引号(作为括号的一部分,该括号应作为字符串的一部分)是结束定界符。 最后的单引号是一个流浪,并导致显示语法错误。

If you want to include either type of quote character within the string, the simplest way is to delimit the string with the other type. If a string is to contain a single quote, delimit it with double quotes and vice versa:

如果要在字符串中包括两种引号字符,则最简单的方法是用另一种类型来分隔字符串。 如果字符串包含单引号,则用双引号将其定界,反之亦然:

>>> >>> printprint (( "This string contains a single quote (') character.""This string contains a single quote (') character." ))This string contains a single quote (') character.This string contains a single quote (') character.>>> >>> printprint (( 'This string contains a double quote (") character.''This string contains a double quote (") character.' ))This string contains a double quote (") character.This string contains a double quote (") character.

字符串中的转义序列 (Escape Sequences in Strings)

Sometimes, you want Python to interpret a character or sequence of characters within a string differently. This may occur in one of two ways:

有时,您希望Python对字符串中的字符或字符序列进行不同的解释。 这可能以两种方式之一发生:

You may want to suppress the special interpretation that certain characters are usually given within a string.You may want to apply special interpretation to characters in a string which would normally be taken literally. 您可能想抑制特殊解释,即某些字符通常在字符串中给出。 您可能想对字符串中的字符应用特殊的解释,这通常会从字面上理解。

You can accomplish this using a backslash () character. A backslash character in a string indicates that one or more characters that follow it should be treated specially. (This is referred to as an escape sequence, because the backslash causes the subsequent character sequence to “escape” its usual meaning.)

您可以使用反斜杠()字符。 字符串中的反斜杠字符表示应特别对待其后的一个或多个字符。 (这被称为转义序列,因为反斜杠导致后续字符序列“转义”其通常的含义。)

Let’s see how this works.

让我们看看它是如何工作的。

禁止特殊字符含义 (Suppressing Special Character Meaning)

You have already seen the problems you can come up against when you try to include quote characters in a string. If a string is delimited by single quotes, you can’t directly specify a single quote character as part of the string because, for that string, the single quote has special meaning—it terminates the string:

您已经看到了尝试在字符串中包含引号字符时可能遇到的问题。 如果字符串由单引号引起来,则不能直接将单引号字符指定为字符串的一部分,因为对于该字符串,单引号具有特殊含义-它终止字符串:

Specifying a backslash in front of the quote character in a string “escapes” it and causes Python to suppress its usual special meaning. It is then interpreted simply as a literal single quote character:

在字符串中的引号字符前面指定反斜杠可以使它“转义”,并导致Python取消其通常的特殊含义。 然后将其简单地解释为文字单引号字符:

>>> >>> printprint (( 'This string contains a single quote ('This string contains a single quote ( '' ) character.') character.' ))This string contains a single quote (') character.This string contains a single quote (') character.

The same works in a string delimited by double quotes as well:

同样在用双引号分隔的字符串中也起作用:

The following is a table of escape sequences which cause Python to suppress the usual special interpretation of a character in a string:

下表是转义序列的表,这些转义序列使Python禁止对字符串中的字符进行通常的特殊解释:

Ordinarily, a newline character terminates line input. So pressingEnterin the middle of a string will cause Python to think it is incomplete:

通常,换行符会终止行输入。 因此,在字符串中间按Enter键会使Python认为它不完整:

>>> >>> printprint (( 'a'aSyntaxError: EOL while scanning string literalSyntaxError: EOL while scanning string literal

To break up a string over more than one line, include a backslash before each newline, and the newlines will be ignored:

要在多行中分解一个字符串,请在每个换行符前添加一个反斜杠,并且这些换行符将被忽略:

To include a literal backslash in a string, escape it with a backslash:

要在字符串中包含文字反斜杠,请使用反斜杠对其进行转义:

>>> >>> printprint (( 'foo'foo bar'bar' ))foobarfoobar

对字符应用特殊含义 (Applying Special Meaning to Characters)

Next, suppose you need to create a string that contains a tab character in it. Some text editors may allow you to insert a tab character directly into your code. But many programmers consider that poor practice, for several reasons:

接下来,假设您需要创建一个包含制表符的字符串。 某些文本编辑器可能允许您将制表符直接插入代码中。 但是许多程序员认为这种做法很差,原因有以下几点:

The computer can distinguish between a tab character and a sequence of space characters, but you can’t. To a human reading the code, tab and space characters are visually indistinguishable.Some text editors are configured to automatically eliminate tab characters by expanding them to the appropriate number of spaces.Some Python REPL environments will not insert tabs into code. 计算机可以区分制表符和空格字符,但是不能。 对于阅读代码的人来说,制表符和空格字符在视觉上是无法区分的。 某些文本编辑器配置为通过将制表符字符扩展到适当的空格数来自动消除制表符。 某些Python REPL环境不会在代码中插入制表符。

In Python (and almost all other common computer languages), a tab character can be specified by the escape sequencet:

在Python(以及几乎所有其他常见的计算机语言)中,可以使用转义序列t指定制表符:

The escape sequencetcauses thetcharacter to lose its usual meaning, that of a literalt. Instead, the combination is interpreted as a tab character.

转义序列t导致t字符失去其通常的含义,即文字t。 而是将组合解释为制表符。

Here is a list of escape sequences that cause Python to apply special meaning instead of interpreting literally:

这是导致Python应用特殊含义而不是逐字解释的转义序列的列表:

Examples:

例子:

>>> >>> printprint (( "a"a tt b"b" ))a ba b>>> >>> printprint (( "a"a 141x61141x61 "" ))aaaaaa>>> >>> printprint (( "a"a nn b"b" ))aabb>>> >>> printprint (( '' u2192u2192 N{rightwards arrow}N{rightwards arrow} '' ))→ →→ →

This type of escape sequence is typically used to insert characters that are not readily generated from the keyboard or are not easily readable or printable.

这种类型的转义序列通常用于插入不容易从键盘生成或不易于阅读或打印的字符。

原始字符串 (Raw Strings)

A raw string literal is preceded byrorR, which specifies that escape sequences in the associated string are not translated. The backslash character is left in the string:

原始字符串文字以rR,该rR指定不转换关联字符串中的转义序列。 反斜杠字符留在字符串中:

三重引用的字符串 (Triple-Quoted Strings)

There is yet another way of delimiting strings in Python. Triple-quoted strings are delimited by matching groups of three single quotes or three double quotes. Escape sequences still work in triple-quoted strings, but single quotes, double quotes, and newlines can be included without escaping them. This provides a convenient way to create a string with both single and double quotes in it:

在Python中还有另一种定界字符串的方法。 三引号字符串由匹配的三个单引号或三个双引号的组分隔。 转义序列仍然可以用三引号引起来,但可以包含单引号,双引号和换行符而不必转义。 这提供了一种创建带有单引号和双引号的字符串的便捷方法:

>>> >>> printprint (( '''This string has a single (') and a double (") quote.''''''This string has a single (') and a double (") quote.''' ))This string has a single (') and a double (") quote.This string has a single (') and a double (") quote.

Because newlines can be included without escaping them, this also allows for multiline strings:

由于可以包含换行符而无需转义它们,因此这也允许使用多行字符串:

You will see in the upcoming tutorial on Python Program Structure how triple-quoted strings can be used to add an explanatory comment to Python code.

您将在即将到来的有关Python程序结构的教程中看到如何使用三引号引起来的字符串向Python代码添加解释性注释。

布尔类型,布尔上下文和“真实性” (Boolean Type, Boolean Context, and “Truthiness”)

Python 3 provides a Boolean data type. Objects of Boolean type may have one of two values (TrueorFalse):

Python 3提供了布尔数据类型。 布尔类型的对象可能具有两个值之一(TrueFalse):

>>> >>> typetype (( TrueTrue ))<class 'bool'><class 'bool'>>>> >>> typetype (( FalseFalse ))<class 'bool'><class 'bool'>

As you will see in upcoming tutorials, expressions in Python are often evaluated in Boolean context, meaning they are interpreted to represent truth or falsehood. A value that is true in Boolean context is sometimes said to be “truthy,” and one that is false in Boolean context is said to be “falsy.” (You may also see “falsy” spelled “falsey.”)

正如您将在即将到来的教程中看到的那样,Python中的表达式通常在布尔上下文中求值,这意味着它们被解释为代表真假。 在布尔上下文中为true的值有时被称为“真值”,在布尔上下文中为false的值有时被称为“虚假”。 (您可能还会看到“ falsy”拼写为“ falsey”。)

The “truthiness” of an object of Boolean type is self-evident: Boolean objects that are equal toTrueare truthy (true), and those equal toFalseare falsy (false). But non-Boolean objects can be evaluated in Boolean context as well and determined to be true or false.

布尔类型对象的“真实性”是不言而喻的:等于True布尔对象是True的(true),等于False布尔对象是False的(false)。 但是,也可以在布尔上下文中评估非布尔对象,并将其确定为true或false。

You will learn more about evaluation of objects in Boolean context when you encounter logical operators in the upcoming tutorial on operators and expressions in Python.

在即将到来的Python运算符和表达式教程中,当您遇到逻辑运算符时,您将学到更多关于布尔上下文中对象评估的知识。

内建功能 (Built-In Functions)

The Python interpreter supports many functions that are built-in: sixty-eight, as of Python 3.6. You will cover many of these in the following discussions, as they come up in context.

Python解释器支持许多内置功能:从Python 3.6开始为68。 在上下文中,您将在以下讨论中涵盖其中的许多内容。

For now, a brief overview follows, just to give a feel for what is available. See the Python documentation on built-in functions for more detail. Many of the following descriptions refer to topics and concepts that will be discussed in future tutorials.

现在,将进行简要概述,以使您对现有功能有所了解。 有关更多详细信息,请参见内置函数的Python文档 。 以下许多描述都涉及将在以后的教程中讨论的主题和概念。

数学 (Math)

类型转换 (Type Conversion)

可迭代和迭代器 (Iterables and Iterators)

复合数据类型 (Composite Data Type)

类,属性和继承 (Classes, Attributes, and Inheritance)

输入输出 (Input/Output)

变量,引用和范围 (Variables, References, and Scope)

杂 (Miscellaneous)

结论 (Conclusion)

In this tutorial, you learned about the built-indata typesandfunctionsPython provides.

在本教程中,您了解了Python提供的内置数据类型功能

The examples given so far have all manipulated and displayed only constant values. In most programs, you are usually going to want to create objects that change in value as the program executes.

到目前为止给出的示例都已操纵并仅显示恒定值。 在大多数程序中,通常需要创建随程序执行而值改变的对象。

Head to the next tutorial to learn about Pythonvariables.

前往下一个教程,了解Python变量。

Don’t miss the follow up tutorial:Click here to join the Real Python Newsletter and you’ll know when the next instalment comes out.

不要错过后续教程:单击此处加入Real Python Newslet ,您将知道下一期的发行时间。

«Interacting with Python«与Python交互 Basic Data Types in PythonPython中的基本数据类型 Variables in Python»Python中的变量»

[ Improve Your Python With 🐍 Python Tricks 💌 – Get a short & sweet Python Trick delivered to your inbox every couple of days. >> Click here to learn more and see examples ]

[通过🐍Python技巧Improve改进Python –每两天将简短而可爱的Python技巧传递到您的收件箱。>>单击此处了解更多信息,并查看示例 ]

翻译自: //06/basic-data-types-in-python/

基本数据类型python

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。