The Python Tutorial 3.2-3 An Informal Introduction to Python(Python简介)

来源:互联网 发布:会员积分管理系统源码 编辑:程序博客网 时间:2024/06/06 20:55

3. An Informal Introduction to Python(Python简介)


In the following examples, input and output are distinguished by the presence or absence of prompts (>>> and ...): to repeat the example, you must type everything after the prompt, when the prompt appears; lines that do not begin with a prompt are output from the interpreter. Note that a secondary prompt on a line by itself in an example means you must type a blank line; this is used to end a multi-line command.

在下面的示例中,我们通过有没有提示符( >>> 或 ... )来区分输入和输出:为了试验示例,你必须在提示符出现时输入其后的所有内容;那些不以提示符开头的行是Python解释器的输出内容。注意示例中某行内出现从提示符意味着你必须输入一个空白行,这被用来结束多行命令输入。

Many of the examples in this manual, even those entered at the interactive prompt, include comments. Comments in Python start with the hash character, #, and extend to the end of the physical line. A comment may appear at the start of a line or following whitespace or code, but not within a string literal. A hash character within a string literal is just a hash character. Since comments are to clarify code and are not interpreted by Python, they may be omitted when typing in examples.

本手册中的很多示例,甚至那些在交互提示符下的输入,都包含有注释。 Python中的注释以特殊字符 # 开始,直到物理行的结束。注释可以出现在一行的开始位置,也可以跟在空白字符或代码后面,但是不能包含在字符串中间。在字符串中的特殊字符就是其字面意思。由于注释是用来说明代码的,并且不会被Python解释执行,可以在输入示例时将他们省略。

Some examples:

一些示例:

# this is the first commentSPAM = 1                 # and this is the second comment                         # ... and now a third!STRING = "# This is not a comment."

3.1. Using Python as a Calculator(将Pyhon作为计算器)

Let’s try some simple Python commands. Start the interpreter and wait for the primary prompt, >>>. (It shouldn’t take long.)

让我们练习一些简单的Python命令。启动Python解释器并等待主提示符 >>> 出现(这并不需要多久)。

3.1.1. Numbers(数字)

The interpreter acts as a simple calculator: you can type an expression at it and it will write the value. Expression syntax is straightforward: the operators +, -, * and / work just like in most other languages (for example, Pascal or C); parentheses can be used for grouping. For example:

将Python解释器作为一个简单的计算器:你可以输入一个表达式,计算器会返回其值。表达式语言很简单: + , - , * 和 / (加、减、乘、除)运算符像在大多数其他语言中一样工作(例如,Pascal或C);括号( ( 和 ) )可以用来分组(结合律)。例如:

>>> 2+24>>> # This is a comment... 2+24>>> 2+2  # and a comment on the same line as code4>>> (50-5*6)/45.0>>> 8/5 # Fractions aren't lost when dividing integers1.6

Note: You might not see exactly the same result; floating point results can differ from one machine to another. We will say more later about controlling the appearance of floating point output. See also Floating Point Arithmetic: Issues and Limitations for a full discussion of some of the subtleties of floating point numbers and their representations.

注意:有时你可能会得到不同的结果;浮点数在不同机器上的运算结果可能是不同的。后面我们将对控制浮点数输出的显示结果做更多说明;完整的关于符点数和其表示的讨论请参照 Floating Point Arithmetic: Issues and Limitations 浮点数运算:问题和限制 章节。

To do integer division and get an integer result, discarding any fractional result, there is another operator, //:

对整数做除法运算并想去除小数部分取得整数结果时,可以使用另外一个运算符, // :

>>> # Integer division returns the floor:... 7//32>>> 7//-3-3

The equal sign ('=') is used to assign a value to a variable. Afterwards, no result is displayed before the next interactive prompt:

在Python中,等号( '=' )符号被用于给变量赋值。随后,在下一个交互提示符前不会有任何输出结果:

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

A value can be assigned to several variables simultaneously:

你可以同时给几个变量赋一个值。

>>> x = y = z = 0  # Zero x, y and z>>> x0>>> y0>>> z0

Variables must be “defined” (assigned a value) before they can be used, or an error will occur:

在Python中,变量在使用前必须“定义”,否则就会引发错误:

>>> # try to access an undefined variable... nTraceback (most recent call last):  File "", line 1, in NameError: name 'n' is not defined

