<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<!--Converted with LaTeX2HTML 98.2 beta6 (August 14th, 1998)
original version by:  Nikos Drakos, CBLU, University of Leeds
* revised and updated by:  Marcus Hennecke, Ross Moore, Herb Swan
* with significant contributions from:
  Jens Lippmann, Marek Rouchal, Martin Wilck and others -->
<HTML>
<HEAD>
<TITLE>3. An Informal Introduction to Python </TITLE>
<META NAME="description" CONTENT="3. An Informal Introduction to Python ">
<META NAME="keywords" CONTENT="tut">
<META NAME="resource-type" CONTENT="document">
<META NAME="distribution" CONTENT="global">
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=iso-8859-1">
<LINK REL="STYLESHEET" HREF="tut.css">
<LINK REL="next" HREF="node6.html">
<LINK REL="previous" HREF="node4.html">
<LINK REL="up" HREF="tut.html">
<LINK REL="next" HREF="node6.html">
</HEAD>
<BODY bgcolor="#ffffff">
<div class=navigation>
<table align=center width="100%" cellpadding=0 cellspacing=2>
<tr>
<td><A HREF="node6.html"><img width=32 height=32 align=bottom border=0 alt="next"
 src="../icons/next.gif"></A></td>
<td><A HREF="tut.html"><img width=32 height=32 align=bottom border=0 alt="up"
 src="../icons/up.gif"></A></td>
<td><A HREF="node4.html"><img width=32 height=32 align=bottom border=0 alt="previous"
 src="../icons/previous.gif"></A></td>
<td align=center bgcolor="#99CCFF" width="100%">
 <b class=title>Python Tutorial</b></td>
<td><A HREF="node2.html"><img width=32 height=32 align=bottom border=0 alt="contents"
 src="../icons/contents.gif"></A></td>
<td><img width=32 height=32 align=bottom border=0 alt=""
 src="../icons/blank.gif"></td>
<td><img width=32 height=32 align=bottom border=0 alt=""
 src="../icons/blank.gif"></td>
</tr></table><b class=navlabel>Next:</b> <span class=sectref><A HREF="node6.html">4. More Control Flow</A></span>
<b class=navlabel>Up:</b> <span class=sectref><A HREF="tut.html">Python Tutorial</A></span>
<b class=navlabel>Previous:</b> <span class=sectref><A HREF="node4.html">2. Using the Python</A></span>
<br><hr></div>
<!--End of Navigation Panel-->
<!--Table of Child-Links-->
<A NAME="CHILD_LINKS"><STRONG>Subsections</STRONG></A>

<UL>
<LI><A NAME="tex2html207"
 HREF="node5.html#SECTION005100000000000000000">3.1 Using Python as a Calculator </A>
<UL>
<LI><A NAME="tex2html208"
 HREF="node5.html#SECTION005110000000000000000">3.1.1 Numbers </A>
<LI><A NAME="tex2html209"
 HREF="node5.html#SECTION005120000000000000000">3.1.2 Strings </A>
<LI><A NAME="tex2html210"
 HREF="node5.html#SECTION005130000000000000000">3.1.3 Lists </A>
</UL>
<LI><A NAME="tex2html211"
 HREF="node5.html#SECTION005200000000000000000">3.2 First Steps Towards Programming </A>
</UL>
<!--End of Table of Child-Links-->
<HR>

<H1><A NAME="SECTION005000000000000000000"></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;&gt;&gt; </tt>" and "<tt class=samp>... </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>
<dl><dd><pre class=verbatim>
# this is the first comment
SPAM = 1                 # and this is the second comment
                         # ... and now a third!
STRING = "# This is not a comment."
</pre></dl>

<P>

<H1><A NAME="SECTION005100000000000000000"></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;&gt;&gt; </tt>".  (It shouldn't take long.)

<P>

<H2><A NAME="SECTION005110000000000000000"></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 <tt>+</tt>, <tt>-</tt>, <tt>*</tt> and <tt>/</tt>work just like in most other languages (e.g., Pascal or C); parentheses
can be used for grouping.  For example:

<P>
<dl><dd><pre class=verbatim>
&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></dl>

<P>
Like in C, the equal sign ("<tt class=character>=</tt>") is used to assign a value to a
variable.  The value of an assignment is not written:

<P>
<dl><dd><pre class=verbatim>
&gt;&gt;&gt; width = 20
&gt;&gt;&gt; height = 5*9
&gt;&gt;&gt; width * height
900
</pre></dl>
A value can be assigned to several variables simultaneously:

<P>
<dl><dd><pre class=verbatim>
&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></dl>
There is full support for floating point; operators with mixed type
operands convert the integer operand to floating point:

<P>
<dl><dd><pre class=verbatim>
&gt;&gt;&gt; 4 * 2.5 / 3.3
3.0303030303
&gt;&gt;&gt; 7.0 / 2
3.5
</pre></dl>
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>
<dl><dd><pre class=verbatim>
&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></dl>
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 <tt><var>z</var>.real</tt> and <tt><var>z</var>.imag</tt>.  

