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)序列的子序列:
>>> # Fibonacci series: ... # the sum of two elements defines the next ... a, b = 0, 1 >>> while b < 10: ... print b ... a, b = b, a+b ... 1 1 2 3 5 8
This example introduces several new features.
示例中介绍了一些新功能:
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。最后一行又一次使用了这种技术,证明了在赋值之前表达式右边先进行了运算。右边的表达式从左到右运算。
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).
while 循环运行在条件为真时执行。在 Python 中,类似于 C 任何非零值为真,零为假。 这个条件也可以用于字符串或链表,事实上于对任何序列类型,长度非零时为真,空序列为假。示例所用的是一个简单的比较。标准的比较运算符写法和 C 相同: < (小于),> (大于),== (等于),<= (小于等于),>=(大于等于)和!= (不等于)。
循环体是缩进的:缩进是 Python 对语句分组的方法。 Python 还没有提供一个智能编辑功能,你要在每一个缩进行输入一个 tab 或(一个或多个)空格。 实际上你可能会准备更为复杂的文本编辑器来编写你的 Python 程序,大多数文本编辑器都提供了自动缩进功能。交互式的输入一个复杂语句时,需要用一个空行表示完成(因为解释器没办法猜出你什么时候输入最后一行)。需要注意的是每一行都要有相同的缩进来标识这是同一个语句块。
print 语句打印给定表达式的值。它与你仅仅输入你需要的表达式(就像前面的计算器示例)不同,它可以同时输出多个表达式。字符串输出时没有引号,各项之间用一个空格分开,你可以很容易区分它们,如下所示:
>>> i = 256*256 >>> print 'The value of i is', i The value of i is 65536
A trailing comma avoids the newline after the output:
print 语句末尾的逗号避免了输出中的换行:
>>> a, b = 0, 1 >>> while b < 1000: ... print b, ... a, b = b, a+b ... 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
Note that the interpreter inserts a newline before it prints the next prompt if the last line was not completed.
需要注意的是,如果最后一行仍没有写完,解释器会在它打印下一个命令时插入一个新行。