There is full support for floating point; operators with mixed type operands convert the integer operand to floating point:

Python完全支持浮点数,在混合类型操作数运算中整数将被转换为浮点数:

>>> 3 * 3.75 / 1.57.5>>> 7.0 / 23.5

Complex numbers are also supported; imaginary numbers are written with a suffix of j or J. Complex numbers with a nonzero real component are written as (real+imagj), or can be created with the complex(real, imag) function.

同样,Python也支持复数,虚数以 j 或 J 结尾。实部为非零的复数写作 (real+imagj) ,或者通过 complex(real,imag) 构造方法创建。

>>> 1j * 1J(-1+0j)>>> 1j * complex(0, 1)(-1+0j)>>> 3+1j*3(3+3j)>>> (3+1j)*3(9+3j)>>> (1+2j)/(1+1j)(1.5+0.5j)

Complex numbers are always represented as two floating point numbers, the real and imaginary part. To extract these parts from a complex number z, use z.real and z.imag.

复数总是被当做两个浮点数表示:实部和虚部。可以使用 z.real 和 z.imag 从复数 z 中获得这两个部分。

>>> a=1.5+0.5j>>> a.real1.5>>> a.imag0.5

The conversion functions to floating point and integer (float(), int()) don’t work for complex numbers — there is not one correct way to convert a complex number to a real number. Use abs(z) to get its magnitude (as a float) or z.real to get its real part:

整数和浮点数转换函数( int() , float() )均不能用于复数 — 实际上并没有一种正确的方法能将复数转换为实数。使用 abs(z) 可以得到复数 z 的模(以浮点数形式表示)或者使用 z.real 得到它的实部。

>>> a=3.0+4.0j>>> float(a)Traceback (most recent call last):  File "", line 1, in ?TypeError: can't convert complex to float; use abs(z)>>> a.real3.0>>> a.imag4.0>>> abs(a)  # sqrt(a.real**2 + a.imag**2)5.0

In interactive mode, the last printed expression is assigned to the variable _. This means that when you are using Python as a desk calculator, it is somewhat easier to continue calculations, for example:

在交互模式下,最后一次表达式输出被赋予变量 _ 。这说明当你把Python当做桌面计算器使用时,可以很方便的进行连续计算。例如:

>>> tax = 12.5 / 100>>> price = 100.50>>> price * tax12.5625>>> price + _113.0625>>> round(_, 2)113.06

This variable should be treated as read-only by the user. Don’t explicitly assign a value to it — you would create an independent local variable with the same name masking the built-in variable with its magic behavior.

对于用户而言此变量应该是只读的。不要明确的对其作赋值操作 — 如此你将创建一个独立的同名局部变量,并屏蔽具有魔术行为的内置变量。

3.1.2. Strings(字符串)

Besides numbers, Python can also manipulate strings, which can be expressed in several ways. They can be enclosed in single quotes or double quotes:

除了数值,Python还可以通过几种方式操作字符串。字符串可以是用单引号(’)或双引号(”)包围。

>>> 'spam eggs''spam eggs'>>> 'doesn\'t'"doesn't">>> "doesn't""doesn't">>> '"Yes," he said.''"Yes," he said.'>>> "\"Yes,\" he said."'"Yes," he said.'>>> '"Isn\'t," she said.''"Isn\'t," she said.'

The interpreter prints the result of string operations in the same way as they are typed for input: inside quotes, and with quotes and other funny characters escaped by backslashes, to show the precise value. The string is enclosed in double quotes if the string contains a single quote and no double quotes, else it’s enclosed in single quotes. The print() function produces a more readable output for such input strings.

Python解释器按照字符串被输入的方式打印字符串结果:为了显示准确的值,字符串包含在成对的引号中,引号和其他特殊字符要用反斜线( \ )转译。如果字符串只包含单引号( ' )而没有双引号( " )就可以用双引号( " )包围,反之用单引号( ' )包围。再强调一下, print() 函数可以生成可读性更好的输出。

String literals can span multiple lines in several ways. Continuation lines can be used, with a backslash as the last character on the line indicating that the next line is a logical continuation of the line:

有几种方法可以让字符串文本显示为多行。你可以使用连续行:通过在行尾添加一个反斜线( \ )表示下一行是它逻辑上的延续。

