PYTHON TUTORIALS

From WikiEducator
Jump to: navigation, search

Welcome!

Welkom! Maligayang Pagdating! مرحبا! Добро пожаловать! Bienvenido!

Python It is an easy to learn, powerful programming language. It has efficient high-level data structures and a simple but effective approach to object-oriented programming.
The Python interpreter and the extensive standard library are freely available in source or binary form for all major platforms from the Python Web site.
Please feel free to develop Python tutorials on WikiEducator and link to them from here. External links are likewise encouraged.

Python-logo.gif





Scientific Python

Python allows you to split your program in modules that can be reused in other Python programs. It comes with a large collection of standard modules that you can use as the basis of your programs. Python is an interpreted language, which can save you considerable time during program development because no compilation and linking is necessary. It is also a handy desk calculator.
Python programs tend to to be compact and readable (pithy). Python programs are typically much shorter than their equivalent C or C++ programs.
In Python, many data types are built in. Declaration of variable types prior to assignment is not required and memory management is automatic i.e. objects without referents will be periodically garbage collected, freeing up memory for reallocation.

Scipy-logo.gif



Icon inter.gif

Web Resources

Third Party Libraries



Overview

Variables

A variable is a name bound to an object in memory. This object may change during the execution of the program, although some types of object are defined as immutable.

The value of a variable (or name) may be a string object (‘hello’), an integer object (45), a floating point object (56.7), or something more complicated, such as a built in data structure or some user defined type.

Many names may bind to the same object and the assignment operation "a = b" does not force an object to be copied. Rather, the name "a" now points to (names) the same object as "b" does. Not every computer language behaves in this manner.

Data Structures

If primitive number and string objects are the "atoms" in Python, then data structures are the "molecules". Most data structures are collections in the sense that they aggregate objects and provide means for storing, retrieving, sorting their contents. The most commonly used data structures include the dictionary, list and tuple. The queue, set, array (in numpy) and several others are likewise easy to come by. Note that a string is actually an immutable collection type, and so may be classified as a data structure if one prefers.

Functions

Functions consume arguments, process them internally, and return results. They have much in common with what, in other languages, are known as subprocedures or subroutines. They're also close relatives of the mathematical idea of "a function" but without the same restrictions on domain and range, although a function producing different outputs from the same inputs would be considered working off "side effects" and might indicate a need to rework the design.

Generators

Python Generator

Generators are akin to functions but remember state between invocations. The keyword yield is used in place of return, and infinite loops, usually discouraged in programming, make plenty of sense in a generator as often the job is simply to evaluate a next cycle, as many times as called.

The example at right shows a generator for the Fibonacci Sequence, which advances by summing the previous two terms, typically initialized to 0, 1 (the default) or 1, 1 although any pair might be used. After a generator is defined, it must be called with whatever initial arguments (in this case optional, as defaults have been set). The returned object is an iterator, meaning it supports iteration by means of the built-in next function.

With each feeding of the generator to the next function, it cycles through a next loop, updating values for a and b. The yield statement marks the pause point, where the flow of execution returns to the calling scope.

Notice in the last line evaluated, list comprehension syntax is used, meaning the expression inside the square brackets results in the successive members of the resulting list.

Generators have many advanced uses in that they implement what is called "lazy evaluation" making them economical for multi-tasking. Switching between generators provides a program with asynchronous thread-like behavior. The send function also makes it possible to update a generator by sending new values in through a yield expression (not shown).

Generators need not be written as infinite loops. Some exhaust themselves naturally.

In the examples below, the built-in next function is bound to the name kick, whereas each generator gets bound to the name can upon initialization. Kicking the can down the road then becomes our metaphor for lazy evaluation. In other words, this is idiosyncratic Python designed to reinforce the imagery around iterating over an iterable, an object supporting a particular interface (as we say in Java) or API.



Icon reading.jpg

Reading

Example Sequence Generators (click tiles for larger view)
  • Tetrahedral Numbers

Tetrahedral Numbers OEIS A000292

def tetra():
    n, total = 0, 0
    while True:
        n += 1
        layer = n * (n + 1)//2
        total += layer
        yield (layer, total)
  • Half-Octahedral (Pyramidal) Numbers

Half-Octahedral Numbers OEIS A000330

def hocta():
    n, total = 0, 0
    while True:
        n += 1
        layer = n ** 2
        total += layer
        yield (layer, total)
  • Crystal Ball Sequence

(Icosahedral) Numbers OEIS A005902

def cubocta():
    layer, total = 1, 1
    n = 0
    while True:
        yield (layer, total)
        n += 1
        layer = 10 * n * n + 2
        total += layer
  • Pascal's Triangle

Pascal's Triangle OEIS A007318

def pascal():
    row = [1]
    while True:
        yield row
        row = [i + j for i,j in zip(row + [0], [0] + row)]




Classes

Python Class

Python's many native types of object, including primitive number types and data structures, comprise a set of built in classes available right out of the box. However, many programs will extend a namespace (a module) with additional types.

A class definition provides a shared blueprint for all objects constructed from it. This blueprint defines the attributes and methods associated with that type. For example, a list has a sort method, whereas a string type has methods for converting lowercase to uppercase the vice versa.

The example at right provides a blueprint for pythons imagined as snakes with stomachs. The stomach starts empty at the time of birth, as defined by __init__ (short for initialize), also known as the constructor. The Python blueprint may be used to give birth to (instantiate) any number of snake objects, each with its own stomach and place in computer memory.

Characteristic of Python's look and feel are the large number of "special names" with double underlines on both sides. In the code at right, __init__ and __repr__ are two examples. The __repr__ method is short for "representation" and determines what string will be displayed whenever a snake object is expected to represent itself. In the interactive Python shell, simply entering the name of an object and hitting return triggers its __repr__ method. As a mnemonic, you might think of these special names as __ribs__, what snakes are known for having in some abundance.

Note that the initial argument to Python methods is typically self. This is not a keyword, meaning other names might be used in this same position (although in practice this has been discouraged). The variable in this first position anchors the object or instance to its own private dictionary (obj.__dict__), is basically a pointer to the instance itself, not to its blueprint (the class) and not to whatever ancestor classes (Python supports multiple inheritance).

In passing values to methods, one does not map to the self argument (i.e. the first one), as this is considered "for internal use only". For example, in passing a food to the eat method, only one value is supplied.

Of course most pythons can't really swallow whole ponies, might at most swallow whole sheep, but in the Pythonic subculture (which inherits from the Netherlands as well as Monty Python's Flying Circus), one has reason to think of both ponies and spam as vital food stuffs.

What goes in must come out, and the poop method, in using the pop method internally (pop is native to any list) turns our snake's stomach into a FIFO queue, meaning a "first in first out" pipeline (as opposed to LIFO or "last in first out" -- more stack-like behavior).

Python encourages an "object oriented" way of modeling a knowledge domain, meaning that problem solvers are encouraged to analyze a situation into a number of objects all interacting with one another. This style of thinking got off the ground with a language called Smalltalk and has been quite influential ever since. Java, JavaScript, C#, Ruby and Ocaml are additional examples of object oriented languages. One might also argue this is a prehistoric way of thinking and has nothing to do with computer languages, which is why it comes naturally.