=====================================
Introduction to Python for Scientists
=====================================
Stefan Schwarzer <sschwarzer@sschwarzer.com>
EuroSciPy 2012
Brussels, 2012-08-23
Tutorial content is at
Overview
--------
* About this tutorial
* First steps in the interpreter
* Names
* Data types
* Conditional statements (``)
* Loops (``, ``)
* Exceptions (``, ``)
* Modules
* Built-in functions
* Object-Oriented Programming (OOP)
About This Workshop
-------------------
* Introduction to the Python programming language
* No prior Python knowledge necessary
* ... but programming knowledge (ideally also in object-oriented
programming)
* Objective of this workshop: participants should be able to
write (at least) small programs
* There's always too little time. :-/
Consequences:
- Only the most important concepts and libraries are explained.
- Possibly there's not enough time to finish the exercises.
- You don't need to understand every detail.
- Please give me feedback about how it goes during the break (or
even earlier)
* We use Python 2.x (better supported at this time, i. e. there are
far more libraries working with Python 2.x)
* If you have questions during the exercises, please ask!
* Remarks:
- Code embedded in the text are enclosed in backticks, for example
``.
- (G)Vim users get syntax highlighting for this text file if they
load ("source") ``.
- Most of the example code in this file is executed with the help of
a small script ``. This is in the zip file for this
tutorial.
Important Literature / Links
----------------------------
* Python homepage:
* Official Python documentation
- Homepage:
- Tutorial:
- Library Reference:
- Language Reference:
* Python Style Guides
-
-
* Python Package Index:
* Common Python mistakes:
* Book "Learning Python"
describes Python 2.x *and* 3.x ! :-)
The Python Language
-------------------
* Allows compact, highly readable programs
* Is relatively easy to learn
* Very useful for scientific software, but also
- system administration
- web applications
- very good "glue language" to connect different systems
* Python supports these programming paradigms:
- procedural
- object-oriented
- some functional programming elements (but not really a functional
language like, say, Haskell)
* Pre-installed on many Linux systems; easily installable on
Windows. There are installer packages ("distributions") especially
for scientic use:
-
-
First Steps in the Interactive Interpreter
------------------------------------------
* Python interpreter can be used interactively. Just start
`` on the command line.
* Interactive mode is excellent to try things out.
* Best way to get a first impression of Python. Example:
* Also, for advanced Python users, to try out modules (libraries).
Example:
* Exit the interpreter at the prompt `` with ctrl-d on Linux/Unix,
ctrl-z on Windows.
Highly Recommended: The Extended IPython Interpreter
----------------------------------------------------
* Available on Linux via the package system. IPython is part of
the special scientific Python distributions.
* Tab completion
* Command history (you can use the arrow keys to see previous
commands, but you can also retrieve previous input and output with
`` and ``, respectively. Example:
* Get help `` or even source code ``:
Getting the source code will only work for items which are
programmed in pure Python, not in compiled languages like C or
Fortran.
* So called "magic" commands, prefixed with ``. For example
- ``: create a simple command to save keystrokes
- ``: edit previously input lines or a file from inside IPython
- ``: combine several input commands into one for easy use
- ``, ``: get or set current working directory
- ``: benchmark some code
* Invocation with `` provides a Matlab-like environment
where NumPy (matrix calculations) and matplotlib (diagramming) are
already loaded.
Identifiers (Names)
-------------------
* Names consist of A-Z, a-z, 0-9 and _
* First character must not be a digit.
* Names are case-sensitive; `` and `` are different
identifiers.
* Keywords *cannot* be used as names.
* Keywords are
* Built-in functions *should* *not* be used as names; see
* PEP 8 lists naming conventions (more on this below). Examples:
- constants: ``
- classes: ``
- modules: preferably ``, else ``
- everything else: ``
Use of underscores:
- non-public name: ``
- "private" attribute in a class: ``
- special method names: ``
Datatypes
---------
* Simple datatypes
- numbers (``, ``, ``, ``)
- boolean values (``)
- strings (``, ``)
* Container datatypes
- lists (``)
- tuples (``)
- dictionarys = associative arrays = hashes(``)
- sets (``)
* Functions, classes, methods
* Files
* Modules
* Some other, more exotic types
Numbers
-------
* Examples
* There are `` and `` types, but you can usually ignore the
difference. If necessary, ``s are converted to ``s
implicitly.
* `` values correspond to C's `` type with a precision
of about 16 significant digits.
* `` values consist of real and imaginary part:
* If different numeric datatypes are used in an expression, the values
are implicitly converted to the "highest" type (`` -> `` ->
`` -> ``). Examples:
* Interpreter playtime
Boolean Values
--------------
* Boolean values are the constants `` and ``.
* Actually, `` and `` are integer values in disguise.
Warning: Such expressions can impair the readability of the code.
Think a bit about whether you can use other code that's easier to
understand.
* Boolean values can be combined with ``, `` and ``
(in order of increasing priority).
* `` and `` are "short-circuit operators". This means the
second operand won't even be evaluated if the result is already
known. The result then is the first operand (but not necessarily
`` or ``).
* More on `` values below
Strings
-------
* Python doesn't have a special type for single characters (unlike
`` in C).
* Strings are enclosed in quote characters:
* These "triple-quoted" strings can contain all other kinds of quotes,
just not "themselves". So the following is *not* possible:
* Quote characters can be "escaped" with backslashes if desired:
Usually this isn't necessary though.
* All strings so far are of type ``. There are also unicode strings
(type ``).
* As in other languages, there are a few special strings:
\" escaped double quote
\' escaped single quote
\n line feed (newline)
\t tab
\r carriage return ("\r\n" is the usual line end string under
Windows)
\b backspace
Even characters which aren't on any keyboard can be expressed by
their numerical codes:
\xhh byte with hexadecimal code hh
\uhhhh unicode character of code point hhhh
\Uhhhhhhhh ditto, with 8 hexadecimal digits
see
* If there's an `` before a quote character that introduces a string,
the string is a "raw string". In it, escapes are ignored. Example:
The latter string actually doesn't contain a newline character but a
`` and an ``.
* Strings can be compared with comparison operators like
``, ``, `` and ``.
* Interpreter playtime
The Basics of Basics about Unicode
----------------------------------
* The times of "plain text" are long gone. Without knowing the
encoding of a text file, you can't possibly know which characters
are in it.
* Unicode defines several thousand characters and assigns a number
("code point") to each character. This is an abstract value and
says nothing about the bytes used to store the character.
* To physically store or transfer characters, you have to "encode"
them to a byte string. Common encodings are UTF-8, ISO-8859-1
(Latin 1), ISO-8859-15 (Latin 9) and CP-1252 (on Windows).
* Thus: unicode --- encode ---> bytes
bytes --- decode ---> unicode
* Recommended links:
-
-
Unicode Strings
---------------
* The strings discussed so far were byte strings (type ``),
sequences of bytes.
* In Python, there are also unicode strings (type ``).
* To write a unicode literal, prepend the leading quote character
with a ``:
* If an expression contains both byte strings *and* unicode strings,
byte strings are implicitly converted to unicode strings.
* If you want to use unicode literals in Python source code (e. g. for
the name of a person), you have to put a special comment in the
first two lines of the file. Example:
If there's no such encoding comment, ASCII is assumed. In this case,
you aren't allowed to use any non-ASCII characters in the file.
* *Remark* Python 3 always uses unicode for character strings and
UTF-8 as default encoding for Python source code.
Byte Strings and Unicode Strings (Again)
----------------------------------------
* Accessing single characters
* Strings are "immutable":
* Ranges of characters can be accessed with "slices":
* Slices allow a step as a third value:
* Playtime. Suggestions:
Lists
-----
* Lists can contain any number (including 0) of objects.
* You can access individual elements in a list via indices.
Since lists are mutable, you also can modify its contents.
This isn't possible with strings.
* Slices work as with strings:
* Use the `` and `` methods to add elements to a list:
* `` allows to insert elements "in the middle":
* Lists are equal if they contain the same elements in the same order.
* Playtime. What happens here?
Tuples
------
* Tupels are very much like lists, but are immutable.
* Empty and single-element tuples:
* "Tuple unpacking" is often used, either explicit or implicit.
It also works with lists on the right hand side.
Dictionaries
------------
* Dictionaries contain key/value pairs.
The pairs have *no* guaranteed order!
* Every key can only exist once in a dictionary. If you assign to the
key again, the old value is overwritten with the new one.
* An assignment to a key which didn't exist before creates a new
dictionary entry (key/value pair).
* Keys must be immutable.
* Dictionaries are equal if they contain the same key/value pairs.
Note that "same" here means that the keys or values compare as
equal.
Sets
----
* Sets are similar to dictionaries.
* Sets contain only values, no key/value pairs.
* There's *no* guaranteed order.
* Contained elements must be immutable.
* Sets can be used for set operations. Example: Which values are in
set 1, but *not* in set 2?
Which values are in set 1 *and* set 2?
Names and Assignment
--------------------
* *Python does *not* copy (only if requested explicitly)!
* An assignment assigns a name (left) to an object (right).
* Tip: The `` operator tells if two objects are *identical*, not
just if their values compare equal.
* The following code is legal (but not recommended):
Each of these assignments connects an object of a different type
with the same name. The previously assigned object is discarded if
it's not used anywhere else.
Names and Assignment - Immutable Objects
----------------------------------------
* Assignments
* After the first assignment:
x ---> 1.0
* After the second assignment:
x ---+
+---> 1.0
y ---+
* After the third assignment:
x ---> 1.0 (the object created first)
y ---> 1.0 (the object created in the third line)
Names and Assignment - Mutable Objects
--------------------------------------
* What happens here?
* After the first assignment, `` is a name referring to the list
`` *which is created before the assignment*.
L1 ---> [1, 2]
* After the second assignment, the *single* list object is known under
two names, `` and ``.
L1 ---+
+---> [1, 2]
L2 ---+
* The `` call modifies this single list.
* This "anomaly" isn't possible for immutable objects (like numbers or
strings). After all, by definition, you can't modify them.
* Playtime. What happens here?
String Methods
--------------
* Some useful methods:
* Other useful operations on strings:
String Formatting
-----------------
* Strings can be combined with each other and with other
objects in rather flexible ways.
* Syntax: ``
* Examples:
* Variant: named placeholders and a dictionary
See
List Methods
------------
* Already seen: `` and ``
* ``: everything you can iterate over. This will be explained
in more detail later. In ``, the `` is usually a list.
* `` sorts a list "in place", i. e. the list itself is modified.
The result (return value) is the special value ``.
`` takes an optional argument ``. This is a function which is
applied to all list elements. The list elements are sorted according
to these function results. The list elements themselves don't change.
* `` reverses the list order in-place and returns ``.
* `` returns the index of the first element which has the
value ``.
* Also useful:
*Beware*: When "multiplying" a list with an integer, the list is
*not* copied. This means the elements of the resulting list are the
same object.
* Interpreter playtime
Tuple Methods
-------------
Tuples have some of the methods of lists, but no methods that can
change the tuple. After all, tuples are immutable.
Dictionary Methods
------------------
* `` returns a list of all dictionary keys, ``
the values and `` a list of `` pairs. The orders of
the methods' results are consistent *as long as the dictionary is
not modified between the calls*.
* `` returns the value for key `` if it's in the
dictionary, otherwise the method returns ``. The second
argument is optional; in this case the default is ``.
* `` is very similar to ``, but if the
key doesn't exist yet, the default is inserted in the dictionary
as this key's value. Again, the `` argument is optional.
* `` updates the dictionary `` with the
key/value pairs of ``. If a key exists in both dictionaries,
the value from the second dictionary is used.
* Also useful:
Exercise
--------
What are the contents of `` after running the following code?
Code Blocks
-----------
* Code blocks are *not* wrapped in `` or ``.
* Code blocks are created by indenting all statements in them by the
same amount of spaces. Example:
Note on ``: It's recommended not to introduce a name which is
also the name of a built-in.
* The Python Style Guide (PEP 8) requires *four* *spaces* per
indentation level.
* Most publicly available Python code is formatted according to this
convention.
* Most programming editors automatically adapt their settings
accordingly when they "notice" that a Python file is edited.
Often, pressing the tab key then inserts four spaces, not a tab
character.
* If your editor of choice doesn't make these changes automatically,
configure it so that it does. :-)
Conditional Statements
----------------------
* The structure of the `` statement is
* The `` and `` branches are optional. `` without
`` is also possible.
* The condition expressions don't need to be written in brackets.
* After each condition and after `` follows a colon.
* The condition expressions don't have to evaluate to a boolean
value.
Boolean Values
--------------
* Not only `` and `` are usable as results of a condition
expression.
* In Python, the following expressions are considered false:
- ``
- ``
- all values with the numerical value 0: 0 0.0 0+0j
- empty strings: "" u""
- empty containers: [] () {} set() frozenset()
- for completeness:
- objects of user-defined classes which define the ``
method and return `` from it.
- objects of user-defined classes which define ``, but
not `` and calling `` returns 0.
* All other values are considered true.
* If you're unsure, check with ``:
Statements Spanning More Than One Line
--------------------------------------
* "Usually" a Python statement ends at the end of the line.
* Exceptions:
- The line ends with a backslash `` (which is not part of a
comment).
- At the end of a line there are still "open brackets".
* Examples:
Loops
-----
* `` loops
Write colons after the condition and ``.
The `` branch is optional and is rarely used.
* You can skip an iteration with the `` statement. When
`` is executed, the condition at the top of the loop is
evaluated again.
* You can leave a loop with the `` statement.
* If you have nested loops (`` and `` loops), `` and
`` refer to the innermost loop that contains these statements.
* `` loop:
Use colons after the iterable and the ``.
Again, the `` part is optional and rarely seen.
* The `` can be a tuple. In this case, each element of the
iterable is "unpacked" so that it can be assigned to the names
after the ``.
* If you use ``, the loop continues with the next element
of the iterable.
* Because the `` loop is so flexible, you seldem need to work
with indices. If you *do* need indices, for example to overwrite
list elements, use the `` function:
* Loops also come in the form of expressions, so-called "list
comprehensions". This example creates a list of the squares
of all even numbers between 0 and 10:
You can nest `` and `` fragments in list comprehensions.
However, a good rule of thumb is to limit this to
- one `` and one `` fragment or
- two `` fragments.
Otherwise, better use explicit `` and `` statements, or your
code will be difficult to understand for others (and maybe for
you as well a few months later ;-) ).
Exercise
--------
Write a script to calculate the factorial of a number. The argument
should be passed in via the command line.
Factorial `` definition:
n! = 1 * 2 * 3 * n
0! = 1
The factorial function is undefined for negative values, so you
should check for this error condition.
Tip: You can get the first command line argument as an integer
with
Here's a possible solution. I use `` as a constant because I can't
use command line arguments with the editor invocation trick.
With small "optimizations":
Functions
---------
* Syntax
* Probably the simplest function:
* With one argument:
* With two arguments, one of them a default argument:
* The argument list can have an arbitrary number of arguments.
* Default arguments have to go at the end, so this is *invalid*:
* Default are evaluated *only once* - when the function is defined!
* The `` statement returns a value from the function. The return
value can be a tuple. This way, you basically can return multiple
values.
* A function can have more than one `` statement. They can return
values of different types, but usually it's better not to do this.
* If there's no `` statement or it doesn't have a value, the
returned value is ``. However, it's probably better style to
express your intention by writing ``.
* If you use names in the call, the order of the arguments can be
different from the order in the function definition. Example:
* A string immediately after the `` line is a "docstring" and can
be accessed programmatically.
* With the syntax `` and `` it's possible to pass
arbitrary positional and keyword arguments.
Exercise
--------
Write a function to calculate a factorial. The function should accept
an optional string argument which is the error text shown if the
argument is less than zero.
Exception Handling
------------------
* To write sensible programs, you need one more feature: exception
handling.
* Without exception handling, this code would abort the program.
* Syntax for exception handling:
* Syntactically, the part `` is optional. You'll
need it if you want to access attributes of the concrete exception
object. For more on exception classes and objects see below.
* There must be at least one `` block. There can be as many as
you like.
* The `` branch is optional. It's executed if *none* of the error
conditions applies.
* Example:
* Unconditional execution: With ``, a code block is
executed in any case, i. e. regardless whether there's an exception
or not.
* Example:
* To re-raise an exception after some error handling, use ``:
* You can also raise exceptions yourself:
* You can combine `` and `` like this:
* There's also
This catches (almost) all errors - including some you probably don't
want to catch. ;-)
*This hides a `NameError` exception!*
Exercise
--------
Rewrite the factorial function so that it uses exception handling.
In case of an invalid argument, a `` should be raised.
(I'll mention a better approach below.)
Custom Exception Classes
------------------------
* Normally you define custom exception classes so that another
user of the code can handle them specially. Imagine everyone
raised ``s everywhere. You wouldn't be able to tell
which `` means what.
* Recipe for your own exception class:
* Use like:
A caller could then react:
Modules
-------
* Modules are files containing Python code.
* The "normal" Python distribution contains several hundred modules.
Many more are contained in the scientific Python distributions
and in the Python Package Index (PyPI).
* A file ending in `` can be used both as a module and as a
standalone program.
* Modules are loaded with the `` statement. You can access the
names in the module with ``.
* Of course, there are usually other things in a module than just
constants.
* `` variations:
This saves a bit typing, but isn't recommended: The previously
described form is better in that it shows the module each name comes
from.
* There's also ``. This is even worse. Better
use it only for shortcuts in Python's interactive mode.
* Modules can only be imported, if they
- are in the same directory as the importing module, or
- are in one of the directories in Python's module search path
(``, can be extended with the `` environment
variable).
* Many Python programs have the code
at the end. Every module has a `` attribute. If a module is
imported, `` refers to the name of the module. If the file
is executed as a Python program, the name is "__main__". So the same
file can be imported as a module (without running ``) or
be run as a script.
* As an extension of the module concept, there are "packages". Usually
a package is a directory with a file `` in it (see above).
Modules from the package can be imported like this:
* If you have more than one package containing a module with the
same name, you can rename the modules to avoid naming conflicts.
* *Beware!* Make sure you do *not* import the same module from
different directories in ``. This can lead to strange bugs.
Example:
Exercise
--------
Move the factorial function into a module. Write another Python module
which imports the factorial module and uses the function.
Important Modules
-----------------
* A list of the modules of a standard Python installation is at
.
The modules `` and `` are used in almost every program.
The remaining listed modules are sorted alphabetically.
* ``: system informationen, for example ``, ``,
``
* ``: various file and process operations, for example, ``
returns a list of directory and file names in a directory.
``: file operations, for example
`` -> ``
with the appropriate separators. `` is available as soon as
you import ``, so the latter is enough.
* ``: simple tools for web interfaces. There are _lots_ of web
frameworks, but still, `` provides some helpers like ``
to convert HTML special characters to their entity form ("<" ->
"<" etc.)
* ``: read and write ini style configuration files
* ``: support for comma separated values files
* ``: parse and create e-mails, including support for attachments
* ``, ``: filter directory or file names by pattern
* ``, ``, ``, ``, ``: archive file support
* ``: very flexible logging framework
* ``, ``: mathematical operations
* ``: functions equivalent to operators; useful for list
comprehensions and callback functions
* ``, ``: persistence for Python objects
* ``: profiler for runtime analysis
* ``: random numbers
* ``: regular expressions (see example ``)
* ``: high-level directory/file operations
* ``: provide strings with a file interface
* ``: call external programs, including redirection of
standard input, output, error
* ``, ``, ``: date/time operations
* ``, ``: support for concurrency on
thread and process level, respectively. I guess you'll hear
a lot about concurrency at this conference. :-)
* ``, ``: frameworks for automated tests
* ``: different XML parsers; `` is the easiest one most
of the time
Built-in Functions
------------------
* Apart from the functions and classes defined in modules, Python
contains quite a few built-in functions that can be accessed without
importing anything.
* ``, ``, ``, `` and ``, to "convert"
objects to the respective type. (The original objects actually
aren't changed.)
`` is also implicitly called by the `` statement and when
using `` in format strings.
`` can also convert to the `` type. (Actually, the difference
between `` and `` rarely matters because the two are
converted to each other on the fly when necessary.)
Besides `` and ``, `` also creates `` objects.
Contrary to the result of ``, `` creates rather low-level
representations more useful for debugging.
* `` returns a list of numerical values. The function takes up to
three parameters. More information is at
.
* `` accepts the same arguments, but returns an `` object
which doesn't calculate a list in advance. `` is mostly used
in loops.
* `` returns the length of its argument. _For example_, this works
for strings, lists and dictionaries (where the "length" is the
number of key/value pairs).
* `` opens a file. `` is the file name (possibly
with a directory part); `` is a mode like
- ``, the default, stands for reading, `` for writing and ``
for appending.
- A `` after one of the previous letters opens the file in "binary
mode". Use this when you process binary data like image files.
* ``, applied to an iterable, returns a sorted list from the
iterable. The argument is *not* modified. Like the `` method
of lists, `` can take a `` argument.
* ``, `` and `` are used to read, write and delete
attributes of objects. `` checks if an object has an attribute.
Interesting is that the names of the attributes are passed in as
strings, so these functions can work on *calculated* attribute
names.
* `` returns a dictionary with the names and values of the
top-level module namespace.
* `` works similarly. It returns a dictionary for the local
names and values (for example, within a function).
Note: While you can modify `` to change the actual module
globals, this doesn't work with ``.
* `` pair-wise combines two or more iterables. See
.
* `` reads a string from standard input (stdin).
* `` calculates the absolute value of its argument.
* ``, `` and `` calculate the maximum, minimum and sum,
respectively, of their argument. Many more mathematical operations
are in the `` and `` modules (see above).
* More built-in functions are described under
.
* Playtime
Name Lookup
-----------
* When you use a name in the code, Python tries to find the name
and the associated object in the following order. If the name is
found, the latter locations aren't tried.
- L - local (for example, in a function which contains the name)
- E - enclosing (in "enclosing" functions/methods; you can nest
functions!)
- G - global (in the module-global namespace)
- B - built-in (in the builtin namespace)
* An example:
* If you want to access a module-global name from inside a function,
you need to use the `` statement (not to be confused with
the `` built-in function).
File Objects
------------
* File objects are created with the `` function (see above).
The following are the (in my opinion) most important methods of
file objects.
* `` and `` normally aren't used directly, but they're
used implicitly to iterate over the lines of a file:
Note: A shorter and more modern way to write the above code is
* `` closes a file. Note that you need to write ``; you
have to call functions explicitly in Python.
* `` reads all lines of the file into a list. The strings
in the list contain a line ending character (``).
* `` without an argument reads the "rest" of the file and returns
a corresponding string. With an argument, it reads *at most* as many
bytes.
* `` writes a string object into the file. This works only if the
file had been opened for writing (modes `` or ``).
* `` is the "opposite" operation of `` in that
it writes a list of strings into a file. Despite the name of the
method, you have to provide the line break characters yourself in
the strings.
Exercise
--------
Extend the outcome of the previous exercise by reading the arguments
line by line from a file. Write the results to another file.
So, if the input file looks like
you should generate a file containing
A possible solution:
In Python 2.7, you can combine the `` statements like this:
Object-Oriented Programming (OOP)
---------------------------------
* Overview: Who in this room has developed object-oriented software?
(For the purpose of this question, I don't only mean using
classes but implementing them yourself.)
* Object-orientation is easier to show with an example than to
describe. Nevertheless, here's an attempt.
* Objects are a tool for software design. Objects represent "things".
* Objects have "attributes", which represent the current state of an
object. Objects usually also have "methods", which change or query
the state of the object.
* In most object-oriented languages, as in Python, objects are
created from a template, a "class".
* Example:
Some important points ...
* In contrast to the usual OOP terminology, methods in Python are also
attributes, only just callable ones.
* All attributes are accessible and changeable. There are no
"protected" or "private" attributes, only conventions (for example,
prepending an "internal" attribute name with "_").
*Note* That something is *possible* doesn't necessarily mean it
should be done. :-) Also, it's rather the exception to replace
methods in Python programs at runtime. More common, however, is the
addition of non-callable attributes like numbers, strings or lists.
* Every method defined in a class has `` as its first argument
(with the exception of "class methods" and "static methods"). When
the method is called, `` is the class instance.
* Like in other object-oriented languages you can use inheritance,
that is, you create a "derived class" from a "base class" and add
attributes (callable or not). Example:
* Inheritance should only be used if the objects of the derived class
conceptually are also objects of the base class. For example,
talking animals aside ;-) , ``s are always ``s.
In other words, you should *not* inherit from a class just to be
able to access the base class attributes. In that case, it's better
to use "aggregation". That is, the new class gets an object of the
existing class as an attribute.
Example:
Special Methods
---------------
* As already shown, classes can have special methods like ``
and `` that influence the behavior of certain statements and
functions in Python. Here are some more examples:
* `` defines ``.
* `` defines ``.
* ``, `` and `` influence
* ``, ``, `` control indexing
operations.
* `` defines ``.
* `` is called implictly by the `` builtin function.
It's also used when a format string contains a `` placeholder.
* `` is called when applying the `` builtin function
to the object.
* `` is called when an object is destroyed by Python's garbage
collector.
* ``, `` etc. control the result of comparison operators
(here `` and ``).
* ``, `` and many more control mathematical operators
like `` and ``.
* `` controls how an object is converted to a ``
object, for example, for use in `` and `` conditions.
* An extensive list is at
.
Exercise
--------
Derive from the `` class and add a method ``. This method is
supposed to set an instance variable ``. The output of ``
should contain the current speed of the person.
Test the class with the following code:
One possibility:
Exercise
--------
Use the module `` to fetch any HTML page you want. Then use the
`` module oder string operations to find and print the links on the
page line by line. If you're unfamiliar with regular expressions, the
code in `` might help.
For this exercise, it's unimportant whether the links occur in HTML
`` tags or not.
Use functions, classes and/or methods to structure the code so that
it's easy to understand.
Here are a few links to help you:
* ``:
* ``:
* valid characters in URLs:
To simplify things a bit, assume that a link, after the leading
" contains only the following characters:
- Uppercase and lowercase letters from the ASCII characters
- Digits
- ``
*Optional* enhancements to make the exercise more interesting:
* Sort the URLs alphabetically before printing them.
* Remove duplicate URLs, so no link is printed twice.
* Pass in the starting URL per command line.
A possible solution:
In practice you won't use so many small functions. The shown approach
only should give you an idea what functions could be extracted.
Python "Philosophy"
-------------------
* Get some tips with
* EAFP instead of LBYL (EAFP = "it's easier to ask for forgiveness
than permission", LBYL = "look before you leap")
Example:
* Duck Typing ("If it walks like a duck, swims like a duck and quacks
like a duck, it must be a duck.")
This means that two objects with similar interfaces don't need to
be objects of classes derived from the same base class. Here's an
example:
First a "Java-like" approach:
Python-typical (Duck Typing):
A well-known example in the Python standard library are the classes
`` and ``. These have much in common, but don't derive
from the same base class (if you don't count ``).
Outlook
-------
Some topics not discussed in this tutorial:
* Multiple inheritance and mixins
-
* Generators and generator expressions
-
-
* Decorators
-
-
-
* Properties
-
-
* Metaclasses (rarely used in production code)
-
-
* Moreover
- Descriptors
- Coroutines
Appendix: Execute Code Snippets from GVim
-----------------------------------------
* The following macro reaches from the `` to the `` (so it
contains two empty lines at the end).
* Select the this area and press `` to save the text as macro "e".
* If
- `` is in the current directory,
- `` is installed and
- it has a profile "Talk",
you can execute a snippet by pressing `` when the cursor is
between the corresponding `` and ``.
If you don't have `` and/or a `` profile, you can
edit `` to match your environment.