hello = "This is a rather long string containing\n\several lines of text just as you would do in C.\n\    Note that whitespace at the beginning of the line is\ significant."print(hello)

Note that newlines still need to be embedded in the string using \n – the newline following the trailing backslash is discarded. This example would print the following:

注意:还是要在字符串中插入 \n 来换行,反斜线( \ )后面的换行会被忽略。这个例子将会输出以下内容:

This is a rather long string containingseveral lines of text just as you would do in C.    Note that whitespace at the beginning of the line is significant.

Or, strings can be surrounded in a pair of matching triple-quotes: """ or '''. End of lines do not need to be escaped when using triple-quotes, but they will be included in the string. So the following uses one escape to avoid an unwanted initial blank line.\

或者,字符串也可以用三引号'''和"""来表示。在三引号中换行\n,',"不需转义。所以下面使用用一个\可以避免不想要的初始空行。

print("""\Usage: thingy [OPTIONS]     -h                        Display this usage message     -H hostname               Hostname to connect to""")

produces the following output:

产生如下的输出:

Usage: thingy [OPTIONS]     -h                        Display this usage message     -H hostname               Hostname to connect to

If we make the string literal a “raw” string, \n sequences are not converted to newlines, but the backslash at the end of the line, and the newline character in the source, are both included in the string as data. Thus, the example:

如果我们将字符串文本表示为原始值(即Python中字符串的 r 作用符), \n (换行符)序列不会被转换为换行,并且行尾的反斜线( \ )和代码中的换行符都将作为数据包含在字符串中。如下所示:

hello = r"This is a rather long string containing\n\several lines of text much as you would do in C."print(hello)

would print:

将会输出:

This is a rather long string containing\n\several lines of text much as you would do in C.

Strings can be concatenated (glued together) with the + operator, and repeated with *:

字符串可以使用 + 符号(加号)连接,并可以使用 * 符号(星号)重复:

>>> word = 'Help' + 'A'>>> word'HelpA'>>> '<' + word*5 + '>''<HelpAHelpAHelpAHelpAHelpA>'

Two string literals next to each other are automatically concatenated; the first line above could also have been written word = 'Help' 'A'; this only works with two literals, not with arbitrary string expressions:

两个彼此相邻的字符串文本常量可以自动的连接起来,上面第一行的列子也可以写成 word = 'Help' 'A' 的形式。这只能用于两个字符串文本常量中,而不能用于两个字符串表达式中。

>>> 'str' 'ing'                   #  <-  This is ok'string'>>> 'str'.strip() + 'ing'   #  <-  This is ok'string'>>> 'str'.strip() 'ing'     #  <-  This is invalid  File "<stdin>", line 1, in ?    'str'.strip() 'ing'                      ^SyntaxError: invalid syntax

Strings can be subscripted (indexed); like in C, the first character of a string has subscript (index) 0. There is no separate character type; a character is simply a string of size one. As in the Icon programming language, substrings can be specified with the slice notation: two indices separated by a colon.

字符串可以通过下标引用,和C语言一样,第一个字符的下标是 0 。 Python中没有单独的字符类型,单个字符就是只包含一个字符的字符串。类似Icon编程语言,子字符串可以使用 切片标记 来指定:使用冒号分割的两个下标索引。

>>> word[4]'A'>>> word[0:2]'He'>>> word[2:4]'lp'

Slice indices have useful defaults; an omitted first index defaults to zero, an omitted second index defaults to the size of the string being sliced.

索引切片具有实用的默认值:如果省略第一个索引,则默认为 0 ;如果省略第二个索引,则默认为被操作字符串的长度。

>>> word[:2]    # The first two characters'He'>>> word[2:]    # Everything except the first two characters'lpA'

Unlike a C string, Python strings cannot be changed. Assigning to an indexed position in the string results in an error:

不同于C语言的字符串,在Python中字符串是不可改变的。尝试通过索引给字符串赋值将引发错误!

>>> word[0] = 'x'Traceback (most recent call last):  File "", line 1, in ?TypeError: 'str' object does not support item assignment>>> word[:1] = 'Splat'Traceback (most recent call last):  File "", line 1, in ?TypeError: 'str' object does not support slice assignment

However, creating a new string with the combined content is easy and efficient:

然而,通过联合创建字符串即简单又高效。

>>> 'x' + word[1:]'xelpA'>>> 'Splat' + word[4]'SplatA'

