Python - Quick Guide Python Overview:: Interactive Mode Prog Ramming
Python - Quick Guide Python Overview:: Interactive Mode Prog Ramming
http://www.tuto rialspo int.co m/pytho n/pytho n_quick_g uide .htm Co pyrig ht tuto rials po int.co m
PYTHON OVERVIEW:
Python is a hig h-level, interpreted, interactive and object oriented-scripting lang uag e.
Python is Interpreted
Python was developed by Guido van Rossum in the late eig hties and early nineties at the National Research
Institute for Mathematics and Computer Science in the Netherlands.
Easy-to-learn
Easy-to-read
Easy-to-maintain
Portable
Extendable
Databases
Sc alable
GETTING PYTHON:
T he most up-to-date and current source code, binaries, documentation, news, etc. is available at the official
website of Python:
You can download the Python documentation from the following site. T he documentation is available in HT ML,
PDF, and PostScript formats.
root# python
Python 2.5 (r25:51908, Nov 6 2007, 16:54:01)
[GCC 4.1.2 20070925 (Red Hat 4.1.2-27)] on linux2
Type "help", "copyright", "credits" or "license" for more info.
>>>
T ype the following text to the rig ht of the Python prompt and press the Enter key:
Hello, Python!
PYTHON IDENTIFIERS:
A Python identifier is a name used to identify a variable, function, class, module, or other object. An identifier
starts with a letter A to Z or a to z or an underscore (_) followed by zero or more letters, underscores, and dig its
(0 to 9).
Python does not allow punctuation characters such as @, $, and % within identifiers. Python is a case sensitive
prog ramming lang uag e. T hus Manpower and manpower are two different identifiers in Python.
Class names start with an uppercase letter and all other identifiers with a lowercase letter.
Starting an identifier with a sing le leading underscore indicates by convention that the identifier is meant to
be private.
Starting an identifier with two leading underscores indicates a strong ly private identifier.
If the identifier also ends with two trailing underscores, the identifier is a lang uag e-defined special name.
RESERVED WORDS:
T he following list shows the reserved words in Python. T hese reserved words may not be used as constant or
variable or any other identifier names.
assert finally or
def if return
elif in while
else is with
T he number of spaces in the indentation is variable, but all statements within the block must be indented the same
amount. Both blocks in this example are fine:
if True:
print "True"
else:
print "False"
if True:
print "Answer"
print "True"
else:
print "Answer"
print "False"
MULTI-LINE STATEMENTS:
Statements in Python typically end with a new line. Python does, however, allow the use of the line continuation
character (\) to denote that the line should continue. For example:
total = item_one + \
item_two + \
item_three
Statements contained within the [], {}, or () brackets do not need to use the line continuation character. For
example:
QUOTATION IN PYTHON:
Python accepts sing le ('), double (") and triple (''' or """) quotes to denote string literals, as long as the same type
of quote starts and ends the string .
T he triple quotes can be used to span the string across multiple lines. For example, all the following are leg al:
word = 'word'
sentence = "This is a sentence."
paragraph = """This is a paragraph. It is
made up of multiple lines and sentences."""
COMMENTS IN PYTHON:
A hash sig n (#) that is not inside a string literal beg ins a comment. All characters after the # and up to the physical
line end are part of the comment, and the Python interpreter ig nores them.
#!/usr/bin/python
# First comment
print "Hello, Python!"; # second comment
Hello, Python!
# This is a comment.
# This is a comment, too.
# This is a comment, too.
# I said that already.
In an interactive interpreter session, you must enter an empty physical line to terminate a multiline statement.
Compound or complex statements, such as if, while, def, and class, are those which require a header line and a
suite.
Header lines beg in the statement (with the keyword) and terminate with a colon ( : ) and are followed by one or
more lines which make up the suite.
Example:
if expression :
suite
elif expression :
suite
else :
suite
Based on the data type of a variable, the interpreter allocates memory and decides what can be stored in the
reserved memory. T herefore, by assig ning different data types to variables, you can store integ ers, decimals,
or characters in these variables.
print counter
print miles
print name
Numbers
String
List
T uple
Dictionary
PYTHON NUMBERS:
Number objects are created when you assig n a value to them. For example:
var1 = 1
var2 = 10
long (long integ ers [can also be represented in octal and hexadecimal])
PYTHON STRINGS:
String s in Python are identified as a contig uous set of characters in between quotation marks.
Example:
str = 'Hello World!'
#!/usr/bin/python
PYTHON TUPLES:
A tuple is another sequence data type that is similar to the list. A tuple consists of a number of values separated by
commas. Unlike lists, however, tuples are enclosed within parentheses.
PYTHON DICTIONARY:
Python 's dictionaries are hash table type. T hey work like associative arrays or hashes found in Perl and consist
of key-value pairs.
- Subtraction - Subtracts rig ht hand operand from left a - b will g ive -10
hand operand
** Exponent - Performs exponential (power) calculation on a**b will g ive 10 to the power 20
operators
// Floor Division - T he division of operands where the 9//2 is equal to 4 and 9.0//2.0 is
result is the quotient in which the dig its after the decimal equal to 4.0
point are removed.
== Checks if the value of two operands are equal or not, if (a == b) is not true.
yes then condition becomes true.
<> Checks if the value of two operands are equal or not, if (a <> b) is true. T his is similar to !=
values are not equal then condition becomes true. operator.
> Checks if the value of left operand is g reater than the (a > b) is not true.
value of rig ht operand, if yes then condition becomes
true.
< Checks if the value of left operand is less than the value (a < b) is true.
of rig ht operand, if yes then condition becomes true.
>= Checks if the value of left operand is g reater than or (a >= b) is not true.
equal to the value of rig ht operand, if yes then condition
becomes true.
<= Checks if the value of left operand is less than or equal to (a <= b) is true.
the value of rig ht operand, if yes then condition becomes
true.
= Simple assig nment operator, Assig ns values from rig ht c = a + b will assig ne value of a + b
side operands to left side operand into c
//= Floor Dividion and assig ns a value, Performs floor c //= a is equivalent to c = c // a
division on operators and assig n value to the left
operand
& Binary AND Operator copies a bit to the result if it exists (a & b) will g ive 12 which is 0000
in both operands. 1100
| Binary OR Operator copies a bit if it exists in eather (a | b) will g ive 61 which is 0011
operand. 1101
^ Binary XOR Operator copies the bit if it is set in one (a ^ b) will g ive 49 which is 0011
operand but not both. 0001
~ Binary Ones Complement Operator is unary and has the (~a ) will g ive -61 which is 1100
efect of 'flipping ' bits. 0011 in 2's complement form due to
a sig ned binary number.
<< Binary Left Shift Operator. T he left operands value is a << 2 will g ive 240 which is 1111
moved left by the number of bits specified by the rig ht 0000
operand.
>> Binary Rig ht Shift Operator. T he left operands value is a >> 2 will g ive 15 which is 0000
moved rig ht by the number of bits specified by the rig ht 1111
operand.
and Called Log ical AND operator. If both the operands are (a and b) is true.
true then then condition becomes true.
not Called Log ical NOT Operator. Use to reverses the not(a && b) is false.
log ical state of its operand. If a condition is true then
Log ical NOT operator will make false.
not in Evaluates to true if it does not finds a variable in the x not in y, here not in results in a 1
specified sequence and false otherwise. if x is not a member of sequence y.
is Evaluates to true if the variables on either side of the x is y, here is results in 1 if id(x)
operator point to the same object and false otherwise. equals id(y).
is not Evaluates to false if the variables on either side of the x is not y, here is not results in 1 if
operator point to the same object and true otherwise. id(x) is not equal to id(y).
~+- Ccomplement, unary plus and minus (method names for the last two
are +@ and -@)
THE IF STATEMENT:
T he syntax of the if statement is:
if expression:
statement(s)
if expression:
statement(s)
else:
statement(s)
if expression1:
statement(s)
elif expression2:
statement(s)
elif expression3:
statement(s)
else:
statement(s)
if expression1:
statement(s)
if expression2:
statement(s)
elif expression3:
statement(s)
else
statement(s)
elif expression4:
statement(s)
else:
statement(s)
while expression:
statement(s)
An infinite loop mig ht be useful in client/server prog ramming where the server needs to run continuously so that
client prog rams can communicate with it as and when required.
T he most common use for break is when some external condition is trig g ered requiring a hasty exit from a loop.
T he break statement can be used in both while and for loops.
If the else statement is used with a for loop, the else statement is executed when the loop has exhausted
iterating the list.
If the else statement is used with a while loop, the else statement is executed when the condition
becomes false.
T he pass statement is a null operation; nothing happens when it executes. T he pass is also useful in places
where your code will eventually g o, but has not been written yet (e.g ., in stubs for example):
#!/usr/bin/python
DEFINING A FUNCTION
You can define functions to provide the required functionality. Here are simple rules to define a function in Python:
Function blocks beg in with the keyword def followed by the function name and parentheses ( ( ) ).
Any input parameters or arg uments should be placed within these parentheses. You can also define
parameters inside these parentheses.
T he first statement of a function can be an optional statement - the documentation string of the function or
docstring.
T he code block within every function starts with a colon (:) and is indented.
T he statement return [expression] exits a function, optionally passing back an expression to the caller. A
return statement with no arg uments is the same as return None.
Syntax:
def functionname( parameters ):
"function_docstring"
function_suite
return [expression]
By default, parameters have a positional behavior, and you need to inform them in the same order that they were
defined.
Example:
Here is the simplest form of a Python function. T his function takes a string as input parameter and prints it on
standard screen.
CALLING A FUNCTION
Defining a function only g ives it a name, specifies the parameters that are to be included in the function, and
structures the blocks of code.
Once the basic structure of a function is finalized, you can execute it by calling it from another function or directly
from the Python prompt.
#!/usr/bin/python
PYTHON - MODULES:
A module allows you to log ically org anize your Python code. Grouping related code into a module makes the
code easier to understand and use.
A module is a Python object with arbitrarily named attributes that you can bind and reference.
Simply, a module is a file consisting of Python code. A module can define functions, classes, and variables. A
module can also include runnable code.
Example:
T he Python code for a module named aname normally resides in a file named aname.py. Here's an example of a
simple module, hello.py
When the interpreter encounters an import statement, it imports the module if the module is present in the search
path. A search path is a list of directories that the interpreter searches before importing a module.
Example:
T o import the module hello.py, you need to put the following command at the top of the script:
#!/usr/bin/python
Hello : Zara
A module is loaded only once, reg ardless of the number of times it is imported. T his prevents the module
execution from happening over and over ag ain if multiple imports occur.
Syntax:
file object = open(file_name [, access_mode][, buffering])
file_name: T he file_name arg ument is a string value that contains the name of the file that you want to
access.
ac c ess_mode: T he access_mode determines the mode in which the file has to be opened ie. read,
write append etc. A complete list of possible values is g iven below in the table. T his is optional parameter
and the default file access mode is read (r)
buffering : If the buffering value is set to 0, no buffering will take place. If the buffering value is 1, line
buffering will be performed while accessing a file. If you specify the buffering value as an integ er g reater
than 1, then buffering action will be performed with the indicated buffer size. T his is optional paramter.
r Opens a file for reading only. T he file pointer is placed at the beg inning of the file. T his is the
default mode.
rb Opens a file for reading only in binary format. T he file pointer is placed at the beg inning of the file.
T his is the default mode.
r+ Opens a file for both reading and writing . T he file pointer will be at the beg inning of the file.
rb+ Opens a file for both reading and writing in binary format. T he file pointer will be at the beg inning
of the file.
w Opens a file for writing only. Overwrites the file if the file exists. If the file does not exist, creates a
new file for writing .
wb Opens a file for writing only in binary format. Overwrites the file if the file exists. If the file does not
exist, creates a new file for writing .
w+ Opens a file for both writing and reading . Overwrites the existing file if the file exists. If the file
does not exist, creates a new file for reading and writing .
wb+ Opens a file for both writing and reading in binary format. Overwrites the existing file if the file
exists. If the file does not exist, creates a new file for reading and writing .
a Opens a file for appending . T he file pointer is at the end of the file if the file exists. T hat is, the file is
in the append mode. If the file does not exist, it creates a new file for writing .
ab Opens a file for appending in binary format. T he file pointer is at the end of the file if the file exists.
T hat is, the file is in the append mode. If the file does not exist, it creates a new file for writing .
a+ Opens a file for both appending and reading . T he file pointer is at the end of the file if the file exists.
T he file opens in the append mode. If the file does not exist, it creates a new file for reading and
writing .
ab+ Opens a file for both appending and reading in binary format. T he file pointer is at the end of the
file if the file exists. T he file opens in the append mode. If the file does not exist, it creates a new file
for reading and writing .
file.softspace Returns false if space explicitly required with print, true otherwise.
fileObject.close();
FILE POSITIONS:
T he tell() method tells you the current position within the file in other words, the next read or write will occur at
that many bytes from the beg inning of the file:
T he seek(offset[, from]) method chang es the current file position. T he offset arg ument indicates the number of
bytes to be moved. T he from arg ument specifies the reference position from where the bytes are to be moved.
If from is set to 0, it means use the beg inning of the file as the reference position and 1 means use the current
position as the reference position and if it is set to 2 then the end of the file would be taken as the reference
position.
DIRECTORIES IN PYTHON:
The mkdir() Method:
You can use the mkdir() method of the os module to create directories in the current directory. You need to
supply an arg ument to this method, which contains the name of the directory to be created.
Syntax:
os.mkdir("newdir")
Syntax:
os.chdir("newdir")
Syntax:
os.rmdir('dirname')
HANDLING AN EXCEPTION:
If you have some suspicious code that may raise an exception, you can defend your prog ram by placing the
suspicious code in a try: block. After the try: block, include an exc ept: statement, followed by a block of code
which handles the problem as eleg antly as possible.
Syntax:
Here is simple syntax of try....except...else blocks:
try:
Do you operations here;
......................
except ExceptionI:
If there is ExceptionI, then execute this block.
except ExceptionII:
If there is ExceptionII, then execute this block.
......................
else:
If there is no exception then execute this block.
Here are few important points about the above mentioned syntax:
A sing le try statement can have multiple except statements. T his is useful when the try block contains
statements that may throw different types of exceptions.
You can also provide a g eneric except clause, which handles any exception.
After the except clause(s), you can include an else-clause. T he code in the else-block executes if the code
in the try: block does not raise an exception.
T he else-block is a g ood place for code that does not need the try: block's protection.
try:
Do you operations here;
......................
except:
If there is any exception, then execute this block.
......................
else:
If there is no exception then execute this block.
STANDARD EXCEPTIONS:
Here is a list standard Exceptions available in Python: Standard Exceptions
try:
Do you operations here;
......................
Due to any exception, this may be skipped.
finally:
This would always be executed.
......................
ARGUMENT OF AN EXCEPTION:
An exception can have an argument, which is a value that g ives additional information about the problem. T he
contents of the arg ument vary by exception. You capture an exception's arg ument by supplying a variable in the
except clause as follows:
try:
Do you operations here;
......................
except ExceptionType, Argument:
You can print value of Argument here...
RAISING AN EXCEPTIONS:
You can raise exceptions in several ways by using the raise statement. T he g eneral syntax for the raise
statement.
Syntax:
raise [Exception [, args [, traceback]]]
USER-DEFINED EXCEPTIONS:
Python also allows you to create your own exceptions by deriving classes from the standard built-in exceptions.
Here is an example related to RuntimeError. Here a class is created that is subclassed from RuntimeError.
T his is useful when you need to display more specific information when an exception is caug ht.
In the try block, the user-defined exception is raised and caug ht in the except block. T he variable e is used to
create an instance of the class Networkerror.
class Networkerror(RuntimeError):
def __init__(self, arg):
self.args = arg
So once you defined above class, you can raise your exception as follows:
try:
raise Networkerror("Bad hostname")
except Networkerror,e:
print e.args
CREATING CLASSES:
T he class statement creates a new class definition. T he name of the class immediately follows the keyword class
followed by a colon as follows:
class ClassName:
'Optional class documentation string'
class_suite
T he class_suite consists of all the component statements, defining class members, data attributes, and
functions.
ACCESSING ATTRIBUTES:
You access the object's attributes using the dot operator with object. Class variable would be accessed using
class name as follows:
emp1.displayEmployee()
emp2.displayEmployee()
print "Total Employee %d" % Employee.empCount
__module__: Module name in which the class is defined. T his attribute is "__main__" in interactive
mode.
__bases__ : A possibly empty tuple containing the base classes, in the order of their occurrence in the
base class list.
Python's g arbag e collector runs during prog ram execution and is trig g ered when an object's reference count
reaches zero. An object's reference count chang es as the number of aliases that point to it chang es:
An object's reference count increases when it's assig ned a new name or placed in a container (list, tuple, or
dictionary). T he object's reference count decreases when it's deleted with del, its reference is reassig ned, or its
reference g oes out of scope. When an object's reference count reaches zero, Python collects it automatically.
CLASS INHERITANCE:
Instead of starting from scratch, you can create a class by deriving it from a preexisting class by listing the parent
class in parentheses after the new class name:
T he child class inherits the attributes of its parent class, and you can use those attributes as if they were defined in
the child class. A child class can also override data members and methods from the parent.
Syntax:
Derived classes are declared much like their parent class; however, a list of base classes to inherit from are
g iven after the class name:
OVERRIDING METHODS:
You can always override your parent class methods. One reason for overriding parent's methods is because you
may want special or different functionality in your subclass.
2 __del__( self )
Destructor, deletes an object
Sample Call : dell obj
3 __repr__( self )
Evaluatable string representation
Sample Call : repr(obj)
4 __str__( self )
Printable string representation
Sample Call : str(obj)
5 __c mp__ ( self, x )
Object comparison
Sample Call : cmp(obj, x)
OVERLOADING OPERATORS:
Suppose you've created a Vector class to represent two-dimensional vectors. What happens when you use the
plus operator to add them? Most likely Python will yell at you.
You could, however, define the __add__ method in your class to perform vector addition, and then the plus
operator would behave as per expectation:
#!/usr/bin/python
class Vector:
def __init__(self, a, b):
self.a = a
self.b = b
def __str__(self):
return 'Vector (%d, %d)' % (self.a, self.b)
def __add__(self,other):
return Vector(self.a + other.a, self.b + other.b)
v1 = Vector(2,10)
v2 = Vector(5,-2)
print v1 + v2
DATA HIDING:
An object's attributes may or may not be visible outside the class definition. For these cases, you can name
attributes with a double underscore prefix, and those attributes will not be directly visible to outsiders:
#!/usr/bin/python
class JustCounter:
__secretCount = 0
def count(self):
self.__secretCount += 1
print self.__secretCount
counter = JustCounter()
counter.count()
counter.count()
print counter.__secretCount
A regular expression is a special sequence of characters that helps you match or find other string s or sets of
string s, using a specialized syntax held in a pattern. Reg ular expressions are widely used in UNIX world.
T he module re provides full support for Perl-like reg ular expressions in Python. T he re module raises the
exception re.error if an error occurs while compiling or using a reg ular expression.
We would cover two important functions which would be used to handle reg ular expressions. But a small thing
first: T here are various characters which would have special meaning when they are used in reg ular expression.
T o avoid any confusion while dealing with reg ular expressions we would use Raw String s as r'expression'.
string T his is the string which would be searched to match the pattern
flag s You can specifiy different flag s using exclusive OR (|). T hese are modifiers
which are listed in the table below.
T he re.match function returns a matc h object on success, None on failure. We would use group(num) or
groups() function of matc h object to g et matched expression.
g roup(num=0) T his methods returns entire match (or specific subg roup num)
g roups() T his method return all matching subg roups in a tuple (empty if there weren't
any)
string T his is the string which would be searched to match the pattern
flag s You can specifiy different flag s using exclusive OR (|). T hese are modifiers
which are listed in the table below.
T he re.search function returns a matc h object on success, None on failure. We would use group(num) or
groups() function of matc h object to g et matched expression.
g roup(num=0) T his methods returns entire match (or specific subg roup num)
g roups() T his method return all matching subg roups in a tuple (empty if there weren't
any)
MATCHING VS SEARCHING:
Python offers two different primitive operations based on reg ular expressions: matc h checks for a match only at
the beg inning of the string , while searc h checks for a match anywhere in the string (this is what Perl does by
default).
Syntax:
sub(pattern, repl, string, max=0)
T his method replace all occurrences of the RE pattern in string with repl, substituting all occurrences unless
max provided. T his method would return modified string .
re.L Interprets words according to the current locale.T his interpretation affects the alphabetic
g roup (\w and \W), as well as word boundary behavior (\b and \B).
re.M Makes $ match the end of a line (not just the end of the string ) and makes ^ match the start of
any line (not just the start of the string ).
re.U Interprets letters according to the Unicode character set. T his flag affects the behavior of \w,
\W, \b, \B.
re.X Permits "cuter" reg ular expression syntax. It ig nores whitespace (except inside a set [] or
when escaped by a backslash), and treats unescaped # as a comment marker.
REGULAR-EXPRESSION PATTERNS:
Except for control characters, (+ ? . * ^ $ ( ) [ ] { } | \), all characters match themselves. You can escape a
control character by preceding it with a backslash.
Following table lists the reg ular expression syntax that is available in Python.
. Matches any sing le character except newline. Using m option allows it to match
newline as well.
a| b Matches either a or b.
(?-imx) T emporarily tog g les off i, m, or x options within a reg ular expression. If in
parentheses, only that area is affected.
(?: re) Groups reg ular expressions without remembering matched text.
(?#...) Comment.
(?! re) Specifies position using pattern neg ation. Doesn't have a rang e.
\S Matches nonwhitespace.
REGULAR-EXPRESSION EXAMPLES:
Literal characters:
Character classes:
Repetition Cases:
Example Desc ription
Backreferences:
T his matches a previously matched g roup ag ain:
(['"])[^\1]*\1 Sing le or double-quoted string . \1 matches whatever the 1st g roup matched . \2
matches whatever the 2nd g roup matched, etc.
Alternatives:
\brub\B \B is nonword boundary: match "rub" in "rube" and "ruby" but not alone