Initial commit of OpenSPARC T2 architecture model.
[OpenSPARC-T2-SAM] / sam-t2 / devtools / v9 / html / python / tut / node5.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<link rel="STYLESHEET" href="tut.css" type='text/css' />
<link rel="SHORTCUT ICON" href="../icons/pyfav.png" type="image/png" />
<link rel='start' href='../index.html' title='Python Documentation Index' />
<link rel="first" href="tut.html" title='Python Tutorial' />
<link rel='contents' href='node2.html' title="Contents" />
<link rel='index' href='node19.html' title='Index' />
<link rel='last' href='about.html' title='About this document...' />
<link rel='help' href='about.html' title='About this document...' />
<link rel="next" href="node6.html" />
<link rel="prev" href="node4.html" />
<link rel="parent" href="tut.html" />
<link rel="next" href="node6.html" />
<meta name='aesop' content='information' />
<title>3. An Informal Introduction to Python </title>
</head>
<body>
<DIV CLASS="navigation">
<div id='top-navigation-panel' xml:id='top-navigation-panel'>
<table align="center" width="100%" cellpadding="0" cellspacing="2">
<tr>
<td class='online-navigation'><a rel="prev" title="2. Using the Python"
href="node4.html"><img src='../icons/previous.png'
border='0' height='32' alt='Previous Page' width='32' /></A></td>
<td class='online-navigation'><a rel="parent" title="Python Tutorial"
href="tut.html"><img src='../icons/up.png'
border='0' height='32' alt='Up One Level' width='32' /></A></td>
<td class='online-navigation'><a rel="next" title="4. More Control Flow"
href="node6.html"><img src='../icons/next.png'
border='0' height='32' alt='Next Page' width='32' /></A></td>
<td align="center" width="100%">Python Tutorial</td>
<td class='online-navigation'><a rel="contents" title="Table of Contents"
href="node2.html"><img src='../icons/contents.png'
border='0' height='32' alt='Contents' width='32' /></A></td>
<td class='online-navigation'><img src='../icons/blank.png'
border='0' height='32' alt='' width='32' /></td>
<td class='online-navigation'><a rel="index" title="Index"
href="node19.html"><img src='../icons/index.png'
border='0' height='32' alt='Index' width='32' /></A></td>
</tr></table>
<div class='online-navigation'>
<b class="navlabel">Previous:</b>
<a class="sectref" rel="prev" href="node4.html">2. Using the Python</A>
<b class="navlabel">Up:</b>
<a class="sectref" rel="parent" href="tut.html">Python Tutorial</A>
<b class="navlabel">Next:</b>
<a class="sectref" rel="next" href="node6.html">4. More Control Flow</A>
</div>
<hr /></div>
</DIV>
<!--End of Navigation Panel-->
<div class='online-navigation'>
<!--Table of Child-Links-->
<A NAME="CHILD_LINKS"><STRONG>Subsections</STRONG></a>
<UL CLASS="ChildLinks">
<LI><A href="node5.html#SECTION005100000000000000000">3.1 Using Python as a Calculator</a>
<UL>
<LI><A href="node5.html#SECTION005110000000000000000">3.1.1 Numbers</a>
<LI><A href="node5.html#SECTION005120000000000000000">3.1.2 Strings</a>
<LI><A href="node5.html#SECTION005130000000000000000">3.1.3 Unicode Strings</a>
<LI><A href="node5.html#SECTION005140000000000000000">3.1.4 Lists</a>
</ul>
<LI><A href="node5.html#SECTION005200000000000000000">3.2 First Steps Towards Programming</a>
</ul>
<!--End of Table of Child-Links-->
</div>
<HR>
<H1><A NAME="SECTION005000000000000000000"></A><A NAME="informal"></A>
<BR>
3. An Informal Introduction to Python
</H1>
<P>
In the following examples, input and output are distinguished by the
presence or absence of prompts ("<tt class="samp">&gt;<code>&gt;</code>&gt;&nbsp;</tt>" and "<tt class="samp">...&nbsp;</tt>"): 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.
<P>
Many of the examples in this manual, even those entered at the
interactive prompt, include comments. Comments in Python start with
the hash character, "<tt class="character">#</tt>", 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.
<P>
Some examples:
<P>
<div class="verbatim"><pre>
# this is the first comment
SPAM = 1 # and this is the second comment
# ... and now a third!
STRING = "# This is not a comment."
</pre></div>
<P>
<H1><A NAME="SECTION005100000000000000000"></A><A NAME="calculator"></A>
<BR>
3.1 Using Python as a Calculator
</H1>
<P>
Let's try some simple Python commands. Start the interpreter and wait
for the primary prompt, "<tt class="samp">&gt;<code>&gt;</code>&gt;&nbsp;</tt>". (It shouldn't take long.)
<P>
<H2><A NAME="SECTION005110000000000000000"></A><A NAME="numbers"></A>
<BR>
3.1.1 Numbers
</H2>
<P>
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 <code>+</code>, <code>-</code>, <code>*</code> and
<code>/</code> work just like in most other languages (for example, Pascal
or C); parentheses can be used for grouping. For example:
<P>
<div class="verbatim"><pre>
&gt;&gt;&gt; 2+2
4
&gt;&gt;&gt; # This is a comment
... 2+2
4
&gt;&gt;&gt; 2+2 # and a comment on the same line as code
4
&gt;&gt;&gt; (50-5*6)/4
5
&gt;&gt;&gt; # Integer division returns the floor:
... 7/3
2
&gt;&gt;&gt; 7/-3
-3
</pre></div>
<P>
The equal sign ("<tt class="character">=</tt>") is used to assign a value to a variable.
Afterwards, no result is displayed before the next interactive prompt:
<P>
<div class="verbatim"><pre>
&gt;&gt;&gt; width = 20
&gt;&gt;&gt; height = 5*9
&gt;&gt;&gt; width * height
900
</pre></div>
<P>
A value can be assigned to several variables simultaneously:
<P>
<div class="verbatim"><pre>
&gt;&gt;&gt; x = y = z = 0 # Zero x, y and z
&gt;&gt;&gt; x
0
&gt;&gt;&gt; y
0
&gt;&gt;&gt; z
0
</pre></div>
<P>
There is full support for floating point; operators with mixed type
operands convert the integer operand to floating point:
<P>
<div class="verbatim"><pre>
&gt;&gt;&gt; 3 * 3.75 / 1.5
7.5
&gt;&gt;&gt; 7.0 / 2
3.5
</pre></div>
<P>
Complex numbers are also supported; imaginary numbers are written with
a suffix of "<tt class="samp">j</tt>" or "<tt class="samp">J</tt>". Complex numbers with a nonzero
real component are written as "<tt class="samp">(<var>real</var>+<var>imag</var>j)</tt>", or can
be created with the "<tt class="samp">complex(<var>real</var>, <var>imag</var>)</tt>" function.
<P>
<div class="verbatim"><pre>
&gt;&gt;&gt; 1j * 1J
(-1+0j)
&gt;&gt;&gt; 1j * complex(0,1)
(-1+0j)
&gt;&gt;&gt; 3+1j*3
(3+3j)
&gt;&gt;&gt; (3+1j)*3
(9+3j)
&gt;&gt;&gt; (1+2j)/(1+1j)
(1.5+0.5j)
</pre></div>
<P>
Complex numbers are always represented as two floating point numbers,
the real and imaginary part. To extract these parts from a complex
number <var>z</var>, use <code><var>z</var>.real</code> and <code><var>z</var>.imag</code>.
<P>
<div class="verbatim"><pre>
&gt;&gt;&gt; a=1.5+0.5j
&gt;&gt;&gt; a.real
1.5
&gt;&gt;&gt; a.imag
0.5
</pre></div>
<P>
The conversion functions to floating point and integer
(<tt class="function">float()</tt>, <tt class="function">int()</tt> and <tt class="function">long()</tt>) don't
work for complex numbers -- there is no one correct way to convert a
complex number to a real number. Use <code>abs(<var>z</var>)</code> to get its
magnitude (as a float) or <code>z.real</code> to get its real part.
<P>
<div class="verbatim"><pre>
&gt;&gt;&gt; a=3.0+4.0j
&gt;&gt;&gt; float(a)
Traceback (most recent call last):
File "&lt;stdin&gt;", line 1, in ?
TypeError: can't convert complex to float; use abs(z)
&gt;&gt;&gt; a.real
3.0
&gt;&gt;&gt; a.imag
4.0
&gt;&gt;&gt; abs(a) # sqrt(a.real**2 + a.imag**2)
5.0
&gt;&gt;&gt;
</pre></div>
<P>
In interactive mode, the last printed expression is assigned to the
variable <code>_</code>. This means that when you are using Python as a
desk calculator, it is somewhat easier to continue calculations, for
example:
<P>
<div class="verbatim"><pre>
&gt;&gt;&gt; tax = 12.5 / 100
&gt;&gt;&gt; price = 100.50
&gt;&gt;&gt; price * tax
12.5625
&gt;&gt;&gt; price + _
113.0625
&gt;&gt;&gt; round(_, 2)
113.06
&gt;&gt;&gt;
</pre></div>
<P>
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.
<P>
<H2><A NAME="SECTION005120000000000000000"></A><A NAME="strings"></A>
<BR>
3.1.2 Strings
</H2>
<P>
Besides numbers, Python can also manipulate strings, which can be
expressed in several ways. They can be enclosed in single quotes or
double quotes:
<P>
<div class="verbatim"><pre>
&gt;&gt;&gt; 'spam eggs'
'spam eggs'
&gt;&gt;&gt; 'doesn\'t'
"doesn't"
&gt;&gt;&gt; "doesn't"
"doesn't"
&gt;&gt;&gt; '"Yes," he said.'
'"Yes," he said.'
&gt;&gt;&gt; "\"Yes,\" he said."
'"Yes," he said.'
&gt;&gt;&gt; '"Isn\'t," she said.'
'"Isn\'t," she said.'
</pre></div>
<P>
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:
<P>
<div class="verbatim"><pre>
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
</pre></div>
<P>
Note that newlines still need to be embedded in the string using
<code>&#92;n</code>; the newline following the trailing backslash is
discarded. This example would print the following:
<P>
<div class="verbatim"><pre>
This is a rather long string containing
several lines of text just as you would do in C.
Note that whitespace at the beginning of the line is significant.
</pre></div>
<P>
If we make the string literal a ``raw'' string, however, the
<code>&#92;n</code> 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:
<P>
<div class="verbatim"><pre>
hello = r"This is a rather long string containing\n\
several lines of text much as you would do in C."
print hello
</pre></div>
<P>
would print:
<P>
<div class="verbatim"><pre>
This is a rather long string containing\n\
several lines of text much as you would do in C.
</pre></div>
<P>
Or, strings can be surrounded in a pair of matching triple-quotes:
<code>"""</code> or <code>'<code>'</code>'</code>. End of lines do not need to be escaped
when using triple-quotes, but they will be included in the string.
<P>
<div class="verbatim"><pre>
print """
Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
"""
</pre></div>
<P>
produces the following output:
<P>
<div class="verbatim"><pre>
Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
</pre></div>
<P>
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 <tt class="keyword">print</tt> statement, described later, can be used
to write strings without quotes or escapes.)
<P>
Strings can be concatenated (glued together) with the
<code>+</code> operator, and repeated with <code>*</code>:
<P>
<div class="verbatim"><pre>
&gt;&gt;&gt; word = 'Help' + 'A'
&gt;&gt;&gt; word
'HelpA'
&gt;&gt;&gt; '&lt;' + word*5 + '&gt;'
'&lt;HelpAHelpAHelpAHelpAHelpA&gt;'
</pre></div>
<P>
Two string literals next to each other are automatically concatenated;
the first line above could also have been written "<tt class="samp">word = 'Help'
'A'</tt>"; this only works with two literals, not with arbitrary string
expressions:
<P>
<div class="verbatim"><pre>
&gt;&gt;&gt; 'str' 'ing' # &lt;- This is ok
'string'
&gt;&gt;&gt; 'str'.strip() + 'ing' # &lt;- This is ok
'string'
&gt;&gt;&gt; 'str'.strip() 'ing' # &lt;- This is invalid
File "&lt;stdin&gt;", line 1, in ?
'str'.strip() 'ing'
^
SyntaxError: invalid syntax
</pre></div>
<P>
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. Like in Icon,
substrings can be specified with the <em>slice notation</em>: two indices
separated by a colon.
<P>
<div class="verbatim"><pre>
&gt;&gt;&gt; word[4]
'A'
&gt;&gt;&gt; word[0:2]
'He'
&gt;&gt;&gt; word[2:4]
'lp'
</pre></div>
<P>
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.
<P>
<div class="verbatim"><pre>
&gt;&gt;&gt; word[:2] # The first two characters
'He'
&gt;&gt;&gt; word[2:] # Everything except the first two characters
'lpA'
</pre></div>
<P>
Unlike a C string, Python strings cannot be changed. Assigning to an
indexed position in the string results in an error:
<P>
<div class="verbatim"><pre>
&gt;&gt;&gt; word[0] = 'x'
Traceback (most recent call last):
File "&lt;stdin&gt;", line 1, in ?
TypeError: object doesn't support item assignment
&gt;&gt;&gt; word[:1] = 'Splat'
Traceback (most recent call last):
File "&lt;stdin&gt;", line 1, in ?
TypeError: object doesn't support slice assignment
</pre></div>
<P>
However, creating a new string with the combined content is easy and
efficient:
<P>
<div class="verbatim"><pre>
&gt;&gt;&gt; 'x' + word[1:]
'xelpA'
&gt;&gt;&gt; 'Splat' + word[4]
'SplatA'
</pre></div>
<P>
Here's a useful invariant of slice operations:
<code>s[:i] + s[i:]</code> equals <code>s</code>.
<P>
<div class="verbatim"><pre>
&gt;&gt;&gt; word[:2] + word[2:]
'HelpA'
&gt;&gt;&gt; word[:3] + word[3:]
'HelpA'
</pre></div>
<P>
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.
<P>
<div class="verbatim"><pre>
&gt;&gt;&gt; word[1:100]
'elpA'
&gt;&gt;&gt; word[10:]
''
&gt;&gt;&gt; word[2:1]
''
</pre></div>
<P>
Indices may be negative numbers, to start counting from the right.
For example:
<P>
<div class="verbatim"><pre>
&gt;&gt;&gt; word[-1] # The last character
'A'
&gt;&gt;&gt; word[-2] # The last-but-one character
'p'
&gt;&gt;&gt; word[-2:] # The last two characters
'pA'
&gt;&gt;&gt; word[:-2] # Everything except the last two characters
'Hel'
</pre></div>
<P>
But note that -0 is really the same as 0, so it does not count from
the right!
<P>
<div class="verbatim"><pre>
&gt;&gt;&gt; word[-0] # (since -0 equals 0)
'H'
</pre></div>
<P>
Out-of-range negative slice indices are truncated, but don't try this
for single-element (non-slice) indices:
<P>
<div class="verbatim"><pre>
&gt;&gt;&gt; word[-100:]
'HelpA'
&gt;&gt;&gt; word[-10] # error
Traceback (most recent call last):
File "&lt;stdin&gt;", line 1, in ?
IndexError: string index out of range
</pre></div>
<P>
The best way to remember how slices work is to think of the indices as
pointing <em>between</em> characters, with the left edge of the first
character numbered 0. Then the right edge of the last character of a
string of <var>n</var> characters has index <var>n</var>, for example:
<P>
<div class="verbatim"><pre>
+---+---+---+---+---+
| H | e | l | p | A |
+---+---+---+---+---+
0 1 2 3 4 5
-5 -4 -3 -2 -1
</pre></div>
<P>
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 <var>i</var> to <var>j</var> consists of all characters between
the edges labeled <var>i</var> and <var>j</var>, respectively.
<P>
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
<code>word[1:3]</code> is 2.
<P>
The built-in function <tt class="function">len()</tt> returns the length of a string:
<P>
<div class="verbatim"><pre>
&gt;&gt;&gt; s = 'supercalifragilisticexpialidocious'
&gt;&gt;&gt; len(s)
34
</pre></div>
<P>
<div class="seealso">
<p class="heading">See Also:</p>
<dl compact="compact" class="seetitle">
<dt><em class="citetitle"><a href="../lib/typesseq.html"
>Sequence Types</a></em></dt>
<dd>Strings, and the Unicode strings described in the next
section, are examples of <em>sequence types</em>, and
support the common operations supported by such types.</dd>
</dl>
<dl compact="compact" class="seetitle">
<dt><em class="citetitle"><a href="../lib/string-methods.html"
>String Methods</a></em></dt>
<dd>Both strings and Unicode strings support a large number of
methods for basic transformations and searching.</dd>
</dl>
<dl compact="compact" class="seetitle">
<dt><em class="citetitle"><a href="../lib/typesseq-strings.html"
>String Formatting Operations</a></em></dt>
<dd>The formatting operations invoked when strings and Unicode
strings are the left operand of the <code>%</code> operator are
described in more detail here.</dd>
</dl>
</div>
<P>
<H2><A NAME="SECTION005130000000000000000"></A><A NAME="unicodeStrings"></A>
<BR>
3.1.3 Unicode Strings
</H2>
<P>
Starting with Python 2.0 a new data type for storing text data is
available to the programmer: the Unicode object. It can be used to
store and manipulate Unicode data (see <a class="url" href="http://www.unicode.org/">http://www.unicode.org/</a>)
and integrates well with the existing string objects, providing
auto-conversions where necessary.
<P>
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 and 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 "<tt class="samp">i18n</tt>" --
"<tt class="character">i</tt>" + 18 characters + "<tt class="character">n</tt>") of software. Unicode
solves these problems by defining one code page for all scripts.
<P>
Creating Unicode strings in Python is just as simple as creating
normal strings:
<P>
<div class="verbatim"><pre>
&gt;&gt;&gt; u'Hello World !'
u'Hello World !'
</pre></div>
<P>
The small "<tt class="character">u</tt>" in front of the quote indicates that an
Unicode string is supposed to be created. If you want to include
special characters in the string, you can do so by using the Python
<em>Unicode-Escape</em> encoding. The following example shows how:
<P>
<div class="verbatim"><pre>
&gt;&gt;&gt; u'Hello\u0020World !'
u'Hello World !'
</pre></div>
<P>
The escape sequence <code>&#92;u0020</code> indicates to insert the Unicode
character with the ordinal value 0x0020 (the space character) at the
given position.
<P>
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.
<P>
For experts, there is also a raw mode just like the one for normal
strings. You have to prefix the opening quote with 'ur' to have
Python use the <em>Raw-Unicode-Escape</em> encoding. It will only apply
the above <code>&#92;uXXXX</code> conversion if there is an uneven number of
backslashes in front of the small 'u'.
<P>
<div class="verbatim"><pre>
&gt;&gt;&gt; ur'Hello\u0020World !'
u'Hello World !'
&gt;&gt;&gt; ur'Hello\\u0020World !'
u'Hello\\\\u0020World !'
</pre></div>
<P>
The raw mode is most useful when you have to enter lots of
backslashes, as can be necessary in regular expressions.
<P>
Apart from these standard encodings, Python provides a whole set of
other ways of creating Unicode strings on the basis of a known
encoding.
<P>
The built-in function <tt class="function">unicode()</tt><a id='l2h-3' xml:id='l2h-3'></a> provides
access to all registered Unicode codecs (COders and DECoders). Some of
the more well known encodings which these codecs can convert are
<em>Latin-1</em>, <em>ASCII</em>, <em>UTF-8</em>, and <em>UTF-16</em>.
The latter two are variable-length encodings that store each Unicode
character in one or more bytes. The default encoding is
normally set to ASCII, which passes through characters in the range
0 to 127 and rejects any other characters with an error.
When a Unicode string is printed, written to a file, or converted
with <tt class="function">str()</tt>, conversion takes place using this default encoding.
<P>
<div class="verbatim"><pre>
&gt;&gt;&gt; u"abc"
u'abc'
&gt;&gt;&gt; str(u"abc")
'abc'
&gt;&gt;&gt; u"äöü"
u'\xe4\xf6\xfc'
&gt;&gt;&gt; str(u"äöü")
Traceback (most recent call last):
File "&lt;stdin&gt;", line 1, in ?
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordinal not in range(128)
</pre></div>
<P>
To convert a Unicode string into an 8-bit string using a specific
encoding, Unicode objects provide an <tt class="function">encode()</tt> method
that takes one argument, the name of the encoding. Lowercase names
for encodings are preferred.
<P>
<div class="verbatim"><pre>
&gt;&gt;&gt; u"äöü".encode('utf-8')
'\xc3\xa4\xc3\xb6\xc3\xbc'
</pre></div>
<P>
If you have data in a specific encoding and want to produce a
corresponding Unicode string from it, you can use the
<tt class="function">unicode()</tt> function with the encoding name as the second
argument.
<P>
<div class="verbatim"><pre>
&gt;&gt;&gt; unicode('\xc3\xa4\xc3\xb6\xc3\xbc', 'utf-8')
u'\xe4\xf6\xfc'
</pre></div>
<P>
<H2><A NAME="SECTION005140000000000000000"></A><A NAME="lists"></A>
<BR>
3.1.4 Lists
</H2>
<P>
Python knows a number of <em>compound</em> data types, used to group
together other values. The most versatile is the <em>list</em>, which
can be written as a list of comma-separated values (items) between
square brackets. List items need not all have the same type.
<P>
<div class="verbatim"><pre>
&gt;&gt;&gt; a = ['spam', 'eggs', 100, 1234]
&gt;&gt;&gt; a
['spam', 'eggs', 100, 1234]
</pre></div>
<P>
Like string indices, list indices start at 0, and lists can be sliced,
concatenated and so on:
<P>
<div class="verbatim"><pre>
&gt;&gt;&gt; a[0]
'spam'
&gt;&gt;&gt; a[3]
1234
&gt;&gt;&gt; a[-2]
100
&gt;&gt;&gt; a[1:-1]
['eggs', 100]
&gt;&gt;&gt; a[:2] + ['bacon', 2*2]
['spam', 'eggs', 'bacon', 4]
&gt;&gt;&gt; 3*a[:3] + ['Boo!']
['spam', 'eggs', 100, 'spam', 'eggs', 100, 'spam', 'eggs', 100, 'Boo!']
</pre></div>
<P>
Unlike strings, which are <em>immutable</em>, it is possible to change
individual elements of a list:
<P>
<div class="verbatim"><pre>
&gt;&gt;&gt; a
['spam', 'eggs', 100, 1234]
&gt;&gt;&gt; a[2] = a[2] + 23
&gt;&gt;&gt; a
['spam', 'eggs', 123, 1234]
</pre></div>
<P>
Assignment to slices is also possible, and this can even change the size
of the list:
<P>
<div class="verbatim"><pre>
&gt;&gt;&gt; # Replace some items:
... a[0:2] = [1, 12]
&gt;&gt;&gt; a
[1, 12, 123, 1234]
&gt;&gt;&gt; # Remove some:
... a[0:2] = []
&gt;&gt;&gt; a
[123, 1234]
&gt;&gt;&gt; # Insert some:
... a[1:1] = ['bletch', 'xyzzy']
&gt;&gt;&gt; a
[123, 'bletch', 'xyzzy', 1234]
&gt;&gt;&gt; a[:0] = a # Insert (a copy of) itself at the beginning
&gt;&gt;&gt; a
[123, 'bletch', 'xyzzy', 1234, 123, 'bletch', 'xyzzy', 1234]
</pre></div>
<P>
The built-in function <tt class="function">len()</tt> also applies to lists:
<P>
<div class="verbatim"><pre>
&gt;&gt;&gt; len(a)
8
</pre></div>
<P>
It is possible to nest lists (create lists containing other lists),
for example:
<P>
<div class="verbatim"><pre>
&gt;&gt;&gt; q = [2, 3]
&gt;&gt;&gt; p = [1, q, 4]
&gt;&gt;&gt; len(p)
3
&gt;&gt;&gt; p[1]
[2, 3]
&gt;&gt;&gt; p[1][0]
2
&gt;&gt;&gt; p[1].append('xtra') # See section 5.1
&gt;&gt;&gt; p
[1, [2, 3, 'xtra'], 4]
&gt;&gt;&gt; q
[2, 3, 'xtra']
</pre></div>
<P>
Note that in the last example, <code>p[1]</code> and <code>q</code> really refer to
the same object! We'll come back to <em>object semantics</em> later.
<P>
<H1><A NAME="SECTION005200000000000000000"></A><A NAME="firstSteps"></A>
<BR>
3.2 First Steps Towards Programming
</H1>
<P>
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 <em>Fibonacci</em> series as follows:
<P>
<div class="verbatim"><pre>
&gt;&gt;&gt; # Fibonacci series:
... # the sum of two elements defines the next
... a, b = 0, 1
&gt;&gt;&gt; while b &lt; 10:
... print b
... a, b = b, a+b
...
1
1
2
3
5
8
</pre></div>
<P>
This example introduces several new features.
<P>
<UL>
<LI>The first line contains a <em>multiple assignment</em>: the variables
<code>a</code> and <code>b</code> 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.
<P>
</LI>
<LI>The <tt class="keyword">while</tt> loop executes as long as the condition (here:
<code>b &lt; 10</code>) 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: <code>&lt;</code> (less than), <code>&gt;</code> (greater than),
<code>==</code> (equal to), <code>&lt;=</code> (less than or equal to),
<code>&gt;=</code> (greater than or equal to) and <code>!=</code> (not equal to).
<P>
</LI>
<LI>The <em>body</em> of the loop is <em>indented</em>: 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.
<P>
</LI>
<LI>The <tt class="keyword">print</tt> statement 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 and strings. Strings are printed without quotes,
and a space is inserted between items, so you can format things nicely,
like this:
<P>
<div class="verbatim"><pre>
&gt;&gt;&gt; i = 256*256
&gt;&gt;&gt; print 'The value of i is', i
The value of i is 65536
</pre></div>
<P>
A trailing comma avoids the newline after the output:
<P>
<div class="verbatim"><pre>
&gt;&gt;&gt; a, b = 0, 1
&gt;&gt;&gt; while b &lt; 1000:
... print b,
... a, b = b, a+b
...
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
</pre></div>
<P>
Note that the interpreter inserts a newline before it prints the next
prompt if the last line was not completed.
<P>
</LI>
</UL>
<P>
<DIV CLASS="navigation">
<div class='online-navigation'>
<p></p><hr />
<table align="center" width="100%" cellpadding="0" cellspacing="2">
<tr>
<td class='online-navigation'><a rel="prev" title="2. Using the Python"
href="node4.html"><img src='../icons/previous.png'
border='0' height='32' alt='Previous Page' width='32' /></A></td>
<td class='online-navigation'><a rel="parent" title="Python Tutorial"
href="tut.html"><img src='../icons/up.png'
border='0' height='32' alt='Up One Level' width='32' /></A></td>
<td class='online-navigation'><a rel="next" title="4. More Control Flow"
href="node6.html"><img src='../icons/next.png'
border='0' height='32' alt='Next Page' width='32' /></A></td>
<td align="center" width="100%">Python Tutorial</td>
<td class='online-navigation'><a rel="contents" title="Table of Contents"
href="node2.html"><img src='../icons/contents.png'
border='0' height='32' alt='Contents' width='32' /></A></td>
<td class='online-navigation'><img src='../icons/blank.png'
border='0' height='32' alt='' width='32' /></td>
<td class='online-navigation'><a rel="index" title="Index"
href="node19.html"><img src='../icons/index.png'
border='0' height='32' alt='Index' width='32' /></A></td>
</tr></table>
<div class='online-navigation'>
<b class="navlabel">Previous:</b>
<a class="sectref" rel="prev" href="node4.html">2. Using the Python</A>
<b class="navlabel">Up:</b>
<a class="sectref" rel="parent" href="tut.html">Python Tutorial</A>
<b class="navlabel">Next:</b>
<a class="sectref" rel="next" href="node6.html">4. More Control Flow</A>
</div>
</div>
<hr />
<span class="release-info">Release 2.4.2, documentation updated on 28 September 2005.</span>
</DIV>
<!--End of Navigation Panel-->
<ADDRESS>
See <i><a href="about.html">About this document...</a></i> for information on suggesting changes.
</ADDRESS>
</BODY>
</HTML>