If you prefer to execute it by its name,
instead of as an
argument to the Python interpreter, put a "bang" line at
the top. Include the following on the first line of the program,
substituting the absolute path to the Python interpreter for
/'path/to/python': #!/path/to/python
3.
Fundamental Data Types and
Assignment Operators:
TYPE
|
DESCRIPTION
|
SYNTAX
EXAMPLE
|
str,
unicode |
An
immutable sequence of characters |
'Wikipedia',
u'Wikipedia' |
list |
Mutable,
can contain mixed types |
[4.0,
'string', True] |
set, frozenset |
Unordered,
contains no
duplicates |
set([4.0,
'string', True])
frozenset([4.0, 'string', True]) |
int |
A
fixed precision
number (may be transparently expanded to long, which is of
unlimited length) |
42
2147483648L |
float |
Floating
point |
3.1415927 |
complex |
A
complex
number with real number and imaginary
unit |
3+2j |
bool |
Boolean |
True
or False |
Python also allows
programmers to define their own types. This is in
the form of classes, most often used for an object-oriented style of
programming.
4. Basic
Control Flow (conditional and
loop statements):
4.1 if Statements
Perhaps the most well-known statement type is the
if statement. For example:
>>>
x = int(raw_input("Please enter an integer: "))
>>> if x < 0:
...
x = 0
...
print 'Negative changed to zero'
... elif x == 0:
...
print 'Zero'
... elif x == 1:
...
print 'Single'
... else:
...
print 'More'
...
There can be zero or more
elif
parts, and the
else part is
optional. The keyword
`elif'
is short for `else if', and is useful to avoid excessive indentation.
An
if ... elif ... elif ...
sequence is a substitute for the switch or case statements found in
other languages.
4.2 for Statements
The for statement in Python differs a bit from what you may be used to
in C or Pascal. Rather than always iterating over an arithmetic
progression of numbers (like in Pascal), or giving the user the ability
to define both the iteration step and halting condition (as C),
Python's
for statement
iterates over the items of any sequence (a list or a string), in the
order that they appear in the sequence. For example (no pun intended):
>>>
# Measure some strings:
... a = ['cat', 'window',
'defenestrate']
>>> for x in a:
...
print x, len(x)
...
cat 3
window 6
defenestrate 12
It is not safe to modify the sequence being iterated over in the loop
(this can only happen for mutable sequence types, such as lists). If
you need to modify the list you are iterating over (for example, to
duplicate selected items) you must iterate over a copy. The slice
notation makes this particularly convenient:
>>> for x in a[:]: # make a slice copy of the entire list
... if len(x)
> 6: a.insert(0, x)
...
>>> a
['defenestrate', 'cat',
'window', 'defenestrate']
4.3 The range() Function
If you do need to iterate over a sequence of numbers, the built-in
function
range() comes in
handy. It generates lists containing arithmetic progressions:
>>>
range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
The given end point is never part of the generated list; range(10)
generates a list of 10 values, the legal indices for items of a
sequence of length 10. It is possible to let the range start at another
number, or to specify a different increment (even negative; sometimes
this is called the `step'):
>>>
range(5, 10)
[5, 6, 7, 8, 9]
>>> range(0, 10, 3)
[0, 3, 6, 9]
>>> range(-10, -100,
-30)
[-10, -40, -70]
To iterate over the indices of a sequence, combine range() and len() as
follows:
>>> a = ['Mary', 'had', 'a',
'little', 'lamb']
>>> for i in
range(len(a)):
...
print i, a[i]
...
0 Mary
1 had
2 a
3 little
4 lamb
4.4 break and continue
Statements, and else Clauses on Loops
The
break statement, like in
C, breaks out of the smallest enclosing
for or
while loop.
The
continue statement, also
borrowed from C, continues with the next iteration of the loop.
Loop statements may have an
else clause;
it is executed when the loop terminates through exhaustion of the list
(with
for) or when the
condition becomes false (with
while),
but not when the loop is terminated by a
break statement. This is
exemplified by the following loop, which searches for prime numbers:
>>>
for n in range(2, 10):
... for
x in range(2, n):
...
if n % x == 0:
...
print n, 'equals', x, '*', n/x
...
break
... else:
...
# loop fell through without finding a factor
...
print n, 'is a prime number'
...
2 is a prime number
3 is a prime number
4 equals 2 * 2
5 is a prime number
6 equals 2 * 3
7 is a prime number
8 equals 2 * 4
9 equals 3 * 3
4.5 pass Statements
The pass statement does nothing. It can be used when a statement is
required syntactically but the program requires no action. For example:
>>>
while True:
...
pass # Busy-wait for keyboard interrupt
...
5. Functions - syntax, writing and using
functions, example:
Functions in
Phyton are values (like integers in C).They are simply values and can
be passed to other functions/object constructors, and so forth.
We
can create a function that writes the Fibonacci series to an arbitrary
boundary:
>>>
def fib(n): # write Fibonacci series up to n
...
"""Print a Fibonacci series up to n."""
... a, b
= 0, 1
...
while b < n:
...
print b,
...
a, b = b, a+b
...
>>> # Now call the
function we just defined:
... fib(2000)
1 1 2 3 5 8 13 21 34 55 89 144
233 377 610 987 1597
The keyword def introduces a function definition. It must be followed by
the function name and the parenthesized list of formal parameters. The
statements that form the body of the function start at the next line,
and must be indented. The first statement of the function body can
optionally be a string literal; this string literal is the function's
documentation string, or docstring.
The execution of a function
introduces a new symbol table used for the local variables of the
function. More precisely, all variable assignments in a function store
the value in the local symbol table; whereas variable references first
look in the local symbol table, then in the global symbol table, and then in
the table of built-in names. Thus, global variables cannot be directly
assigned a value within a function (unless named in a global
statement), although they may be referenced.
A function that returns a list of the numbers of the Fibonacci series,
instead of printing it:
>>> def fib2(n): # return Fibonacci series up to n
...
"""Return a list containing the Fibonacci series up to n."""
...
result = []
... a, b
= 0, 1
...
while b < n:
...
result.append(b) # see below
...
a, b = b, a+b
...
return result
...
>>> f100 =
fib2(100) # call it
>>>
f100
# write the result
[1, 1, 2, 3, 5, 8, 13, 21, 34,
55, 89]
Functions can also be called using
keyword arguments of the form "keyword
= value". For instance, the following function:
def
parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
print "--
This parrot wouldn't", action,
print "if you
put", voltage, "volts through it."
print "--
Lovely plumage, the", type
print "--
It's", state, "!"
could be called in any of the following
ways:
parrot(1000)
parrot(action = 'VOOOOOM',
voltage = 1000000)
parrot('a thousand', state =
'pushing up the daisies')
parrot('a million', 'bereft of
life', 'jump')
Lambda Forms
With the
lambda keyword,
small anonymous functions can be created. Here's a function that
returns the sum of its two arguments:
"lambda a, b: a+b".
Lambda forms
can be used wherever function objects are required. They are
syntactically restricted to a single expression. Semantically, they are
just syntactic sugar for a normal function definition. Like nested
function definitions, lambda forms can reference variables from the
containing scope:
>>>
def make_incrementor(n):
...
return lambda x: x + n
...
>>> f =
make_incrementor(42)
>>> f(0)
42
>>> f(1)
43
Here
are some more functions using in Pyhton programming language:
append(
x) - Add an item
to
the end of the list; equivalent to a[len(a):] = [x].
extend( L)
- Extend the list
by appending all the items in the given list; equivalent to a[len(a):]
= L.
insert( i,
x) - Insert an
item at
a given position. The first argument is the index of the element before
which to insert, so a.insert(0, x) inserts at the front of the list,
and a.insert(len(a), x) is equivalent to a.append(x).
remove( x)
- Remove the first
item from the list whose value is x. It is an error if there is no such
item.
pop( [i])
- Remove the item
at the given position in the list, and return it. If no index is
specified, a.pop() removes and returns the last item in the list. (The
square brackets around the i in the method signature denote that the
parameter is optional, not that you should type square brackets at that
position. You will see this notation frequently in the Python Library
Reference.)
index( x) - Return the index
in the list of the first item whose value is x. It is an error if there
is no such item.
count( x) - Return the number
of times x appears in the list.
sort( ) - Sort the items of
the list, in place.
reverse( ) - Reverse the
elements of the list, in place.
6. Arrays - syntax, definition, example:
This
module defines an object type which can efficiently represent an array
of basic values: characters, integers, floating point numbers. Arrays
are sequence types and behave very much like lists, except that the
type of objects stored in them is constrained. The type is specified at
object creation time by using a type code, which is a single character.
The following type codes are defined:
array(
typecode[, initializer]) - Return a new
array whose items are
restricted by
typecode, and initialized from the optional initializer value, which
must be a list, string, or iterable over elements of the appropriate
type. Changed in version 2.4: Formerly, only lists or strings were
accepted. If given a list or string, the initializer is passed to the
new array's
fromlist(), fromstring(),
or
fromunicode() method
(see
below) to add initial items to the array. Otherwise, the iterable
initializer is passed to the
extend()
method.
6.1 ArrayType - Obsolete alias for
array.
Array objects support the ordinary
sequence operations of indexing,
slicing, concatenation, and multiplication. When using slice
assignment, the assigned value must be an array object with the same
type code; in all other cases, TypeError is raised. Array objects also
implement the buffer interface, and may be used wherever buffer objects
are supported.
- The following data items and methods are
also supported:
FUNCTION
|
DESCRIPTION
|
typecode |
The typecode character used to create the
array. |
itemsize |
The length in bytes of one array item in
the
internal representation. |
append(
x) |
Append a new item with value x to the end
of
the
array. |
buffer_info(
) |
Return a tuple (address, length) giving
the
current
memory address and the length in elements of the buffer used to hold
array's contents. |
byteswap(
) |
``Byteswap'' all items of the array. This
is
only
supported for values which are 1, 2, 4, or 8 bytes in size; for other
types of values, RuntimeError is raised. It is useful when reading data
from a file written on a machine with a different byte order. |
count(
x) |
Return the number of occurrences of x in
the array. |
extend(
iterable) |
Append items from iterable to the end of
the array.
If iterable is another array, it must have exactly the same type code;
if not, TypeError will be raised. If iterable is not an array, it must
be iterable and its elements must be the right type to be appended to
the array. Changed in version 2.4: Formerly, the argument could only be
another array. |
fromfile(
f, n) |
Read n items (as machine values) from the
file
object f and append them to the end of the array. If less than n items
are available, EOFError is raised, but the items that were available
are still inserted into the array. f must be a real built-in file
object; something else with a read() method won't do. |
fromlist(
list) |
Append items from the
list. This is equivalent to
"for x in list: a.append(x)"except that if there is a type error, the
array is unchanged. |
fromstring(
s)
|
Appends items from the string,
interpreting the
string as an array of machine values (as if it had been read from a
file using the fromfile() method). |
fromunicode(
s) |
Extends this array with data from the
given
unicode
string. The array must be a type 'u' array; otherwise a ValueError is
raised. Use "array.fromstring(ustr.decode(enc))" to append Unicode data
to an array of some other type. |
index(
x) |
Return the smallest i such that i is the
index of
the first occurrence of x in the array. |
insert(
i, x) |
Insert a new item with value x in the
array
before
position i. Negative values are treated as being relative to the end of
the array. |
pop(
[i]) |
Removes the item with the index i from
the array and
returns it. The optional argument defaults to -1, so that by default
the last item is removed and returned. |
read(
f, n) |
Deprecated since release 1.5.1. Use the
fromfile()
method. |
remove(
x) |
Remove the first occurrence of x from the
array. |
reverse(
) |
Reverse the order of the items in the
array. |
tofile(
f) |
Write all items (as machine values) to
the file
object f. |
tolist(
) |
Convert the array to an ordinary list
with the
same
items. |
tostring(
) |
Convert the array to an array of machine
values
and
return the string representation (the same sequence of bytes that would
be written to a file by the tofile() method.) |
tounicode(
) |
Convert the array to a unicode string.
The array
must be a type 'u' array; otherwise a ValueError is raised. Use
"array.tostring().decode(enc)" to obtain a unicode string from an array
of some other type. |
7. Compilers:
Shed Skin Compiler
Compiler-SIG
Psyco 1.6 with Intel MacOS/X support
Beta release 1.0.0b1
Obelisk 28/5/2007
Python 2.0 and VIDE
8. Projects and software in
Phyton:
Phython can be used for many kinds of
software development.Runs on
Windows,
Linux/Unix, Mac OS X, OS/2, Amiga, Palm Handhelds, and Nokia mobile
phones.Python is distributed under an OSI-approved open source license
that makes it free to use.
Some of the largest projects that use Python are the Zope
application
server, the Mnet distributed file store, Youtube, and the original
BitTorrent client. Large organizations that make use of Python include
Google and NASA. Air Canada's reservation management system is written
in Python.
Python has also seen extensive use in the information security
industry. Notably, in several of the tools offered by Immunity
Security,in several of the tools offered by Core Security, in the Web
application security scanner Wapiti, and in the fuzzer TAOF. Python is
commonly used in exploit development.
Python has been successfully embedded in a number of software
products
as a scripting language. It is commonly used in 3D animation packages,
as in Maya, Softimage XSI, Modo, Nuke and Blender. It is also used in
Paint Shop Pro. ESRI is now promoting Python as the best choice for
writing scripts in ArcGIS.It is also used in Civilization IV as the
control language for modding and event interaction. Eve Online, an
MMORPG, is also built using Python.
For many operating systems, Python is a standard component; it
ships
with most Linux distributions, with FreeBSD, NetBSD, and OpenBSD, and
with Mac OS X. Red Hat Linux and Fedora use the pythonic Anaconda.
Gentoo Linux uses Python in its package management system, Portage, and
the standard tool to access it, emerge. Pardus uses it for
administration and during system boot.
On this link you can see a list of the software using python -
link