|An Introduction to Python|
by Guido van Rossum and Fred L. Drake, Jr.
Paperback (6"x9"), 124 pages
RRP £12.95 ($19.95)
Sales of this book support the Python Software Foundation! Get a printed copy>>>
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:
>>> # 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.
The first line contains a multiple assignment: the variables
bsimultaneously 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.
whileloop 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 or equal to),
>=(greater than or equal to) and
!=(not equal to).
- 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.
>>> i = 256*256 >>> print 'The value of i is', i The value of i is 65536A trailing comma avoids the newline after the output:
>>> 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 987Note that the interpreter inserts a newline before it prints the next prompt if the last line was not completed.
|ISBN 0954161769||An Introduction to Python||See the print edition|