Page 22 - Python Tutorial
P. 22
Python Tutorial, Release 3.7.0
>>> a = ['a', 'b', 'c']
>>> n = [1, 2, 3]
>>> x = [a, n]
>>> x
[['a', 'b', 'c'], [1, 2, 3]]
>>> x[0]
['a', 'b', 'c']
>>> x[0][1]
'b'
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 a < 10:
... print(a)
... a, b = b, a+b
...
0
1
1
2
3
5
8
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.
• The while loop executes as long as the condition (here: a < 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).
• The body of the loop is indented: indentation is Python’s way of grouping statements. At the interactive
prompt, 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; all decent 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.
• The print() function writes the value of the argument(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 arguments, 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:
16 Chapter 3. An Informal Introduction to Python