python notes
python notes
Python Overview
Python is a high-level, interpreted, interactive and object-oriented
scripting language. Python is designed to be highly readable. It uses
English keywords frequently where as other languages use punctuation,
and it has fewer syntactical constructions than other languages.
Python is Interpreted: Python is processed at runtime by the
interpreter. You do not need to compile your program before
executing it. This is similar to PERL and PHP.
Python is Interactive: You can actually sit at a Python prompt and
interact with the interpreter directly to write your programs.
Python is Object-Oriented: Python supports Object-Oriented
style or technique of programming that encapsulates code within
objects.
Python is a Beginner's Language: Python is a great language for
the beginner-level programmers and supports the development of a
wide range of applications from simple text processing to WWW
browsers to games.
History of Python
Python was developed by Guido van Rossum in the late eighties and
early nineties at the National Research Institute for Mathematics and
Computer Science in the Netherlands.
Python is derived from many other languages, including ABC,
Modula-3, C, C++, Algol-68, SmallTalk, and Unix shell and other
scripting languages.
Python is copyrighted. Like Perl, Python source code is now available
under the GNU General Public License (GPL).
Python is now maintained by a core development team at the
institute, although Guido van Rossum still holds a vital role in
directing its progress.
Python Features
Python's features include:
Easy-to-learn: Python has few keywords, simple structure, and a
clearly defined syntax. This allows the student to pick up the
language quickly.
Easy-to-read: Python code is more clearly defined and visible to the
eyes.
Easy-to-maintain: Python's source code is fairly easy-to-maintain.
A broad standard library: Python's bulk of the library is very
portable and cross-platform compatible on UNIX, Windows, and
Macintosh.
Interactive Mode: Python has support for an interactive mode
which allows interactive testing and debugging of snippets of code.
Portable: Python can run on a wide variety of hardware platforms
and has the same interface on all platforms.
Extendable: You can add low-level modules to the Python
interpreter. These modules enable programmers to add to or
customize their tools to be more efficient.
Databases: Python provides interfaces to all major commercial
databases.
GUI Programming: Python supports GUI applications that can be
created and ported to many system calls, libraries and windows
systems, such as Windows MFC, Macintosh, and the X Window
system of Unix.
Scalable: Python provides a better structure and support for large
programs than shell scripting.
Apart from the above-mentioned features, Python has a big list of good
features, few are listed below:
IT supports functional and structured programming methods as well
as OOP.
It can be used as a scripting language or can be compiled to byte-code
for building large applications.
It provides very high-level dynamic data types and supports dynamic
type checking.
IT supports automatic garbage collection.
It can be easily integrated with C, C++, COM, ActiveX, CORBA, and
Java.
print counter
print miles
print name
Here, 100, 1000.0 and "John" are the values assigned to counter, miles,
and name variables, respectively. This produces the following result −
100
1000.0
John
Multiple Assignment
Python allows you to assign a single value to several variables
simultaneously. For example −
a=b=c=1
Here, an integer object is created with the value 1, and all three variables
are assigned to the same memory location. You can also assign multiple
objects to multiple variables. For example −
a, b, c = 1, 2, "john"
Here, two integer objects with values 1 and 2 are assigned to variables a
and b respectively, and one string object with the value "john" is assigned
to the variable c.
Standard Data Types
The data stored in memory can be of many types. For example, a person's
age is stored as a numeric value and his or her address is stored as
alphanumeric characters. Python has various standard data types that are
used to define the operations possible on them and the storage method for
each of them.
Python has five standard data types −
Numbers
String
List
Tuple
Dictionary
Python Numbers
Number data types store numeric values. Number objects are created
when you assign a value to them. For example −
var1 = 1
var2 = 10
You can also delete the reference to a number object by using the del
statement. The syntax of the del statement is −
del var1[,var2[,var3[....,varN]]]]
You can delete a single object or multiple objects by using the del
statement. For example −
del var
del var_a, var_b
Python supports four different numerical types −
int (signed integers)
long (long integers, they can also be represented in octal and
hexadecimal)
float (floating point real values)
complex (complex numbers)
Examples
Here are some examples of numbers −
int long float complex
print list1
del list1[2];
print "After deleting value at index 2 : "
print list1
When the above code is executed, it produces following result −
['physics', 'chemistry', 1997, 2000]
After deleting value at index 2 :
['physics', 'chemistry', 2000]
Note: remove() method is discussed in subsequent section.
Basic List Operations
Lists respond to the + and * operators much like strings; they mean
concatenation and repetition here too, except that the result is a new list,
not a string.
In fact, lists respond to all of the general sequence operations we used on
strings in the prior chapter.
Python Expression Results Description
1 cmp(list1, list2)
2 len(list)
3 max(list)
4 min(list)
5 list(seq)
Converts a tuple into list.
Description
The method list() takes sequence types and converts them to
lists. This is used to convert a given tuple into list.
Note: Tuple are very similar to lists with only difference that
element values of a tuple can not be changed and tuple elements
are put between parentheses instead of square bracket.
Syntax
Following is the syntax for list() method:
list( seq )
Parameters
seq -- This is a tuple to be converted into list.
Return Value
This method returns the list.
Example
The following example shows the usage of list() method.
!/usr/bin/python
1 list.append(obj)
2 list.count(obj)
3 list.extend(seq)
4 list.index(obj)
5 list.insert(index, obj)
6 list.pop(obj=list[-1])
7 list.remove(obj)
8 list.reverse()
9 list.sort([func])
Python Tuples
A tuple is a sequence of immutable Python objects. Tuples are sequences,
just like lists. The differences between tuples and lists are, the tuples
cannot be changed unlike lists and tuples use parentheses, whereas lists
use square brackets.
Creating a tuple is as simple as putting different comma-separated values.
Optionally you can put these comma-separated values between
parentheses also. Tuples can be thought of as read-only lists. For
example −
For example –
print tup
del tup;
print "After deleting tup : "
print tup
This produces the following result. Note an exception raised, this is
because after del tup tuple does not exist any more −
('physics', 'chemistry', 1997, 2000)
After deleting tup :
Traceback (most recent call last):
File "test.py", line 9, in <module>
print tup;
NameError: name 'tup' is not defined
Basic Tuples Operations
Tuples respond to the + and * operators much like strings; they mean
concatenation and repetition here too, except that the result is a new tuple,
not a string.
In fact, tuples respond to all of the general sequence operations we used on
strings in the prior chapter −
Python Expression Results Description
1 cmp(tuple1, tuple2)
2 len(tuple)
3 max(tuple)
4 min(tuple)
5 tuple(seq)
Converts a list into tuple.
Description
The method tuple() converts a list of items into tuples
Syntax
Following is the syntax for tuple() method −
tuple( seq )
Parameters
seq -- This is a tuple to be converted into tuple.
Return Value
This method returns the tuple.
Example
The following example shows the usage of tuple() method.
#!/usr/bin/python
Python Dictionary
#!/usr/bin/python
Each key is separated from its value by a colon (:), the items are separated
by commas, and the whole thing is enclosed in curly braces. An empty
dictionary without any items is written with just two curly braces, like this:
{}.
Keys are unique within a dictionary while values may not be. The values of
a dictionary can be of any type, but the keys must be of an immutable data
type such as strings, numbers, or tuples.
Example
dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"
tinydict = {'name': 'john','code':6734, 'dept': 'sales'}
1 cmp(dict1, dict2)
Compares elements of both dict.
2 len(dict)
Gives the total length of the dictionary. This would be equal to
the number of items in the dictionary.
3 str(dict)
Produces a printable string representation of a dictionary
4 type(variable)
Returns the type of the passed variable. If passed variable is
dictionary, then it would return a dictionary type.
Python includes following dictionary methods −
SN Methods with Description
1 dict.clear()
Removes all elements of dictionary dict
2 dict.copy()
Returns a shallow copy of dictionary dict
3 dict.fromkeys()
Create a new dictionary with keys from seq and
values set to value.
4 dict.get(key, default=None)
For key key, returns value or default if key not in dictionary
5 dict.has_key(key)
Returns true if key in dictionary dict, false otherwise
6 dict.items()
Returns a list of dict's (key, value) tuple pairs
7 dict.keys()
Returns list of dictionary dict's keys
8 dict.setdefault(key, default=None)
Similar to get(), but will set dict[key]=default if key is not already
in dict
9 dict.update(dict2)
Adds dictionary dict2's key-values pairs to dict
10 dict.values()
Returns list of dictionary dict's values
Looping Techniques
>>>
To loop over two or more sequences at the same time, the entries can be
paired with the zip() function.
>>>
>>>
To loop over a sequence in sorted order, use the sorted() function which
returns a new sorted list while leaving the source unaltered.
>>>
When looping through dictionaries, the key and corresponding value can be
retrieved at the same time using the iteritems() method.
>>>
Python Strings
Strings are amongst the most popular types in Python. We can create them
simply by enclosing characters in quotes. Python treats single quotes the
same as double quotes. Creating strings is as simple as assigning a value to
a variable. For example −
var1 = 'Hello World!'
var2 = "Python Programming"
Accessing Values in Strings
Python does not support a character type; these are treated as strings of
length one, thus also considered a substring.
To access substrings, use the square brackets for slicing along with the
index or indices to obtain your substring. For example −
#!/usr/bin/python
\b 0x08 Backspace
\cx Control-x
\C-x Control-x
\e 0x1b Escape
\f 0x0c Formfeed
\M-\C-x Meta-Control-x
\n 0x0a Newline
\s 0x20 Space
\t 0x09 Tab
\x Character x
[] Slice - Gives the character from the given a[1] will give
index e
[:] Range Slice - Gives the characters from the a[1:4] will
given range give ell
%c character
%o octal integer
- left justification
1 capitalize()
Capitalizes first letter of string
It returns a copy of the string with only its first character
capitalized.
Syntax
str.capitalize()
Parameters
NA
Return Value
string
Example
#!/usr/bin/python
str = "this is string example....wow!!!";
2 center(width, fillchar)
4 decode(encoding='UTF-8',errors='strict')
Decodes the string using the codec registered for encoding.
encoding defaults to the default string encoding.
5 encode(encoding='UTF-8',errors='strict')
7 expandtabs(tabsize=8)
10 isalnum()
11 isalpha()
12 isdigit()
Returns true if string has at least 1 cased character and all cased
characters are in lowercase and false otherwise.
14 isnumeric()
15 isspace()
16 istitle()
17 isupper()
Returns true if string has at least one cased character and all
cased characters are in uppercase and false otherwise.
18 join(seq)
19 len(string)
20 ljust(width[, fillchar])
21 lower()
print str.lower()
When we run above program, it produces following result −
this is string example....wow!!!
22 lstrip()
23 maketrans()
24 max(str)
25 min(str)
27 rfind(str, beg=0,end=len(string))
29 rjust(width,[, fillchar])
30 rstrip()
31 split(str="", num=string.count(str))
32 splitlines( num=string.count('\n'))
Splits string at all (or num) NEWLINEs and returns a list of each
line with NEWLINEs removed.
33 startswith(str, beg=0,end=len(string))
34 strip([chars])
35 swapcase()
Inverts case for all letters in string.
36 title()
Returns "titlecased" version of string, that is, all words begin with
uppercase and the rest are lowercase.
37 translate(table, deletechars="")
38 upper()
39 zfill (width)
40 isdecimal()
Example
#!/usr/bin/python
var1 = 100
if var1:
print "1 - Got a true expression value"
print var1
var2 = 0
if var2:
print "2 - Got a true expression value"
print var2
print "Good bye!"
When the above code is executed, it produces the following result −
1 - Got a true expression value
100
Good bye!
IF...ELIF...ELSE Statements
An else statement can be combined with an if statement.
An else statement contains the block of code that executes if the
conditional expression in the if statement resolves to 0 or a FALSE value.
The else statement is an optional statement and there could be at most
only one else statement following if .
Syntax
The syntax of the if...else statement is −
if expression:
statement(s)
else:
statement(s)
Flow Diagram
Example
#!/usr/bin/python
var1 = 100
if var1:
print "1 - Got a true expression value"
print var1
else:
print "1 - Got a false expression value"
print var1
var2 = 0
if var2:
print "2 - Got a true expression value"
print var2
else:
print "2 - Got a false expression value"
print var2
var = 100
if var == 200:
print "1 - Got a true expression value"
print var
elif var == 150:
print "2 - Got a true expression value"
print var
elif var == 100:
print "3 - Got a true expression value"
print var
else:
print "4 - Got a false expression value"
print var
var = 100
if var < 200:
print "Expression value is less than 200"
if var == 150:
print "Which is 150"
elif var == 100:
print "Which is 100"
elif var == 50:
print "Which is 50"
elif var < 50:
print "Expression value is less than 50"
else:
print "Could not find true expression"
var = 100
nested loops You can use one or more loop inside any another
while, for or do..while loop.
Here, key point of the while loop is that the loop might not ever run. When
the condition is tested and the result is false, the loop body will be skipped
and the first statement after the while loop will be executed.
Example
#!/usr/bin/python
count = 0
while (count < 9):
print 'The count is:', count
count = count + 1
var = 1
while var == 1 : # This constructs an infinite loop
num = raw_input("Enter a number :")
print "You entered: ", num
count = 0
while count < 5:
print count, " is less than 5"
count = count + 1
else:
print count, " is not less than 5"
When the above code is executed, it produces the following result −
0 is less than 5
1 is less than 5
2 is less than 5
3 is less than 5
4 is less than 5
5 is not less than 5
Single Statement Suites
Similar to the if statement syntax, if your while clause consists only of a
single statement, it may be placed on the same line as the while header.
Here is the syntax and example of a one-line while clause −
#!/usr/bin/python
flag = 1
It has the ability to iterate over the items of any sequence, such as a list or
a string.
Syntax
for iterating_var in sequence:
statements(s)
If a sequence contains an expression list, it is evaluated first. Then, the first
item in the sequence is assigned to the iterating variable iterating_var.
Next, the statements block is executed. Each item in the list is assigned
toiterating_var, and the statement(s) block is executed until the entire
sequence is exhausted.
Flow Diagram
Example
#!/usr/bin/python
i=2
while(i < 100):
j=2
while(j <= (i/j)):
if not(i%j): break
j=j+1
if (j > i/j) : print i, " is prime"
i=i+1
>>>
>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
reversed(seq)
Return a reverse iterator. seq must be an object
>>>
>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1))
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
Example
#!/usr/bin/python
Python Numbers
Number data types store numeric values. They are immutable data types,
means that changing the value of a number data type results in a newly
allocated object.
Number objects are created when you assign a value to them. For example
−
var1 = 1
var2 = 10
You can also delete the reference to a number object by using
the delstatement. The syntax of the del statement is −
del var1[,var2[,var3[....,varN]]]]
You can delete a single object or multiple objects by using
the del statement. For example:
del var
del var_a, var_b
Python supports four different numerical types −
int (signed integers): They are often called just integers or ints,
are positive or negative whole numbers with no decimal point.
long (long integers ): Also called longs, they are integers of
unlimited size, written like integers and followed by an uppercase or
lowercase L.
float (floating point real values) : Also called floats, they
represent real numbers and are written with a decimal point dividing
the integer and fractional parts. Floats may also be in scientific
notation, with E or e indicating the power of 10 (2.5e2 = 2.5 x 102 =
250).
complex (complex numbers) : are of the form a + bJ, where a
and b are floats and J (or j) represents the square root of -1 (which is
an imaginary number). The real part of the number is a, and the
imaginary part is b. Complex numbers are not used much in Python
programming.
Examples
Here are some examples of numbers
int long float complex
#!/usr/bin/python
raw_input
input
The raw_input Function
The raw_input([prompt]) function reads one line from standard input
and returns it as a string (removing the trailing newline).
#!/usr/bin/python
This prompts you to enter any string and it would display same string on
the screen. When I typed "Hello Python!", its output is like this −
#!/usr/bin/python
This would produce the following result against the entered input −
File
What Is a File?
Before we can go into how to work with files in Python, itʼs important to
understand what exactly a file is and how modern operating systems handle some
of their aspects.
At its core, a file is a contiguous set of bytes used to store data. This data is
organized in a specific format and can be anything as simple as a text file or as
complicated as a program executable. In the end, these byte files are then
translated into binary 1 and 0 for easier processing by the computer.
Files on most modern file systems are composed of three main parts:
1. Header: metadata about the contents of the file (file name, size, type, and so
on)
2. Data: contents of the file as written by the creator or editor
3. End of file (EOF): special character that indicates the end of the file
What this data represents depends on the format specification used, which is
typically represented by an extension. For example, a file that has an extension
of .gif most likely conforms to the Graphics Interchange Format specification.
There are hundreds, if not thousands, of file extensions out there. For this tutorial,
youʼll only deal with .txt or .csv file extensions.
File Paths
When you access a file on an operating system, a file path is required. The file path is a string
that represents the location of a file. It’s broken up into three major parts:
1. Folder Path: the file folder location on the file system where subsequent folders are separated
by a forward slash / (Unix) or backslash \ (Windows)
2. File Name: the actual name of the file
3. Extension: the end of the file path pre-pended with a period (.) used to indicate the file type
Hereʼs a quick example. Letʼs say you have a file located within a file structure
like this:
│
├── path/
| │
│ ├── to/
│ │ └── cats.gif
│ │
│ └── dog_breeds.txt
|
└── animals.csv
Let’s say you wanted to access the cats.gif file, and your current location was in the same
folder as path. In order to access the file, you need to go through the path folder and then
the to folder, finally arriving at the cats.gif file. The Folder Path is path/to/. The File Name
is cats. The File Extension is .gif. So the full path is path/to/cats.gif.
Now let’s say that your current location or current working directory (cwd) is in the to folder of
our example folder structure. Instead of referring to the cats.gif by the full path
of path/to/cats.gif, the file can be simply referenced by the file name and
extension cats.gif.
/
│
├── path/
| │
| ├── to/ ← Your current working directory (cwd) is here
| │ └── cats.gif ← Accessing this file
| │
| └── dog_breeds.txt
|
└── animals.csv
But what about dog_breeds.txt? How would you access that without using the full path? You
can use the special characters double-dot (..) to move one directory up. This means
that ../dog_breeds.txt will reference the dog_breeds.txt file from the directory of to:
/
│
├── path/ ← Referencing this parent folder
| │
| ├── to/ ← Current working directory (cwd)
| │ └── cats.gif
| │
| └── dog_breeds.txt ← Accessing this file
|
└── animals.csv
The double-dot (..) can be chained together to traverse multiple directories above the current
directory. For example, to access animals.csv from the to folder, you would
use ../../animals.csv.
Line Endings
One problem often encountered when working with file data is the representation of a new line
or line ending. The line ending has its roots from back in the Morse Code era, when a specific
pro-sign was used to communicate the end of a transmission or the end of a line.
Pug\r\n
Jack Russell Terrier\r\n
English Springer Spaniel\r\n
German Shepherd\r\n
Staffordshire Bull Terrier\r\n
Cavalier King Charles Spaniel\r\n
Golden Retriever\r\n
West Highland White Terrier\r\n
Boxer\r\n
Border Terrier\r\n
Before you can read or write a file, you have to open it using Python's built-
in open() function. This function creates a file object, which would be
utilized to call other support methods associated with it.
Syntax
file object = open(file_name [, access_mode][, buffering])
Modes Description
r Opens a file for reading only. The file pointer is placed at the
beginning of the file. This is the default mode.
rb Opens a file for reading only in binary format. The file pointer
is placed at the beginning of the file. This is the default mode.
r+ Opens a file for both reading and writing. The file pointer
placed at the beginning of the file.
rb+ Opens a file for both reading and writing in binary format.
The file pointer placed at the beginning 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.
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 both appending and reading. The file pointer
is at the end of the file if the file exists. The 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.
The file pointer is at the end of the file if the file exists. The
file opens in the append mode. If the file does not exist, it
creates a new file for reading and writing.
Attribute Description
Example
#!/usr/bin/python
# Open a file
fo = open("foo.txt", "wb")
print "Name of the file: ", fo.name
print "Closed or not : ", fo.closed
print "Opening mode : ", fo.mode
print "Softspace flag : ", fo.softspace
Example
#!/usr/bin/python
# Open a file
fo = open("foo.txt", "wb")
print "Name of the file: ", fo.name
Here, passed parameter is the content to be written into the opened file.
Example
#!/usr/bin/python
# Open a file
fo = open("foo.txt", "wb")
fo.write( "Python is a great language.\nYeah its great!!\n");
The above method would create foo.txt file and would write given content
in that file and finally it would close that file. If you would open this file, it
would have following content.
Here, passed parameter is the number of bytes to be read from the opened
file. This method starts reading from the beginning of the file and
if count is missing, then it tries to read as much as possible, maybe until
the end of file.
Example
Let's take a file foo.txt, which we created above.
#!/usr/bin/python
# Open a file
fo = open("foo.txt", "r+")
str = fo.read(10);
print "Read String is : ", str
# Close opend file
fo.close()
File Positions
The 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
beginning of the file.
The seek(offset[, from]) method changes the current file position.
The offsetargument indicates the number of bytes to be moved.
The from argument specifies the reference position from where the bytes
are to be moved.
If from is set to 0, it means use the beginning 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.
Example
Let us take a file foo.txt, which we created above.
#!/usr/bin/python
# Open a file
fo = open("foo.txt", "r+")
str = fo.read(10);
print "Read String is : ", str
Example
Following is the example to rename an existing file test1.txt:
#!/usr/bin/python
import os
# Rename a file from test1.txt to test2.txt
os.rename( "test1.txt", "test2.txt" )
Example
Following is the example to delete an existing file test2.txt −
#!/usr/bin/python
import os
Directories in Python
All files are contained within various directories, and Python has no
problem handling these too. The os module has several methods that help
you create, remove, and change directories.
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 argument to this method
which contains the name of the directory to be created.
Syntax
os.mkdir("newdir")
Example
Following is the example to create a directory test in the current directory
−
#!/usr/bin/python
import os
Example
Following is the example to go into "/home/newdir" directory −
#!/usr/bin/python
import os
Example
Following is the example to give current directory −
#!/usr/bin/python
import os
Example
Following is the example to remove "/tmp/test" directory. It is required to
give fully qualified name of the directory, otherwise it would search for
that directory in the current directory.
#!/usr/bin/python
import os
1 file.close()
Close the file. A closed file cannot be read or written any more.
2 file.flush()
Flush the internal buffer, like stdio's fflush. This may be a no-op
on some file-like objects.
3 file.fileno()
Returns the integer file descriptor that is used by the underlying
implementation to request I/O operations from the operating
system.
4 file.isatty()
Returns True if the file is connected to a tty(-like) device, else
False.
5 file.next()
Returns the next line from the file each time it is being called.
6 file.read([size])
Reads at most size bytes from the file (less if the read hits EOF
before obtaining size bytes).
7 file.readline([size])
Reads one entire line from the file. A trailing newline character is
kept in the string.
8 file.readlines([sizehint])
Reads until EOF using readline() and return a list containing the
lines. If the optional sizehint argument is present, instead of
reading up to EOF, whole lines totalling approximately sizehint
bytes (possibly after rounding up to an internal buffer size) are
read.
9 file.seek(offset[, whence])
Sets the file's current position
10 file.tell()
Returns the file's current position
11 file.truncate([size])
Truncates the file's size. If the optional size argument is present,
the file is truncated to (at most) that size.
12 file.write(str)
Writes a string to the file. There is no return value.
13 file.writelines(sequence)
Writes a sequence of strings to the file. The sequence can be any
iterable object producing strings, typically a list of strings.
Syntax Errors
Syntax errors, also known as parsing errors, are perhaps the most common
kind of complaint you get:
>>>
The parser repeats the offending line and displays a little ‘arrow’ pointing at
the earliest point in the line where the error was detected. The error is
caused by (or at least detected at) the token preceding the arrow: in the
example, the error is detected at the keyword print, since a colon (':') is
missing before it. File name and line number are printed so you know
where to look in case the input came from a script.
Assertions in Python
An assertion is a sanity-check that you can turn on or turn off when you
are done with your testing of the program.
The easiest way to think of an assertion is to liken it to a raise-
if statement (or to be more accurate, a raise-if-not statement). An
expression is tested, and if the result comes up false, an exception is raised.
Assertions are carried out by the assert statement, the newest keyword to
Python, introduced in version 1.5.
Programmers often place assertions at the start of a function to check for
valid input, and after a function call to check for valid output.
The assert Statement
When it encounters an assert statement, Python evaluates the
accompanying expression, which is hopefully true. If the expression is
false, Python raises anAssertionError exception.
The syntax for assert is −
#!/usr/bin/python
def KelvinToFahrenheit(Temperature):
assert (Temperature >= 0),"Colder than absolute zero!"
return ((Temperature-273)*1.8)+32
print KelvinToFahrenheit(273)
print int(KelvinToFahrenheit(505.78))
print KelvinToFahrenheit(-5)
32.0
451
Traceback (most recent call last):
File "test.py", line 9, in
print KelvinToFahrenheit(-5)
File "test.py", line 4, in KelvinToFahrenheit
assert (Temperature >= 0),"Colder than absolute zero!"
AssertionError: Colder than absolute zero!
What is Exception?
An exception is an event, which occurs during the execution of a program
that disrupts the normal flow of the program's instructions. In general,
when a Python script encounters a situation that it cannot cope with, it
raises an exception. An exception is a Python object that represents an
error.
When a Python script raises an exception, it must either handle the
exception immediately otherwise it terminates and quits.
Handling an exception
If you have some suspicious code that may raise an exception, you can
defend your program by placing the suspicious code in a try: block. After
the try: block, include an except: statement, followed by a block of code
which handles the problem as elegantly as possible.
Syntax
Here is simple syntax of try....except...else blocks −
try:
You do your 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.
You can also provide a generic except clause, which handles any
exception.
After the except clause(s), you can include an else-clause. The code in
the else-block executes if the code in the try: block does not raise an
exception.
The else-block is a good place for code that does not need the try:
block's protection.
Example
This example opens a file, writes content in the, file and comes out
gracefully because there is no problem at all −
#!/usr/bin/python
try:
fh = open("testfile", "w")
fh.write("This is my test file for exception handling!!")
except IOError:
print "Error: can\'t find file or read data"
else:
print "Written content in the file successfully"
fh.close()
try:
fh = open("testfile", "r")
fh.write("This is my test file for exception handling!!")
except IOError:
print "Error: can\'t find file or read data"
else:
print "Written content in the file successfully"
try:
You do your operations here;
......................
except:
If there is any exception, then execute this block.
......................
else:
If there is no exception then execute this block.
This kind of a try-except statement catches all the exceptions that occur.
Using this kind of try-except statement is not considered a good
programming practice though, because it catches all exceptions but does
not make the programmer identify the root cause of the problem that may
occur.
The except Clause with Multiple Exceptions
You can also use the same except statement to handle multiple exceptions
as follows −
try:
You do your operations here;
......................
except(Exception1[, Exception2[,...ExceptionN]]]):
If there is any exception from the given exception list,
then execute this block.
......................
else:
If there is no exception then execute this block.
try:
You do your operations here;
......................
Due to any exception, this may be skipped.
finally:
This would always be executed.
......................
Note that you can provide except clause(s), or a finally clause, but not both.
You cannot use else clause as well along with a finally clause.
Example
#!/usr/bin/python
try:
fh = open("testfile", "w")
fh.write("This is my test file for exception handling!!")
finally:
print "Error: can\'t find file or read data"
If you do not have permission to open the file in writing mode, then this
will produce the following result:
#!/usr/bin/python
try:
fh = open("testfile", "w")
try:
fh.write("This is my test file for exception handling!!")
finally:
print "Going to close the file"
fh.close()
except IOError:
print "Error: can\'t find file or read data"
try:
You do your operations here;
......................
except ExceptionType, Argument:
You can print value of Argument here...
If you write the code to handle a single exception, you can have a variable
follow the name of the exception in the except statement. If you are
trapping multiple exceptions, you can have a variable follow the tuple of
the exception.
This variable receives the value of the exception mostly containing the
cause of the exception. The variable can receive a single value or multiple
values in the form of a tuple. This tuple usually contains the error string,
the error number, and an error location.
Example
Following is an example for a single exception −
#!/usr/bin/python
try:
Business Logic here...
except "Invalid level!":
Exception handling here...
else:
Rest of the code here...
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. This is useful when you need to display
more specific information when an exception is caught.
In the try block, the user-defined exception is raised and caught in the
except block. The 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 the exception as follows −
try:
raise Networkerror("Bad hostname")
except Networkerror,e:
print e.args
Python Functions
A function is a block of organized, reusable code that is used to perform a
single, related action. Functions provide better modularity for your
application and a high degree of code reusing.
As you already know, Python gives you many built-in functions like print(),
etc. but you can also create your own functions. These functions are
called user-defined functions.
Defining a Function
You can define functions to provide the required functionality. Here are
simple rules to define a function in Python.
Function blocks begin with the keyword def followed by the function
name and parentheses ( ( ) ).
The code block within every function starts with a colon (:) and is
indented.
Calling a Function
Defining a function only gives 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.
Following is the example to call printme() function −
#!/usr/bin/python
#!/usr/bin/python
#!/usr/bin/python
Function Arguments
You can call a function by using the following types of formal arguments:
Required arguments
Keyword arguments
Default arguments
Variable-length arguments
Required arguments
Required arguments are the arguments passed to a function in correct
positional order. Here, the number of arguments in the function call
should match exactly with the function definition.
To call the function printme(), you definitely need to pass one argument,
otherwise it gives a syntax error as follows −
#!/usr/bin/python
Keyword arguments
Keyword arguments are related to the function calls. When you use
keyword arguments in a function call, the caller identifies the arguments
by the parameter name.
This allows you to skip arguments or place them out of order because the
Python interpreter is able to use the keywords provided to match the
values with parameters. You can also make keyword calls to
the printme() function in the following ways −
#!/usr/bin/python
My string
The following example gives more clear picture. Note that the order of
parameters does not matter.
#!/usr/bin/python
Name: miki
Age 50
Default arguments
A default argument is an argument that assumes a default value if a value
is not provided in the function call for that argument. The following
example gives an idea on default arguments, it prints default age if it is not
passed −
#!/usr/bin/python
Name: miki
Age 50
Name: miki
Age 35
Variable-length arguments
You may need to process a function for more arguments than you specified
while defining the function. These arguments are called variable-
lengtharguments and are not named in the function definition, unlike
required and default arguments.
Syntax for a function with non-keyword variable arguments is this −
An asterisk (*) is placed before the variable name that holds the values of
all nonkeyword variable arguments. This tuple remains empty if no
additional arguments are specified during the function call. Following is a
simple example −
#!/usr/bin/python
# Function definition is here
def printinfo( arg1, *vartuple ):
"This prints a variable passed arguments"
print "Output is: "
print arg1
for var in vartuple:
print var
return;
Output is:
10
Output is:
70
60
50
Functional programming
The Anonymous Functions
These functions are called anonymous because they are not declared in the
standard manner by using the def keyword. You can use
the lambda keyword to create small anonymous functions.
Lambda forms can take any number of arguments but return just one
value in the form of an expression. They cannot contain commands
or multiple expressions.
An anonymous function cannot be a direct call to print because
lambda requires an expression
Lambda functions have their own local namespace and cannot access
variables other than those in their parameter list and those in the
global namespace.
#!/usr/bin/python
Value of total : 30
Value of total : 40
#!/usr/bin/python
Scope of Variables
All variables in a program may not be accessible at all locations in that
program. This depends on where you have declared a variable.
The scope of a variable determines the portion of the program where you
can access a particular identifier. There are two basic scopes of variables in
Python −
Global variables
Local variables
Global vs. Local variables
Variables that are defined inside a function body have a local scope, and
those defined outside have a global scope.
This means that local variables can be accessed only inside the function in
which they are declared, whereas global variables can be accessed
throughout the program body by all functions. When you call a function,
the variables declared inside it are brought into scope. Following is a
simple example −
#!/usr/bin/python
Python Modules
Function is a block of code which execute some logic. Module is a bundle
of functions. Modules contain n function inside.
A module allows you to logically organize 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
The Python code for a module named aname normally resides in a file
namedaname.py. Here's an example of a simple module, support.py
#!/usr/bin/python
For example, to import the function fibonacci from the module fib, use the
following statement −
This statement does not import the entire module fib into the current
namespace; it just introduces the item fibonacci from the module fib into
the global symbol table of the importing module.
The from...import * Statement:
It is also possible to import all names from a module into the current
namespace by using the following import statement −
This provides an easy way to import all the items from a module into the
current namespace; however, this statement should be used sparingly.
Locating Modules
When you import a module, the Python interpreter searches for the
module in the following sequences −
If the module isn't found, Python then searches each directory in the
shell variable PYTHONPATH.
If all else fails, Python checks the default path. On UNIX, this default
path is normally /usr/local/lib/python/.
The module search path is stored in the system module sys as
the sys.pathvariable. The sys.path variable contains the current directory,
PYTHONPATH, and the installation-dependent default.
The PYTHONPATH Variable:
The PYTHONPATH is an environment variable, consisting of a list of
directories. The syntax of PYTHONPATH is the same as that of the shell
variable PATH.
Here is a typical PYTHONPATH from a Windows system:
set PYTHONPATH=c:\python20\lib;
set PYTHONPATH=/usr/local/lib/python
#!/usr/bin/python
Money = 2000
def AddMoney():
# Uncomment the following line to fix the code:
# global Money
Money = Money + 1
print Money
AddMoney()
print Money
#!/usr/bin/python
content = dir(math)
print content
reload(module_name)
Here, module_name is the name of the module you want to reload and not
the string containing the module name. For example, to
reload hello module, do the following −
reload(hello)
Packages in Python
A package is a hierarchical file directory structure that defines a single
Python application environment that consists of modules and subpackages
and sub-subpackages, and so on.
Consider a file Pots.py available in Phone directory. This file has following
line of source code −
#!/usr/bin/python
def Pots():
print "I'm Pots Phone"
Similar way, we have another two files having different functions with the
same name as above −
Phone/__init__.py
To make all of your functions available when you've imported Phone, you
need to put explicit import statements in __init__.py as follows −
After you add these lines to __init__.py, you have all of these classes
available when you import the Phone package.
#!/usr/bin/python
Data member: A class variable or instance variable that holds data associated
with a class and its objects.
Instance variable: A variable that is defined inside a method and belongs only
to the current instance of a class.
Creating Classes
The class statement creates a new class definition. The name of the class
immediately follows the keyword class followed by a colon as follows −
class ClassName:
class_suite
Example
Following is the example of a simple Python class −
class Employee:
empCount = 0
self.name = name
self.salary = salary
Employee.empCount += 1
def displayCount(self):
def displayEmployee(self):
The variable empCount is a class variable whose value is shared among all
instances of a this class. This can be accessed asEmployee.empCount from
inside the class or outside the class.
The first method __init__() is a special method, which is called class constructor
or initialization method that Python calls when you create a new instance of this
class.
You declare other class methods like normal functions with the exception that
the first argument to each method is self. Python adds the self argument to the
list for you; you do not need to include it when you call the methods.
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()
#!/usr/bin/python
class Employee:
empCount = 0
self.name = name
self.salary = salary
Employee.empCount += 1
def displayCount(self):
print "Total Employee %d" % Employee.empCount
def displayEmployee(self):
emp1.displayEmployee()
emp2.displayEmployee()
Total Employee 2
You can add, remove, or modify attributes of classes and objects at any
time −
Instead of using the normal statements to access attributes, you can use
the following functions −
__bases__: A possibly empty tuple containing the base classes, in the order of
their occurrence in the base class list.
For the above class let us try to access all these attributes −
#!/usr/bin/python
class Employee:
empCount = 0
self.name = name
self.salary = salary
Employee.empCount += 1
def displayCount(self):
You normally will not notice when the garbage collector destroys an
orphaned instance and reclaims its space. But a class can implement the
special method__del__(), called a destructor, that is invoked when the
instance is about to be destroyed. This method might be used to clean up
any non memory resources used by an instance.
Example
This __del__() destructor prints the class name of an instance that is about
to be destroyed −
#!/usr/bin/python
class Point:
self.x = x
self.y = y
def __del__(self):
class_name = self.__class__.__name__
pt1 = Point()
pt2 = pt1
pt3 = pt1
del pt1
del pt2
del pt3
Point destroyed
Note: Ideally, you should define your classes in separate file, then you
should import them in your main program file using import statement.
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.
The 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 is given after the class name −
class_suite
Example
#!/usr/bin/python
parentAttr = 100
def __init__(self):
def parentMethod(self):
Parent.parentAttr = attr
def getAttr(self):
def __init__(self):
def childMethod(self):
Similar way, you can drive a class from multiple parent classes as follows −
.....
.....
class C(A, B): # subclass of A and B
.....
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.
Example
#!/usr/bin/python
def myMethod(self):
def myMethod(self):
2 __del__( self )
Destructor, deletes an object
Sample Call : del obj
3 __repr__( self )
Evaluatable string representation
Sample Call : repr(obj)
4 __str__( self )
Printable string representation
Sample Call : str(obj)
5 __cmp__ ( self, x )
Object comparison
Sample Call : cmp(obj, x)
Overloading Operators
Suppose you have 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
−
Example
#!/usr/bin/python
class Vector:
self.a = a
self.b = b
def __str__(self):
def __add__(self,other):
v1 = Vector(2,10)
v2 = Vector(5,-2)
print v1 + v2
Vector(7,8)
Data Hiding
An object's attributes may or may not be visible outside the class definition.
You need to name attributes with a double underscore prefix, and those
attributes then are not be directly visible to outsiders.
Example
#!/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
print counter.__secretCount
.........................
print counter._JustCounter__secretCount
1
2
2