Here’s a useful invariant of slice operations: s[:i] + s[i:] equals s.

切片操作具有一个有用的恒等特性: s[:i] + s[i:] 等于 "s"。

>>> word[:2] + word[2:]'HelpA'>>> word[:3] + word[3:]'HelpA'

Degenerate slice indices are handled gracefully: an index that is too large is replaced by the string size, an upper bound smaller than the lower bound returns an empty string.

Python能够优雅的处理那些没有意义的切片索引:一个过大的索引值(即下标值大于字符串实际长度)将被字符串实际长度所代替,当上边界比下边界大时(即切片左值大于右值)就返回空字符串。

>>> word[1:100]'elpA'>>> word[10:]''>>> word[2:1]''

Indices may be negative numbers, to start counting from the right. For example:

索引也可以是负数,这将导致从右边开始计算。例如:

>>> word[-1]     # The last character'A'>>> word[-2]     # The last-but-one character'p'>>> word[-2:]    # The last two characters'pA'>>> word[:-2]    # Everything except the last two characters'Hel'

But note that -0 is really the same as 0, so it does not count from the right!

请注意 -0 实际上就是 0 ,所以它不会导致从右边开始计算!

>>> word[-0]     # (since -0 equals 0)'H'

Out-of-range negative slice indices are truncated, but don’t try this for single-element (non-slice) indices:

超过边界的负数索引将被截断,但不要尝试对单元素(非切片操作)做如此操作。

>>> word[-100:]'HelpA'>>> word[-10]    # errorTraceback (most recent call last):  File "", line 1, in ?IndexError: string index out of range

One way to remember how slices work is to think of the indices as pointingbetween characters, with the left edge of the first character numbered 0. Then the right edge of the last character of a string of n characters has index n, for example:

理解切片如何工作的一种方式就是把索引想象成字符之间 的指针,第一个字符左边是数字 0 。那么包含 n 个字符的字符串最后一个字符的右边索引即是 n ,例如:

 +---+---+---+---+---+ | H | e | l | p | A | +---+---+---+---+---+ 0   1   2   3   4   5-5  -4  -3  -2  -1

The first row of numbers gives the position of the indices 0...5 in the string; the second row gives the corresponding negative indices. The slice from i to j consists of all characters between the edges labeled i and j, respectively.

第一行数字显示了字符串中索引0...5的位置,第二行数字显示了对应的负数索引。从 i 到 j 之间的切片由这两个标记之间的所有字符组成。

For non-negative indices, the length of a slice is the difference of the indices, if both are within bounds. For example, the length of word[1:3] is 2.

对于非负索引,如果索引在边界内,切片的长度是两个索引的差。例如, word[1:3] 的长度是2

The built-in function len() returns the length of a string:

内置函数 len() 返回字符串的实际长度。

>>> s = 'supercalifragilisticexpialidocious'>>> len(s)34

See also

同时也参见

Sequence Types — str, bytes, bytearray, list, tuple, range (序列--str, bytes, bytearray, list, tuple, range)
Strings are examples of sequence types, and support the common operations supported by such types.
String Methods (字符串方法)
Strings support a large number of methods for basic transformations and searching.
String Formatting (字符串格式化)
Information about string formatting with str.format() is described here.Old String Formatting Operations (旧的字符串格式化操作) The old formatting operations invoked when strings and Unicode strings are the left operand of the % operator are described in more detail here.

3.1.3. About Unicode(关于Unicode)