<P>
<dl><dd><pre class=verbatim>
&gt;&gt;&gt; a=1.5+0.5j
&gt;&gt;&gt; a.real
1.5
&gt;&gt;&gt; a.imag
0.5
</pre></dl>
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 <tt>abs(<var>z</var>)</tt> to get its
magnitude (as a float) or <tt>z.real</tt> to get its real part.

<P>
<dl><dd><pre class=verbatim>
&gt;&gt;&gt; a=1.5+0.5j
&gt;&gt;&gt; float(a)
Traceback (innermost last):
  File "&lt;stdin&gt;", line 1, in ?
TypeError: can't convert complex to float; use e.g. abs(z)
&gt;&gt;&gt; a.real
1.5
&gt;&gt;&gt; abs(a)
1.58113883008
</pre></dl>
In interactive mode, the last printed expression is assigned to the
variable <tt>_</tt>.  This means that when you are using Python as a
desk calculator, it is somewhat easier to continue calculations, for
example:

<P>
<dl><dd><pre class=verbatim>
&gt;&gt;&gt; tax = 17.5 / 100
&gt;&gt;&gt; price = 3.50
&gt;&gt;&gt; price * tax
0.6125
&gt;&gt;&gt; price + _
4.1125
&gt;&gt;&gt; round(_, 2)
4.11
</pre></dl>

<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>
<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>
<dl><dd><pre class=verbatim>
&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></dl>

<P>
String literals can span multiple lines in several ways.  Newlines can
be escaped with backslashes, e.g.:

<P>
<dl><dd><pre class=verbatim>
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.\n"
print hello
</pre></dl>

<P>
which would print the following:

<P>
<dl><dd><pre class=verbatim>
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></dl>

<P>
Or, strings can be surrounded in a pair of matching triple-quotes:
<tt>"""</tt> or <tt>'''</tt>.  End of lines do not need to be escaped
when using triple-quotes, but they will be included in the string.

<P>
<dl><dd><pre class=verbatim>
print """
Usage: thingy [OPTIONS] 
     -h                        Display this usage message
     -H hostname               Hostname to connect to
