cpython/Doc/tutorial/introduction.rst

538 lines
17 KiB
ReStructuredText
Raw Normal View History

2015-05-25 06:27:39 -03:00
.. _tut-informal:
2007-08-15 11:28:22 -03:00
**********************************
An Informal Introduction to Python
**********************************
In the following examples, input and output are distinguished by the presence or
absence of prompts (:term:`>>>` and :term:`...`): to repeat the example, you must type
2007-08-15 11:28:22 -03:00
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.
Many of the examples in this manual, even those entered at the interactive
prompt, include comments. Comments in Python start with the hash character,
2008-09-13 14:18:21 -03:00
``#``, 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.
2008-09-13 14:18:21 -03:00
Since comments are to clarify code and are not interpreted by Python, they may
be omitted when typing in examples.
2007-08-15 11:28:22 -03:00
Some examples::
# this is the first comment
spam = 1 # and this is the second comment
# ... and now a third!
text = "# This is not a comment because it's inside quotes."
2007-08-15 11:28:22 -03:00
.. _tut-calculator:
Using Python as a Calculator
============================
Let's try some simple Python commands. Start the interpreter and wait for the
primary prompt, ``>>>``. (It shouldn't take long.)
.. _tut-numbers:
Numbers
-------
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 ``+``, ``-``, ``*`` and ``/`` work just like in most other languages
(for example, Pascal or C); parentheses (``()``) can be used for grouping.
For example::
2007-08-15 11:28:22 -03:00
>>> 2 + 2
2007-08-15 11:28:22 -03:00
4
>>> 50 - 5*6
20
>>> (50 - 5*6) / 4
5.0
>>> 8 / 5 # division always returns a floating point number
1.6
The integer numbers (e.g. ``2``, ``4``, ``20``) have type :class:`int`,
the ones with a fractional part (e.g. ``5.0``, ``1.6``) have type
:class:`float`. We will see more about numeric types later in the tutorial.
Division (``/``) always returns a float. To do :term:`floor division` and
get an integer result (discarding any fractional result) you can use the ``//``
operator; to calculate the remainder you can use ``%``::
2009-01-03 17:18:54 -04:00
>>> 17 / 3 # classic division returns a float
5.666666666666667
>>>
>>> 17 // 3 # floor division discards the fractional part
5
>>> 17 % 3 # the % operator returns the remainder of the division
2007-08-15 11:28:22 -03:00
2
>>> 5 * 3 + 2 # result * divisor + remainder
17
2007-08-15 11:28:22 -03:00
With Python, it is possible to use the ``**`` operator to calculate powers [#]_::
>>> 5 ** 2 # 5 squared
25
>>> 2 ** 7 # 2 to the power of 7
128
The equal sign (``=``) is used to assign a value to a variable. Afterwards, no
2007-08-15 11:28:22 -03:00
result is displayed before the next interactive prompt::
>>> width = 20
>>> height = 5 * 9
2007-08-15 11:28:22 -03:00
>>> width * height
900
If a variable is not "defined" (assigned a value), trying to use it will
give you an error::
2008-09-13 14:18:21 -03:00
>>> n # try to access an undefined variable
2009-01-03 17:18:54 -04:00
Traceback (most recent call last):
2008-09-13 14:18:21 -03:00
File "<stdin>", line 1, in <module>
NameError: name 'n' is not defined
2007-08-15 11:28:22 -03:00
There is full support for floating point; operators with mixed type operands
convert the integer operand to floating point::
>>> 3 * 3.75 / 1.5
7.5
>>> 7.0 / 2
3.5
In interactive mode, the last printed expression is assigned to the variable
``_``. This means that when you are using Python as a desk calculator, it is
somewhat easier to continue calculations, for example::
>>> tax = 12.5 / 100
>>> price = 100.50
>>> price * tax
12.5625
>>> price + _
113.0625
>>> round(_, 2)
113.06
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.
In addition to :class:`int` and :class:`float`, Python supports other types of
numbers, such as :class:`~decimal.Decimal` and :class:`~fractions.Fraction`.
Python also has built-in support for :ref:`complex numbers <typesnumeric>`,
and uses the ``j`` or ``J`` suffix to indicate the imaginary part
(e.g. ``3+5j``).
2007-08-15 11:28:22 -03:00
.. _tut-strings:
Strings
-------
Besides numbers, Python can also manipulate strings, which can be expressed
in several ways. They can be enclosed in single quotes (``'...'``) or
double quotes (``"..."``) with the same result [#]_. ``\`` can be used
to escape quotes::
2007-08-15 11:28:22 -03:00
>>> 'spam eggs' # single quotes
2007-08-15 11:28:22 -03:00
'spam eggs'
>>> 'doesn\'t' # use \' to escape the single quote...
2007-08-15 11:28:22 -03:00
"doesn't"
>>> "doesn't" # ...or use double quotes instead
2007-08-15 11:28:22 -03:00
"doesn't"
>>> '"Yes," he said.'
'"Yes," he said.'
>>> "\"Yes,\" he said."
'"Yes," he said.'
>>> '"Isn\'t," she said.'
'"Isn\'t," she said.'
In the interactive interpreter, the output string is enclosed in quotes and
special characters are escaped with backslashes. While this might sometimes
look different from the input (the enclosing quotes could change), the two
strings are equivalent. The string is enclosed in double quotes if
the string contains a single quote and no double quotes, otherwise it is
enclosed in single quotes. The :func:`print` function produces a more
readable output, by omitting the enclosing quotes and by printing escaped
and special characters::
>>> '"Isn\'t," she said.'
'"Isn\'t," she said.'
>>> print('"Isn\'t," she said.')
"Isn't," she said.
>>> s = 'First line.\nSecond line.' # \n means newline
>>> s # without print(), \n is included in the output
'First line.\nSecond line.'
>>> print(s) # with print(), \n produces a new line
First line.
Second line.
If you don't want characters prefaced by ``\`` to be interpreted as
special characters, you can use *raw strings* by adding an ``r`` before
the first quote::
>>> print('C:\some\name') # here \n means newline!
C:\some
ame
>>> print(r'C:\some\name') # note the r before the quote
C:\some\name
String literals can span multiple lines. One way is using triple-quotes:
``"""..."""`` or ``'''...'''``. End of lines are automatically
included in the string, but it's possible to prevent this by adding a ``\`` at
the end of the line. The following example::
Merged revisions 74277,74321,74323,74326,74355,74465,74467,74488,74492,74513,74531,74549,74553,74625,74632,74643-74644,74647,74652,74666,74671,74727,74739 via svnmerge from svn+ssh://pythondev@svn.python.org/python/trunk ........ r74277 | sean.reifschneider | 2009-08-01 18:54:55 -0500 (Sat, 01 Aug 2009) | 3 lines - Issue #6624: yArg_ParseTuple with "s" format when parsing argument with NUL: Bogus TypeError detail string. ........ r74321 | guilherme.polo | 2009-08-05 11:51:41 -0500 (Wed, 05 Aug 2009) | 1 line Easier reference to find (at least while svn continues being used). ........ r74323 | guilherme.polo | 2009-08-05 18:48:26 -0500 (Wed, 05 Aug 2009) | 1 line Typo. ........ r74326 | jesse.noller | 2009-08-05 21:05:56 -0500 (Wed, 05 Aug 2009) | 1 line Fix issue 4660: spurious task_done errors in multiprocessing, remove doc note for from_address ........ r74355 | gregory.p.smith | 2009-08-12 12:02:37 -0500 (Wed, 12 Aug 2009) | 2 lines comment typo fix ........ r74465 | vinay.sajip | 2009-08-15 18:23:12 -0500 (Sat, 15 Aug 2009) | 1 line Added section on logging to one file from multiple processes. ........ r74467 | vinay.sajip | 2009-08-15 18:34:47 -0500 (Sat, 15 Aug 2009) | 1 line Refined section on logging to one file from multiple processes. ........ r74488 | vinay.sajip | 2009-08-17 08:14:37 -0500 (Mon, 17 Aug 2009) | 1 line Further refined section on logging to one file from multiple processes. ........ r74492 | r.david.murray | 2009-08-17 14:26:49 -0500 (Mon, 17 Aug 2009) | 2 lines Issue 6685: 'toupper' -> 'upper' in cgi doc example explanation. ........ r74513 | skip.montanaro | 2009-08-18 09:37:52 -0500 (Tue, 18 Aug 2009) | 1 line missing module ref (issue6723) ........ r74531 | vinay.sajip | 2009-08-20 17:04:32 -0500 (Thu, 20 Aug 2009) | 1 line Added section on exceptions raised during logging. ........ r74549 | benjamin.peterson | 2009-08-24 12:42:36 -0500 (Mon, 24 Aug 2009) | 1 line fix pdf building by teaching latex the right encoding package ........ r74553 | r.david.murray | 2009-08-26 20:04:59 -0500 (Wed, 26 Aug 2009) | 2 lines Remove leftover text from end of sentence. ........ r74625 | benjamin.peterson | 2009-09-01 17:27:57 -0500 (Tue, 01 Sep 2009) | 1 line remove the check that classmethod's argument is a callable ........ r74632 | georg.brandl | 2009-09-03 02:27:26 -0500 (Thu, 03 Sep 2009) | 1 line #6828: fix wrongly highlighted blocks. ........ r74643 | georg.brandl | 2009-09-04 01:59:20 -0500 (Fri, 04 Sep 2009) | 2 lines Issue #2666: Handle BROWSER environment variable properly for unknown browser names in the webbrowser module. ........ r74644 | georg.brandl | 2009-09-04 02:55:14 -0500 (Fri, 04 Sep 2009) | 1 line #5047: remove Monterey support from configure. ........ r74647 | georg.brandl | 2009-09-04 03:17:04 -0500 (Fri, 04 Sep 2009) | 2 lines Issue #5275: In Cookie's Cookie.load(), properly handle non-string arguments as documented. ........ r74652 | georg.brandl | 2009-09-04 06:25:37 -0500 (Fri, 04 Sep 2009) | 1 line #6756: add some info about the "acct" parameter. ........ r74666 | georg.brandl | 2009-09-05 04:04:09 -0500 (Sat, 05 Sep 2009) | 1 line #6841: remove duplicated word. ........ r74671 | georg.brandl | 2009-09-05 11:47:17 -0500 (Sat, 05 Sep 2009) | 1 line #6843: add link from filterwarnings to where the meaning of the arguments is covered. ........ r74727 | benjamin.peterson | 2009-09-08 18:04:22 -0500 (Tue, 08 Sep 2009) | 1 line #6865 fix ref counting in initialization of pwd module ........ r74739 | georg.brandl | 2009-09-11 02:55:20 -0500 (Fri, 11 Sep 2009) | 1 line Move function back to its section. ........
2009-09-11 19:24:02 -03:00
2010-11-12 00:22:22 -04:00
print("""\
Merged revisions 74277,74321,74323,74326,74355,74465,74467,74488,74492,74513,74531,74549,74553,74625,74632,74643-74644,74647,74652,74666,74671,74727,74739 via svnmerge from svn+ssh://pythondev@svn.python.org/python/trunk ........ r74277 | sean.reifschneider | 2009-08-01 18:54:55 -0500 (Sat, 01 Aug 2009) | 3 lines - Issue #6624: yArg_ParseTuple with "s" format when parsing argument with NUL: Bogus TypeError detail string. ........ r74321 | guilherme.polo | 2009-08-05 11:51:41 -0500 (Wed, 05 Aug 2009) | 1 line Easier reference to find (at least while svn continues being used). ........ r74323 | guilherme.polo | 2009-08-05 18:48:26 -0500 (Wed, 05 Aug 2009) | 1 line Typo. ........ r74326 | jesse.noller | 2009-08-05 21:05:56 -0500 (Wed, 05 Aug 2009) | 1 line Fix issue 4660: spurious task_done errors in multiprocessing, remove doc note for from_address ........ r74355 | gregory.p.smith | 2009-08-12 12:02:37 -0500 (Wed, 12 Aug 2009) | 2 lines comment typo fix ........ r74465 | vinay.sajip | 2009-08-15 18:23:12 -0500 (Sat, 15 Aug 2009) | 1 line Added section on logging to one file from multiple processes. ........ r74467 | vinay.sajip | 2009-08-15 18:34:47 -0500 (Sat, 15 Aug 2009) | 1 line Refined section on logging to one file from multiple processes. ........ r74488 | vinay.sajip | 2009-08-17 08:14:37 -0500 (Mon, 17 Aug 2009) | 1 line Further refined section on logging to one file from multiple processes. ........ r74492 | r.david.murray | 2009-08-17 14:26:49 -0500 (Mon, 17 Aug 2009) | 2 lines Issue 6685: 'toupper' -> 'upper' in cgi doc example explanation. ........ r74513 | skip.montanaro | 2009-08-18 09:37:52 -0500 (Tue, 18 Aug 2009) | 1 line missing module ref (issue6723) ........ r74531 | vinay.sajip | 2009-08-20 17:04:32 -0500 (Thu, 20 Aug 2009) | 1 line Added section on exceptions raised during logging. ........ r74549 | benjamin.peterson | 2009-08-24 12:42:36 -0500 (Mon, 24 Aug 2009) | 1 line fix pdf building by teaching latex the right encoding package ........ r74553 | r.david.murray | 2009-08-26 20:04:59 -0500 (Wed, 26 Aug 2009) | 2 lines Remove leftover text from end of sentence. ........ r74625 | benjamin.peterson | 2009-09-01 17:27:57 -0500 (Tue, 01 Sep 2009) | 1 line remove the check that classmethod's argument is a callable ........ r74632 | georg.brandl | 2009-09-03 02:27:26 -0500 (Thu, 03 Sep 2009) | 1 line #6828: fix wrongly highlighted blocks. ........ r74643 | georg.brandl | 2009-09-04 01:59:20 -0500 (Fri, 04 Sep 2009) | 2 lines Issue #2666: Handle BROWSER environment variable properly for unknown browser names in the webbrowser module. ........ r74644 | georg.brandl | 2009-09-04 02:55:14 -0500 (Fri, 04 Sep 2009) | 1 line #5047: remove Monterey support from configure. ........ r74647 | georg.brandl | 2009-09-04 03:17:04 -0500 (Fri, 04 Sep 2009) | 2 lines Issue #5275: In Cookie's Cookie.load(), properly handle non-string arguments as documented. ........ r74652 | georg.brandl | 2009-09-04 06:25:37 -0500 (Fri, 04 Sep 2009) | 1 line #6756: add some info about the "acct" parameter. ........ r74666 | georg.brandl | 2009-09-05 04:04:09 -0500 (Sat, 05 Sep 2009) | 1 line #6841: remove duplicated word. ........ r74671 | georg.brandl | 2009-09-05 11:47:17 -0500 (Sat, 05 Sep 2009) | 1 line #6843: add link from filterwarnings to where the meaning of the arguments is covered. ........ r74727 | benjamin.peterson | 2009-09-08 18:04:22 -0500 (Tue, 08 Sep 2009) | 1 line #6865 fix ref counting in initialization of pwd module ........ r74739 | georg.brandl | 2009-09-11 02:55:20 -0500 (Fri, 11 Sep 2009) | 1 line Move function back to its section. ........
2009-09-11 19:24:02 -03:00
Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
2009-09-25 17:14:02 -03:00
""")
Merged revisions 74277,74321,74323,74326,74355,74465,74467,74488,74492,74513,74531,74549,74553,74625,74632,74643-74644,74647,74652,74666,74671,74727,74739 via svnmerge from svn+ssh://pythondev@svn.python.org/python/trunk ........ r74277 | sean.reifschneider | 2009-08-01 18:54:55 -0500 (Sat, 01 Aug 2009) | 3 lines - Issue #6624: yArg_ParseTuple with "s" format when parsing argument with NUL: Bogus TypeError detail string. ........ r74321 | guilherme.polo | 2009-08-05 11:51:41 -0500 (Wed, 05 Aug 2009) | 1 line Easier reference to find (at least while svn continues being used). ........ r74323 | guilherme.polo | 2009-08-05 18:48:26 -0500 (Wed, 05 Aug 2009) | 1 line Typo. ........ r74326 | jesse.noller | 2009-08-05 21:05:56 -0500 (Wed, 05 Aug 2009) | 1 line Fix issue 4660: spurious task_done errors in multiprocessing, remove doc note for from_address ........ r74355 | gregory.p.smith | 2009-08-12 12:02:37 -0500 (Wed, 12 Aug 2009) | 2 lines comment typo fix ........ r74465 | vinay.sajip | 2009-08-15 18:23:12 -0500 (Sat, 15 Aug 2009) | 1 line Added section on logging to one file from multiple processes. ........ r74467 | vinay.sajip | 2009-08-15 18:34:47 -0500 (Sat, 15 Aug 2009) | 1 line Refined section on logging to one file from multiple processes. ........ r74488 | vinay.sajip | 2009-08-17 08:14:37 -0500 (Mon, 17 Aug 2009) | 1 line Further refined section on logging to one file from multiple processes. ........ r74492 | r.david.murray | 2009-08-17 14:26:49 -0500 (Mon, 17 Aug 2009) | 2 lines Issue 6685: 'toupper' -> 'upper' in cgi doc example explanation. ........ r74513 | skip.montanaro | 2009-08-18 09:37:52 -0500 (Tue, 18 Aug 2009) | 1 line missing module ref (issue6723) ........ r74531 | vinay.sajip | 2009-08-20 17:04:32 -0500 (Thu, 20 Aug 2009) | 1 line Added section on exceptions raised during logging. ........ r74549 | benjamin.peterson | 2009-08-24 12:42:36 -0500 (Mon, 24 Aug 2009) | 1 line fix pdf building by teaching latex the right encoding package ........ r74553 | r.david.murray | 2009-08-26 20:04:59 -0500 (Wed, 26 Aug 2009) | 2 lines Remove leftover text from end of sentence. ........ r74625 | benjamin.peterson | 2009-09-01 17:27:57 -0500 (Tue, 01 Sep 2009) | 1 line remove the check that classmethod's argument is a callable ........ r74632 | georg.brandl | 2009-09-03 02:27:26 -0500 (Thu, 03 Sep 2009) | 1 line #6828: fix wrongly highlighted blocks. ........ r74643 | georg.brandl | 2009-09-04 01:59:20 -0500 (Fri, 04 Sep 2009) | 2 lines Issue #2666: Handle BROWSER environment variable properly for unknown browser names in the webbrowser module. ........ r74644 | georg.brandl | 2009-09-04 02:55:14 -0500 (Fri, 04 Sep 2009) | 1 line #5047: remove Monterey support from configure. ........ r74647 | georg.brandl | 2009-09-04 03:17:04 -0500 (Fri, 04 Sep 2009) | 2 lines Issue #5275: In Cookie's Cookie.load(), properly handle non-string arguments as documented. ........ r74652 | georg.brandl | 2009-09-04 06:25:37 -0500 (Fri, 04 Sep 2009) | 1 line #6756: add some info about the "acct" parameter. ........ r74666 | georg.brandl | 2009-09-05 04:04:09 -0500 (Sat, 05 Sep 2009) | 1 line #6841: remove duplicated word. ........ r74671 | georg.brandl | 2009-09-05 11:47:17 -0500 (Sat, 05 Sep 2009) | 1 line #6843: add link from filterwarnings to where the meaning of the arguments is covered. ........ r74727 | benjamin.peterson | 2009-09-08 18:04:22 -0500 (Tue, 08 Sep 2009) | 1 line #6865 fix ref counting in initialization of pwd module ........ r74739 | georg.brandl | 2009-09-11 02:55:20 -0500 (Fri, 11 Sep 2009) | 1 line Move function back to its section. ........
2009-09-11 19:24:02 -03:00
produces the following output (note that the initial newline is not included):
Merged revisions 74277,74321,74323,74326,74355,74465,74467,74488,74492,74513,74531,74549,74553,74625,74632,74643-74644,74647,74652,74666,74671,74727,74739 via svnmerge from svn+ssh://pythondev@svn.python.org/python/trunk ........ r74277 | sean.reifschneider | 2009-08-01 18:54:55 -0500 (Sat, 01 Aug 2009) | 3 lines - Issue #6624: yArg_ParseTuple with "s" format when parsing argument with NUL: Bogus TypeError detail string. ........ r74321 | guilherme.polo | 2009-08-05 11:51:41 -0500 (Wed, 05 Aug 2009) | 1 line Easier reference to find (at least while svn continues being used). ........ r74323 | guilherme.polo | 2009-08-05 18:48:26 -0500 (Wed, 05 Aug 2009) | 1 line Typo. ........ r74326 | jesse.noller | 2009-08-05 21:05:56 -0500 (Wed, 05 Aug 2009) | 1 line Fix issue 4660: spurious task_done errors in multiprocessing, remove doc note for from_address ........ r74355 | gregory.p.smith | 2009-08-12 12:02:37 -0500 (Wed, 12 Aug 2009) | 2 lines comment typo fix ........ r74465 | vinay.sajip | 2009-08-15 18:23:12 -0500 (Sat, 15 Aug 2009) | 1 line Added section on logging to one file from multiple processes. ........ r74467 | vinay.sajip | 2009-08-15 18:34:47 -0500 (Sat, 15 Aug 2009) | 1 line Refined section on logging to one file from multiple processes. ........ r74488 | vinay.sajip | 2009-08-17 08:14:37 -0500 (Mon, 17 Aug 2009) | 1 line Further refined section on logging to one file from multiple processes. ........ r74492 | r.david.murray | 2009-08-17 14:26:49 -0500 (Mon, 17 Aug 2009) | 2 lines Issue 6685: 'toupper' -> 'upper' in cgi doc example explanation. ........ r74513 | skip.montanaro | 2009-08-18 09:37:52 -0500 (Tue, 18 Aug 2009) | 1 line missing module ref (issue6723) ........ r74531 | vinay.sajip | 2009-08-20 17:04:32 -0500 (Thu, 20 Aug 2009) | 1 line Added section on exceptions raised during logging. ........ r74549 | benjamin.peterson | 2009-08-24 12:42:36 -0500 (Mon, 24 Aug 2009) | 1 line fix pdf building by teaching latex the right encoding package ........ r74553 | r.david.murray | 2009-08-26 20:04:59 -0500 (Wed, 26 Aug 2009) | 2 lines Remove leftover text from end of sentence. ........ r74625 | benjamin.peterson | 2009-09-01 17:27:57 -0500 (Tue, 01 Sep 2009) | 1 line remove the check that classmethod's argument is a callable ........ r74632 | georg.brandl | 2009-09-03 02:27:26 -0500 (Thu, 03 Sep 2009) | 1 line #6828: fix wrongly highlighted blocks. ........ r74643 | georg.brandl | 2009-09-04 01:59:20 -0500 (Fri, 04 Sep 2009) | 2 lines Issue #2666: Handle BROWSER environment variable properly for unknown browser names in the webbrowser module. ........ r74644 | georg.brandl | 2009-09-04 02:55:14 -0500 (Fri, 04 Sep 2009) | 1 line #5047: remove Monterey support from configure. ........ r74647 | georg.brandl | 2009-09-04 03:17:04 -0500 (Fri, 04 Sep 2009) | 2 lines Issue #5275: In Cookie's Cookie.load(), properly handle non-string arguments as documented. ........ r74652 | georg.brandl | 2009-09-04 06:25:37 -0500 (Fri, 04 Sep 2009) | 1 line #6756: add some info about the "acct" parameter. ........ r74666 | georg.brandl | 2009-09-05 04:04:09 -0500 (Sat, 05 Sep 2009) | 1 line #6841: remove duplicated word. ........ r74671 | georg.brandl | 2009-09-05 11:47:17 -0500 (Sat, 05 Sep 2009) | 1 line #6843: add link from filterwarnings to where the meaning of the arguments is covered. ........ r74727 | benjamin.peterson | 2009-09-08 18:04:22 -0500 (Tue, 08 Sep 2009) | 1 line #6865 fix ref counting in initialization of pwd module ........ r74739 | georg.brandl | 2009-09-11 02:55:20 -0500 (Fri, 11 Sep 2009) | 1 line Move function back to its section. ........
2009-09-11 19:24:02 -03:00
.. code-block:: text
Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
2007-08-15 11:28:22 -03:00
Strings can be concatenated (glued together) with the ``+`` operator, and
repeated with ``*``::
>>> # 3 times 'un', followed by 'ium'
>>> 3 * 'un' + 'ium'
'unununium'
2007-08-15 11:28:22 -03:00
Two or more *string literals* (i.e. the ones enclosed between quotes) next
to each other are automatically concatenated. ::
2007-08-15 11:28:22 -03:00
>>> 'Py' 'thon'
'Python'
2007-08-15 11:28:22 -03:00
This only works with two literals though, not with variables or expressions::
2007-08-15 11:28:22 -03:00
>>> prefix = 'Py'
>>> prefix 'thon' # can't concatenate a variable and a string literal
...
SyntaxError: invalid syntax
>>> ('un' * 3) 'ium'
...
SyntaxError: invalid syntax
2007-08-15 11:28:22 -03:00
If you want to concatenate variables or a variable and a literal, use ``+``::
2007-08-15 11:28:22 -03:00
>>> prefix + 'thon'
'Python'
2007-08-15 11:28:22 -03:00
This feature is particularly useful when you want to break long strings::
2007-08-15 11:28:22 -03:00
>>> text = ('Put several strings within parentheses '
'to have them joined together.')
>>> text
'Put several strings within parentheses to have them joined together.'
2007-08-15 11:28:22 -03:00
Strings can be *indexed* (subscripted), with the first character having index 0.
There is no separate character type; a character is simply a string of size
one::
2007-08-15 11:28:22 -03:00
>>> word = 'Python'
>>> word[0] # character in position 0
'P'
>>> word[5] # character in position 5
'n'
2007-08-15 11:28:22 -03:00
Indices may also be negative numbers, to start counting from the right::
2007-08-15 11:28:22 -03:00
>>> word[-1] # last character
'n'
>>> word[-2] # second-last character
'o'
>>> word[-6]
'P'
2007-08-15 11:28:22 -03:00
Note that since -0 is the same as 0, negative indices start from -1.
2007-08-15 11:28:22 -03:00
In addition to indexing, *slicing* is also supported. While indexing is used
to obtain individual characters, *slicing* allows you to obtain substring::
2007-08-15 11:28:22 -03:00
>>> word[0:2] # characters from position 0 (included) to 2 (excluded)
'Py'
>>> word[2:5] # characters from position 2 (included) to 5 (excluded)
'tho'
2007-08-15 11:28:22 -03:00
Note how the start is always included, and the end always excluded. This
makes sure that ``s[:i] + s[i:]`` is always equal to ``s``::
2007-08-15 11:28:22 -03:00
>>> word[:2] + word[2:]
'Python'
>>> word[:4] + word[4:]
'Python'
2007-08-15 11:28:22 -03:00
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. ::
>>> word[:2] # character from the beginning to position 2 (excluded)
'Py'
>>> word[4:] # characters from position 4 (included) to the end
'on'
>>> word[-2:] # characters from the second-last (included) to the end
'on'
2007-08-15 11:28:22 -03:00
One way to remember how slices work is to think of the indices as pointing
*between* characters, with the left edge of the first character numbered 0.
Then the right edge of the last character of a string of *n* characters has
index *n*, for example::
+---+---+---+---+---+---+
| P | y | t | h | o | n |
+---+---+---+---+---+---+
0 1 2 3 4 5 6
-6 -5 -4 -3 -2 -1
2007-08-15 11:28:22 -03:00
The first row of numbers gives the position of the indices 0...6 in the string;
2007-08-15 11:28:22 -03:00
the second row gives the corresponding negative indices. The slice from *i* to
*j* consists of all characters between the edges labeled *i* and *j*,
respectively.
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 ``word[1:3]`` is
2.
Attempting to use an index that is too large will result in an error::
>>> word[42] # the word only has 6 characters
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: string index out of range
However, out of range slice indexes are handled gracefully when used for
slicing::
>>> word[4:42]
'on'
>>> word[42:]
''
Python strings cannot be changed --- they are :term:`immutable`.
Therefore, assigning to an indexed position in the string results in an error::
>>> word[0] = 'J'
...
TypeError: 'str' object does not support item assignment
>>> word[2:] = 'py'
...
TypeError: 'str' object does not support item assignment
If you need a different string, you should create a new one::
>>> 'J' + word[1:]
'Jython'
>>> word[:2] + 'py'
'Pypy'
2007-08-15 11:28:22 -03:00
The built-in function :func:`len` returns the length of a string::
>>> s = 'supercalifragilisticexpialidocious'
>>> len(s)
34
.. seealso::
2012-10-12 04:59:14 -03:00
:ref:`textseq`
2009-01-03 17:18:54 -04:00
Strings are examples of *sequence types*, and support the common
operations supported by such types.
2007-08-15 11:28:22 -03:00
:ref:`string-methods`
Strings support a large number of methods for
2007-08-15 11:28:22 -03:00
basic transformations and searching.
:ref:`f-strings`
String literals that have embedded expressions.
:ref:`formatstrings`
Information about string formatting with :meth:`str.format`.
:ref:`old-string-formatting`
The old formatting operations invoked when strings and Unicode strings are
the left operand of the ``%`` operator are described in more detail here.
2007-08-15 11:28:22 -03:00
.. _tut-lists:
2007-08-15 11:28:22 -03:00
Lists
-----
2007-08-15 11:28:22 -03:00
Python knows a number of *compound* data types, used to group together other
values. The most versatile is the *list*, which can be written as a list of
comma-separated values (items) between square brackets. Lists might contain
items of different types, but usually the items all have the same type. ::
2007-08-15 11:28:22 -03:00
>>> squares = [1, 4, 9, 16, 25]
>>> squares
[1, 4, 9, 16, 25]
2007-08-15 11:28:22 -03:00
Like strings (and all other built-in :term:`sequence` type), lists can be
indexed and sliced::
2007-08-15 11:28:22 -03:00
>>> squares[0] # indexing returns the item
1
>>> squares[-1]
25
>>> squares[-3:] # slicing returns a new list
[9, 16, 25]
2007-08-15 11:28:22 -03:00
All slice operations return a new list containing the requested elements. This
means that the following slice returns a new (shallow) copy of the list::
2007-08-15 11:28:22 -03:00
>>> squares[:]
[1, 4, 9, 16, 25]
2007-08-15 11:28:22 -03:00
Lists also support operations like concatenation::
2007-08-15 11:28:22 -03:00
>>> squares + [36, 49, 64, 81, 100]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
2007-08-15 11:28:22 -03:00
Unlike strings, which are :term:`immutable`, lists are a :term:`mutable`
type, i.e. it is possible to change their content::
Merged revisions 78966,78970,79018,79026-79027,79055,79156,79159,79163-79164,79173,79176,79194,79208,79212 via svnmerge from svn+ssh://pythondev@svn.python.org/python/trunk ........ r78966 | florent.xicluna | 2010-03-14 10:20:59 -0500 (Sun, 14 Mar 2010) | 2 lines Do not hardcode Expat version. It's possible to build Python with --with-system-expat option. ........ r78970 | benjamin.peterson | 2010-03-14 21:58:24 -0500 (Sun, 14 Mar 2010) | 1 line this little exception dance is pointless ........ r79018 | collin.winter | 2010-03-16 22:04:01 -0500 (Tue, 16 Mar 2010) | 1 line Delete unused import. ........ r79026 | vinay.sajip | 2010-03-17 10:05:57 -0500 (Wed, 17 Mar 2010) | 1 line Issue #8162: logging: Clarified docstring and documentation for disable function. ........ r79027 | collin.winter | 2010-03-17 12:36:16 -0500 (Wed, 17 Mar 2010) | 1 line Avoid hardcoding refcounts in tests. ........ r79055 | benjamin.peterson | 2010-03-18 16:30:48 -0500 (Thu, 18 Mar 2010) | 1 line remove installation of deleted test/output dir ........ r79156 | florent.xicluna | 2010-03-20 17:21:02 -0500 (Sat, 20 Mar 2010) | 2 lines Cleanup test_struct using check_warnings. ........ r79159 | florent.xicluna | 2010-03-20 17:26:42 -0500 (Sat, 20 Mar 2010) | 2 lines Cleanup test_tarfile, and use check_warnings. ........ r79163 | michael.foord | 2010-03-20 19:53:39 -0500 (Sat, 20 Mar 2010) | 1 line A faulty load_tests in a test module no longer halts test discovery. A placeholder test, that reports the failure, is created instead. ........ r79164 | michael.foord | 2010-03-20 19:55:58 -0500 (Sat, 20 Mar 2010) | 1 line Change order of arguments in a unittest function. ........ r79173 | georg.brandl | 2010-03-21 04:09:38 -0500 (Sun, 21 Mar 2010) | 1 line Document that GzipFile supports iteration. ........ r79176 | georg.brandl | 2010-03-21 04:17:41 -0500 (Sun, 21 Mar 2010) | 1 line Introduce copy by slicing, used in later chapters. ........ r79194 | florent.xicluna | 2010-03-21 06:58:11 -0500 (Sun, 21 Mar 2010) | 2 lines Use assertRaises and add a specific warning filter. ........ r79208 | andrew.kuchling | 2010-03-21 13:47:12 -0500 (Sun, 21 Mar 2010) | 1 line Add items ........ r79212 | georg.brandl | 2010-03-21 14:01:38 -0500 (Sun, 21 Mar 2010) | 1 line Fix plural. ........
2010-03-21 20:13:07 -03:00
>>> cubes = [1, 8, 27, 65, 125] # something's wrong here
>>> 4 ** 3 # the cube of 4 is 64, not 65!
64
>>> cubes[3] = 64 # replace the wrong value
>>> cubes
[1, 8, 27, 64, 125]
Merged revisions 78966,78970,79018,79026-79027,79055,79156,79159,79163-79164,79173,79176,79194,79208,79212 via svnmerge from svn+ssh://pythondev@svn.python.org/python/trunk ........ r78966 | florent.xicluna | 2010-03-14 10:20:59 -0500 (Sun, 14 Mar 2010) | 2 lines Do not hardcode Expat version. It's possible to build Python with --with-system-expat option. ........ r78970 | benjamin.peterson | 2010-03-14 21:58:24 -0500 (Sun, 14 Mar 2010) | 1 line this little exception dance is pointless ........ r79018 | collin.winter | 2010-03-16 22:04:01 -0500 (Tue, 16 Mar 2010) | 1 line Delete unused import. ........ r79026 | vinay.sajip | 2010-03-17 10:05:57 -0500 (Wed, 17 Mar 2010) | 1 line Issue #8162: logging: Clarified docstring and documentation for disable function. ........ r79027 | collin.winter | 2010-03-17 12:36:16 -0500 (Wed, 17 Mar 2010) | 1 line Avoid hardcoding refcounts in tests. ........ r79055 | benjamin.peterson | 2010-03-18 16:30:48 -0500 (Thu, 18 Mar 2010) | 1 line remove installation of deleted test/output dir ........ r79156 | florent.xicluna | 2010-03-20 17:21:02 -0500 (Sat, 20 Mar 2010) | 2 lines Cleanup test_struct using check_warnings. ........ r79159 | florent.xicluna | 2010-03-20 17:26:42 -0500 (Sat, 20 Mar 2010) | 2 lines Cleanup test_tarfile, and use check_warnings. ........ r79163 | michael.foord | 2010-03-20 19:53:39 -0500 (Sat, 20 Mar 2010) | 1 line A faulty load_tests in a test module no longer halts test discovery. A placeholder test, that reports the failure, is created instead. ........ r79164 | michael.foord | 2010-03-20 19:55:58 -0500 (Sat, 20 Mar 2010) | 1 line Change order of arguments in a unittest function. ........ r79173 | georg.brandl | 2010-03-21 04:09:38 -0500 (Sun, 21 Mar 2010) | 1 line Document that GzipFile supports iteration. ........ r79176 | georg.brandl | 2010-03-21 04:17:41 -0500 (Sun, 21 Mar 2010) | 1 line Introduce copy by slicing, used in later chapters. ........ r79194 | florent.xicluna | 2010-03-21 06:58:11 -0500 (Sun, 21 Mar 2010) | 2 lines Use assertRaises and add a specific warning filter. ........ r79208 | andrew.kuchling | 2010-03-21 13:47:12 -0500 (Sun, 21 Mar 2010) | 1 line Add items ........ r79212 | georg.brandl | 2010-03-21 14:01:38 -0500 (Sun, 21 Mar 2010) | 1 line Fix plural. ........
2010-03-21 20:13:07 -03:00
You can also add new items at the end of the list, by using
the :meth:`~list.append` *method* (we will see more about methods later)::
2007-08-15 11:28:22 -03:00
>>> cubes.append(216) # add the cube of 6
>>> cubes.append(7 ** 3) # and the cube of 7
>>> cubes
[1, 8, 27, 64, 125, 216, 343]
2007-08-15 11:28:22 -03:00
Assignment to slices is also possible, and this can even change the size of the
list or clear it entirely::
>>> letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> letters
['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> # replace some values
>>> letters[2:5] = ['C', 'D', 'E']
>>> letters
['a', 'b', 'C', 'D', 'E', 'f', 'g']
>>> # now remove them
>>> letters[2:5] = []
>>> letters
['a', 'b', 'f', 'g']
>>> # clear the list by replacing all the elements with an empty list
>>> letters[:] = []
>>> letters
2007-08-15 11:28:22 -03:00
[]
The built-in function :func:`len` also applies to lists::
>>> letters = ['a', 'b', 'c', 'd']
>>> len(letters)
Merged revisions 58886-58929 via svnmerge from svn+ssh://pythondev@svn.python.org/python/trunk ........ r58892 | guido.van.rossum | 2007-11-06 15:32:56 -0800 (Tue, 06 Nov 2007) | 2 lines Add missing "return NULL" in overflow check in PyObject_Repr(). ........ r58893 | raymond.hettinger | 2007-11-06 17:13:09 -0800 (Tue, 06 Nov 2007) | 1 line Fix marshal's incorrect handling of subclasses of builtin types (backport candidate). ........ r58895 | raymond.hettinger | 2007-11-06 18:26:17 -0800 (Tue, 06 Nov 2007) | 1 line Optimize dict.fromkeys() with dict inputs. Useful for resetting bag/muliset counts for example. ........ r58896 | raymond.hettinger | 2007-11-06 18:45:46 -0800 (Tue, 06 Nov 2007) | 1 line Add build option for faster loop execution. ........ r58900 | nick.coghlan | 2007-11-07 03:57:51 -0800 (Wed, 07 Nov 2007) | 1 line Add missing NEWS entry ........ r58905 | christian.heimes | 2007-11-07 09:50:54 -0800 (Wed, 07 Nov 2007) | 1 line Backported fix for bug #1392 from py3k branch r58903. ........ r58906 | christian.heimes | 2007-11-07 10:30:22 -0800 (Wed, 07 Nov 2007) | 1 line Backport of Guido's review of my patch. ........ r58908 | raymond.hettinger | 2007-11-07 18:52:43 -0800 (Wed, 07 Nov 2007) | 1 line Add set.isdisjoint() ........ r58915 | raymond.hettinger | 2007-11-08 10:47:51 -0800 (Thu, 08 Nov 2007) | 1 line Reposition the decref (spotted by eagle-eye norwitz). ........ r58920 | georg.brandl | 2007-11-09 04:31:43 -0800 (Fri, 09 Nov 2007) | 2 lines Fix seealso link to sets docs. Do not merge to Py3k. ........ r58921 | georg.brandl | 2007-11-09 05:08:48 -0800 (Fri, 09 Nov 2007) | 2 lines Fix misleading example. ........ r58923 | georg.brandl | 2007-11-09 09:33:23 -0800 (Fri, 09 Nov 2007) | 3 lines Correct a comment about testing methods - nowadays most tests don't run directly on import. ........ r58924 | martin.v.loewis | 2007-11-09 14:56:30 -0800 (Fri, 09 Nov 2007) | 2 lines Add Amaury Forgeot d'Arc. ........ r58925 | raymond.hettinger | 2007-11-09 15:14:44 -0800 (Fri, 09 Nov 2007) | 1 line Optimize common case for dict.fromkeys(). ........ r58927 | raymond.hettinger | 2007-11-09 17:54:03 -0800 (Fri, 09 Nov 2007) | 1 line Use a freelist to speed-up block allocation and deallocation in collections.deque(). ........ r58929 | guido.van.rossum | 2007-11-10 14:12:24 -0800 (Sat, 10 Nov 2007) | 3 lines Issue 1416. Add getter, setter, deleter methods to properties that can be used as decorators to create fully-populated properties. ........
2007-11-10 19:39:45 -04:00
4
2007-08-15 11:28:22 -03:00
It is possible to nest lists (create lists containing other lists), for
example::
>>> 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'
2007-08-15 11:28:22 -03:00
.. _tut-firststeps:
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:
2008-01-07 13:32:13 -04:00
... print(b)
... a, b = b, a+b
2009-01-03 17:18:54 -04:00
...
2007-08-15 11:28:22 -03:00
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 :keyword:`while` loop 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), ``>`` (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.
2007-08-15 11:28:22 -03:00
2013-01-20 11:05:13 -04:00
* The :func:`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::
2007-08-15 11:28:22 -03:00
>>> i = 256*256
>>> print('The value of i is', i)
2007-08-15 11:28:22 -03:00
The value of i is 65536
2013-01-20 11:09:44 -04:00
The keyword argument *end* can be used to avoid the newline after the output,
or end the output with a different string::
2007-08-15 11:28:22 -03:00
>>> a, b = 0, 1
>>> while b < 1000:
2010-11-12 00:22:22 -04:00
... print(b, end=',')
2007-08-15 11:28:22 -03:00
... a, b = b, a+b
2009-01-03 17:18:54 -04:00
...
2010-11-12 00:22:22 -04:00
1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,
.. rubric:: Footnotes
.. [#] Since ``**`` has higher precedence than ``-``, ``-3**2`` will be
interpreted as ``-(3**2)`` and thus result in ``-9``. To avoid this
and get ``9``, you can use ``(-3)**2``.
.. [#] Unlike other languages, special characters such as ``\n`` have the
same meaning with both single (``'...'``) and double (``"..."``) quotes.
The only difference between the two is that within single quotes you don't
need to escape ``"`` (but you have to escape ``\'``) and vice versa.