Starting with Python 3.0 all strings support Unicode (see http://www.unicode.org/).

从Python 3.0开始所有的字符串都支持Unicode(参考 http://www.unicode.org )。

Unicode has the advantage of providing one ordinal for every character in every script used in modern and ancient texts. Previously, there were only 256 possible ordinals for script characters. Texts were typically bound to a code page which mapped the ordinals to script characters. This lead to very much confusion especially with respect to internationalization (usually written as i18n — 'i' + 18 characters + 'n') of software. Unicode solves these problems by defining one code page for all scripts.

Unicode为古代或现代每种语言文本中使用的每个字符提供了统一编码。以前,只有256个可用的语言字符编码,文本被绑定到将编码映射到语言字符的代码页上。这使得软件的国际化(通常写作 i18n — i +18个字符+ n )极为困难。 Unicode通过为所有的语言定义一个代码页解决了这个问题。

If you want to include special characters in a string, you can do so by using the Python Unicode-Escape encoding. The following example shows how:

如果想在字符串中包含特殊字符,你可以使用Python的 Unicode_Escape 编码方式。下面的列子展示了如何这样做:

>>> 'Hello\u0020World !''Hello World !'

The escape sequence \u0020 indicates to insert the Unicode character with the ordinal value 0x0020 (the space character) at the given position.

转码序列 \u0020 表示在指定位置插入编码为0x0020的Unicode字符(空格)。

Other characters are interpreted by using their respective ordinal values directly as Unicode ordinals. If you have literal strings in the standard Latin-1 encoding that is used in many Western countries, you will find it convenient that the lower 256 characters of Unicode are the same as the 256 characters of Latin-1.

其他字符就像Unicode编码一样被直接解释为对应的编码值。如果你有在许多西方国家使用的标准Latin-1编码的字符串,你会发现编码小于256的Unicode字符和在Latin-1编码中的一样

Apart from these standard encodings, Python provides a whole set of other ways of creating Unicode strings on the basis of a known encoding.To convert a string into a sequence of bytes using a specific encoding, string objects provide an encode() method that takes one argument, the name of the encoding. Lowercase names for encodings are preferred.

除了这些标准编码,Python还提供了一整套基于其他已知编码创建Unicode字符串的方法。字符串对象提供了一个 encode() 方法用以将字符串转换成特定编码的字节序列,它接收一个小写的编码名称作为参数。

>>> "Äfel".encode('utf-8')b'\xc3\x84pfel'

3.1.4. Lists(列表)

Python knows a number of compound data types, used to group together other values. The most versatile is the list, which can be written as a list of comma-separated values (items) between square brackets. List items need not all have the same type.

Python支持几种 复合 数据类型,用来对其他值进行分组。最常用的是 列表(list) ,在中括号中用逗号分隔的一系列值(项)。列表中的项不需要是同一种类型。

>>> a = ['spam', 'eggs', 100, 1234]>>> a['spam', 'eggs', 100, 1234]

Like string indices, list indices start at 0, and lists can be sliced, concatenated and so on:

类似字符串索引,列表索引也是从 0 开始,并且列表也可作切片、连接等操作。

>>> a[0]'spam'>>> a[3]1234>>> a[-2]100>>> a[1:-1]['eggs', 100]>>> a[:2] + ['bacon', 2*2]['spam', 'eggs', 'bacon', 4]>>> 3*a[:3] + ['Boo!']['spam', 'eggs', 100, 'spam', 'eggs', 100, 'spam', 'eggs', 100, 'Boo!']

All slice operations return a new list containing the requested elements. This means that the following slice returns a shallow copy of the list a:

所有的切片操作都会返回一个包含了必需元素的新列表,这就意味些如下示例中切片返回列表a的复制

>>> a[:]['spam', 'eggs', 100, 1234]

Unlike strings, which are immutable, it is possible to change individual elements of a list:

与字符串的 不可变性 不同,列表中每个元素都是可变的。

>>> a['spam', 'eggs', 100, 1234]>>> a[2] = a[2] + 23>>> a['spam', 'eggs', 123, 1234]

Assignment to slices is also possible, and this can even change the size of the list or clear it entirely:

给列表切片赋值也是允许的,甚至可以改变它的大小或清空整个列表。

>>> # Replace some items:... a[0:2] = [1, 12]>>> a[1, 12, 123, 1234]>>> # Remove some:... a[0:2] = []>>> a[123, 1234]>>> # Insert some:... a[1:1] = ['bletch', 'xyzzy']>>> a[123, 'bletch', 'xyzzy', 1234]>>> # Insert (a copy of) itself at the beginning>>> a[:0] = a>>> a[123, 'bletch', 'xyzzy', 1234, 123, 'bletch', 'xyzzy', 1234]>>> # Clear the list: replace all items with an empty list>>> a[:] = []>>> a[]

The built-in function len() also applies to lists:

内置函数 len() 同样可以作用于列表。

>>> a = ['a', 'b', 'c', 'd']>>> len(a)4

It is possible to nest lists (create lists containing other lists), for example:

你可以将列表嵌套使用(创建包含其他列表的列表),例如:

>>> q = [2, 3]>>> p = [1, q, 4]>>> len(p)3>>> p[1][2, 3]>>> p[1][0]2

You can add something to the end of the list:

你可以在列表末尾添加内容:

>>> p[1].append('xtra')>>> p[1, [2, 3, 'xtra'], 4]>>> q[2, 3, 'xtra']

Note that in the last example, p[1] and q really refer to the same object! We’ll come back to object semantics later.

注意:在最后的列子里, p[1] 和 q 实际上指向同一个对象!我们将在后面讨论 对象语法 。

3.2. First Steps Towards Programming(迈向编程的第一步)

Of course, we can use Python for more complicated tasks than adding two and two together. For instance, we can write an initial sub-sequence of the Fibonacci series as follows:

当然,我们可以用Python作比2加2更复杂的任务。例如,我们可以像下面一样写出 菲波那契数 序列的初始子序列:

>>> # Fibonacci series:... # the sum of two elements defines the next... a, b = 0, 1>>> while b < 10:...     print(b)...     a, b = b, a+b...112358

This example introduces several new features.

这个例子展示了几个新功能。

The first line contains a multiple assignment: the variables a and b simultaneously get the new values 0 and 1. On the last line this is used again, demonstrating that the expressions on the right-hand side are all evaluated first before any of the assignments take place. The right-hand side expressions are evaluated from the left to the right.

第一行包含了一条 多项赋值 表达式:变量 a 和 b 同时得到新值 0 和 1 。最后一行我们又一次这样使用,这说明等号右边的表达式在任何赋值前被首先计算。等号右边的表达式遵从从左向右的求值顺序。

The while loop executes as long as the condition (here: b < 10) remains true. In Python, like in C, any non-zero integer value is true; zero is false. The condition may also be a string or list value, in fact any sequence; anything with a non-zero length is true, empty sequences are false. The test used in the example is a simple comparison. The standard comparison operators are written the same as in C: < (less than), > (greater than), == (equal to), <= (less than or equal to), >= (greater than or equal to) and != (not equal to).

只要条件(此处为: b < 10 )为真 while 循环就会一直执行。像C语言一样,在Python中任何非零的整数值都为 True ,0为 False 。条件也可以是一个字符串或列表值,事实上可以是任何序列,所有长度非零的序列都是 True ,空的序列为 False 。例子中使用的测试是一个简单的比较。标准的比较操作符和C语言中的写法一样: < (小于)、 > (大于)、 == (等于)、 <= (小于等于)、 >= (大于等于)和 != (不等于)。

The body of the loop is indented: indentation is Python’s way of grouping statements. Python does not (yet!) provide an intelligent input line editing facility, so you have to type a tab or space(s) for each indented line. In practice you will prepare more complicated input for Python with a text editor; most text editors have an auto-indent facility. When a compound statement is entered interactively, it must be followed by a blank line to indicate completion (since the parser cannot guess when you have typed the last line). Note that each line within a basic block must be indented by the same amount.

循环的 主体 是 缩进 代码块:缩进是Python语法分组的方法。 Python(仍然!)没有提供一种智能的行输入功能,所以你必须为每个缩进行输入制表符(Tab)或空格(Space)。实践中你应该准备一个文本编辑器来应对更复杂的Python代码输入,大多数文本编辑器都具备自动缩进功能。当交互式的输入一个复合语句时,必须在其后输入一个空行以表明输入完成(因为解释器无法猜出你什么时候输入最后一行)。注意:在同一层的代码块中的每行必须具有相同数目的缩进。

The print() function writes the value of the expression(s) it is given. It differs from just writing the expression you want to write (as we did earlier in the calculator examples) in the way it handles multiple expressions, floating point quantities, and strings. Strings are printed without quotes, and a space is inserted between items, so you can format things nicely, like this:

输出函数 print() 将给定的表达式输出。与简单的以你想要输出的表达式输出方式不同(像前面我们在计算器示例中的做法),它可以处理多个表达式,大浮点数或字符串。字符串被不带引号的打印,并且两项之间会插入一个空格,所以你可以更好的格式化字符串,列如:

>>> i = 256*256>>> print('The value of i is', i)The value of i is 65536

The keyword end can be used to avoid the newline after the output, or end the output with a different string:

关键字 end (参数)可以用来避免输出后面出现换行,或者用不同的字符串结束输出。

>>> a, b = 0, 1>>> while b < 1000:...     print(b, end=',')...     a, b = b, a+b...1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,