Python
What is Python?
Python® is a dynamic object-oriented programming language that can be used for many kinds of software development. It offers strong support for integration with other languages and tools, comes with extensive standard libraries, and can be learned in a few days. Many Python programmers report substantial productivity gains and feel the language encourages the development of higher quality, more maintainable code.
Installing
Installing Python is generally easy, and nowadays many Linux and UNIX distributions include a recent Python. Even some Windows computers (notably those from HP) now come with Python already installed. If you do need to install Python and aren't confident about the task you can finda few notes on theBeginners Guide/Downloadwiki page, but installation is unremarkable on most platforms.
Getting started quickly
Python Environment
Interactive Mode:
simply typing the command ‘python’
commands are read from a terminal primary prompt, usually three greater-than signs (">>> ")
help() Enter the name of any module, keyword, or topic to get help on using Python, e.g. math
Stand-alone mode:
Make a file hello.py:
#! /usr/bin/python
print “hello”
Run:
python hello.py Or
chmod +x hello.py
./hello.py
Data types and operations
Numbers
>>> 2+2 # 4
>>> (50-5*6)/4 # 5
sign ("=") is used to assign a value to a variable
>>> width = 20
>>> height = 5*9
>>> width * height #900
float or integer
>>> 3 /2 # 1
>>> float(3)/2 # 1.5
>>> 3.0/2 # 1.5
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:
Strings can be indexed, sliced and concatenated (from 0)
>>>word = ’’This is a rather long string‘’
The first two characters ‘Th'
>>> word[:2]
>>> word[ 2:4] # ‘is'
All but the first two characters
‘is is a rather long string
>>> word[ 2:] ‘
>>> 'x' + word[ 1:] # 'xhis is a rather long string‘
>>> word[-1] # the last character ‘g’
>>> word[-2:] # the last two characters ‘ng’
creating a new string
>>> word[:2] +'at' # ‘That'
Lists
>>> a = ['spam', 'eggs', 100, 1234]
Like string indices, list indices start at 0, and lists can be sliced, concatenated
Unlike strings, which are immutable, it is possible to change individual elements of a list
The built-in function len() applies to lists:
from string
>>>x=‘a b c d e f’.split() # x=['a', 'b', 'c', 'd', 'e', 'f']
Dictionaries
>>> tel = {'jack': 4098, 'sape': 4139}
>>> tel['guido'] = 4127 # {'sape': 4139, 'guido': 4127, 'jack': 4098}
>>> del tel['sape'] # {'jack': 4098, 'guido': 4127}
>>> tel.keys() # ['jack', 'guido']
>>> tel.items() # [('jack', 4098), ('guido', 4127)]
Sets
unordered collection with no duplicate elements
>>> a = set('abracadabra')
>>> b = set('alacazam')
>>> a # unique letters in a set(#91'a', 'r', 'b', 'c', 'd'])
>>> a - b # letters in a but not in b set(#91'r', 'd', 'b'])
>>> a | b # letters in either a or b set(#91'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'])
>>> a & b # letters in both a and b set(#91'a', 'c'])
>>> a ^ b # letters in a or b but not both set(#91'r', 'd', 'b', 'm', 'z', 'l'])
Tuples
immutable list
>>> t = 12345, 54321, 'hello!'
>>> tΎ] # 12345
first step 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:
... print b
... a, b = b, a+b
...
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 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. Python does not (yet!) provide an intelligent input line editing facility, so you have to type a tab or space(s) for each indented line. In practice you will prepare more complicated input for Python with a text editor; most text editors have an auto-indent facility. When a compound statement is entered interactively, it must be followed by a blank line to indicate completion (since the parser cannot guess when you have typed the last line). Note that each line within a basic block must be indented by the same amount.
The print statement writes the value of the expression(s) it is given. It differs from just writing the expression you want to write (as we did earlier in the calculator examples) in the way it handles multiple expressions and strings. Strings are printed without quotes, and a space is inserted between items, so you can format things nicely, like this:
>>> i = 256*256
>>> print 'The value of i is', i
The value of i is 65536
A trailing comma avoids the newline after the output:
>>> a, b = 0, 1
>>> while b < 1000:
... print b,
... a, b = b, a+b
...
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
Note that the interpreter inserts a newline before it prints the next prompt if the last line was not completed.
Statements of flow controlling and Syntax
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.
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']
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)
Ύ, 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
input and output
File IO
>>> f=open(‘tmp.txt', ‘w‘,0)
Open a file. The mode can be 'r', 'w' or 'a' for reading (default), writing or appending. The file will be created if it doesn't exist. when opened for writing or appending; it will be truncated when opened for writing. If the buffering argument is given, 0 means unbuffered, 1 means line buffered, and larger numbers specify the buffer size.
>>> f.write(‘temp file’)
>>> open(‘tmp.txt’).read() # return ‘temp file’
Output Formatting
>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678}
>>> for name, phone in table.items():
... print '%-10s ==> %10d' % (name, phone)
Jack ==> 4098
Dcab ==> 7678
Sjoerd ==> 4127
http://www.python.org/doc/lib/typesseq-strings.html
Learning more from Internet
Even after reading the content above, you may still want to find out which IDEs and text editors are tailored to make Python editing easy, browse the list of introductory books, or look at code samples that you might find helpful.
There is a list of tutorials suitable for experienced programmers on the BeginnersGuide/Tutorials page. There is also a list of resources in other languages which might be useful if English is not your first language.
The online documentation is your first port of call for definitive information. There is a fairly brief tutorial that gives you basic information about the language and gets you started. You can follow this by looking at the library reference
for a full description of Python's many libraries and the language reference for a complete (though somewhat dry) explanation of Python's syntax.
Comments (0)
You don't have permission to comment on this page.