"""
</pre></dl>

<P>
produces the following output:

<P>
<dl><dd><pre class=verbatim>
Usage: thingy [OPTIONS] 
     -h                        Display this usage message
     -H hostname               Hostname to connect to
</pre></dl>

<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 <tt>+</tt>operator, and repeated with <tt>*</tt>:

<P>
<dl><dd><pre class=verbatim>
&gt;&gt;&gt; word = 'Help' + 'A'
&gt;&gt;&gt; word
'HelpA'
&gt;&gt;&gt; '&lt;' + word*5 + '&gt;'
'&lt;HelpAHelpAHelpAHelpAHelpA&gt;'
</pre></dl>

<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>
<dl><dd><pre class=verbatim>
&gt;&gt;&gt; 'str' 'ing'                   #  &lt;-  This is ok
'string'
&gt;&gt;&gt; string.strip('str') + 'ing'   #  &lt;-  This is ok
'string'
&gt;&gt;&gt; string.strip('str') 'ing'     #  &lt;-  This is invalid
  File "&lt;stdin&gt;", line 1
    string.strip('str') 'ing'
                            ^
SyntaxError: invalid syntax
</pre></dl>

<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 <i>slice notation</i>: two indices
separated by a colon.

<P>
<dl><dd><pre class=verbatim>
&gt;&gt;&gt; word[4]
'A'
&gt;&gt;&gt; word[0:2]
'He'
&gt;&gt;&gt; word[2:4]
'lp'
</pre></dl>

<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>
<dl><dd><pre class=verbatim>
&gt;&gt;&gt; word[:2]    # The first two characters
'He'
&gt;&gt;&gt; word[2:]    # All but the first two characters
'lpA'
</pre></dl>

<P>
Here's a useful invariant of slice operations: <tt>s[:i] + s[i:]</tt>equals <tt>s</tt>.

<P>
<dl><dd><pre class=verbatim>
&gt;&gt;&gt; word[:2] + word[2:]
'HelpA'
&gt;&gt;&gt; word[:3] + word[3:]
'HelpA'
</pre></dl>

<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>
<dl><dd><pre class=verbatim>
&gt;&gt;&gt; word[1:100]
'elpA'
&gt;&gt;&gt; word[10:]
''
&gt;&gt;&gt; word[2:1]
''
</pre></dl>

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

<P>
<dl><dd><pre class=verbatim>
&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]    # All but the last two characters
'Hel'
</pre></dl>

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

<P>
<dl><dd><pre class=verbatim>
&gt;&gt;&gt; word[-0]     # (since -0 equals 0)
'H'
</pre></dl>

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

<P>
<dl><dd><pre class=verbatim>
&gt;&gt;&gt; word[-100:]
'HelpA'
&gt;&gt;&gt; word[-10]    # error
Traceback (innermost last):
  File "&lt;stdin&gt;", line 1
IndexError: string index out of range
</pre></dl>

<P>
The best way to remember how slices work is to think of the indices as
pointing <i>between</i> 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>
<dl><dd><pre class=verbatim>
 +---+---+---+---+---+ 
 | H | e | l | p | A |
 +---+---+---+---+---+ 
 0   1   2   3   4   5 
-5  -4  -3  -2  -1
</pre></dl>

<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 nonnegative indices, the length of a slice is the difference of
the indices, if both are within bounds, e.g., the length of
<tt>word[1:3]</tt> is 2.

<P>
The built-in function <tt class=function>len()</tt> returns the length of a string:

<P>
<dl><dd><pre class=verbatim>
&gt;&gt;&gt; s = 'supercalifragilisticexpialidocious'
&gt;&gt;&gt; len(s)
34
</pre></dl>

<P>

<H2><A NAME="SECTION005130000000000000000"></A>
<BR>
3.1.3 Lists 
</H2>

<P>
Python knows a number of <i>compound</i> data types, used to group
together other values.  The most versatile is the <i>list</i>, 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>
<dl><dd><pre class=verbatim>
&gt;&gt;&gt; a = ['spam', 'eggs', 100, 1234]
&gt;&gt;&gt; a
['spam', 'eggs', 100, 1234]
</pre></dl>

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

<P>
<dl><dd><pre class=verbatim>
&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] + ['Boe!']
['spam', 'eggs', 100, 'spam', 'eggs', 100, 'spam', 'eggs', 100, 'Boe!']
</pre></dl>

<P>
Unlike strings, which are <i>immutable</i>, it is possible to change
individual elements of a list:

<P>
<dl><dd><pre class=verbatim>
&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></dl>

<P>
Assignment to slices is also possible, and this can even change the size
of the list:

<P>
<dl><dd><pre class=verbatim>
&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></dl>

<P>
The built-in function <tt class=function>len()</tt> also applies to lists:

<P>
<dl><dd><pre class=verbatim>
&gt;&gt;&gt; len(a)
8
</pre></dl>

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

<P>
<dl><dd><pre class=verbatim>
&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></dl>

<P>
Note that in the last example, <tt>p[1]</tt> and <tt>q</tt> really refer to
the same object!  We'll come back to <i>object semantics</i> later.

<P>

<H1><A NAME="SECTION005200000000000000000"></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
subsequence of the <i>Fibonacci</i> series as follows:

<P>
<dl><dd><pre class=verbatim>
&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></dl>

<P>
This example introduces several new features.

<P>

<UL><LI>The first line contains a <i>multiple assignment</i>: the variables
<tt>a</tt> and <tt>b</tt> 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.

<P>

<LI>The <tt class=keyword>while</tt> loop executes as long as the condition (here:
<tt>b &lt; 10</tt>) 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: <tt>&lt;</tt>, <tt>&gt;</tt>, <tt>==</tt>, <tt>&lt;=</tt>,
<tt>&gt;=</tt> and <tt>!=</tt>.

<P>

<LI>The <i>body</i> of the loop is <i>indented</i>: 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).

<P>

<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>
<dl><dd><pre class=verbatim>
&gt;&gt;&gt; i = 256*256
&gt;&gt;&gt; print 'The value of i is', i
The value of i is 65536
</pre></dl>

<P>
A trailing comma avoids the newline after the output:

<P>
<dl><dd><pre class=verbatim>
&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></dl>

<P>
Note that the interpreter inserts a newline before it prints the next
prompt if the last line was not completed.

<P>

</UL>

<P>
<p>
<div class=navigation><hr><table align=center width="100%" cellpadding=0 cellspacing=2>
<tr>
<td><A HREF="node6.html"><img width=32 height=32 align=bottom border=0 alt="next"
 src="../icons/next.gif"></A></td>
<td><A HREF="tut.html"><img width=32 height=32 align=bottom border=0 alt="up"
 src="../icons/up.gif"></A></td>
<td><A HREF="node4.html"><img width=32 height=32 align=bottom border=0 alt="previous"
 src="../icons/previous.gif"></A></td>
<td align=center bgcolor="#99CCFF" width="100%">
 <b class=title>Python Tutorial</b></td>
<td><A HREF="node2.html"><img width=32 height=32 align=bottom border=0 alt="contents"
 src="../icons/contents.gif"></A></td>
<td><img width=32 height=32 align=bottom border=0 alt=""
 src="../icons/blank.gif"></td>
<td><img width=32 height=32 align=bottom border=0 alt=""
 src="../icons/blank.gif"></td>
</tr></table><b class=navlabel>Next:</b> <span class=sectref><A HREF="node6.html">4. More Control Flow</A></span>
<b class=navlabel>Up:</b> <span class=sectref><A HREF="tut.html">Python Tutorial</A></span>
<b class=navlabel>Previous:</b> <span class=sectref><A HREF="node4.html">2. Using the Python</A></span>
</div>
<!--End of Navigation Panel-->
<ADDRESS>
<hr>Send comments on this document to <a href="mailto:python-docs@python.org">python-docs@python.org</a>.
</ADDRESS>
</BODY>
</HTML>
