Python Material
Python Material
Strings are amongst the most popular types in Python. Strings can be created
simply by enclosing characters in quotes (). Python treats single quotes the same
as double quotes. Other languages such as C use single quotes for characters and
double quotes for strings. Python does not have a character type.
Nearly every Python application uses strings in one form or another. Strings
are a literal or scalar type, meaning they are treated by the interpreter as a singular
value and are not containers which hold other Python objects. Strings are
immutable, meaning that changing an element of a string requires creating a new
string. Strings are made up of individual characters, and each such element of
strings may be accessed sequentially through an operation called slicing
Creating and Assigning Values to Strings
Dictionaries
Dictionaries stores elements in the form of Key value form.
The syntax of a dictionary entry is key:value.
Dictionary entries are enclosed in braces ( { } ).
How to Create and Assign Dictionaries
>>> dict1 = {}
>>> dict2 = {'name': 'earth', 'port': 80}
>>> dict1, dict2
({}, {'port': 80, 'name': 'earth'})
Access Values in Dictionaries
Provide the dictionary name along with the Key to get the corresponding value
>>> dict2['name']
'earth'
Updating dictionaries
You can update a dictionary by adding a new entry or element (i.e., a keyvalue pair),modifying an existing entry, or deleting an existing entry (see below for
more details on removing an entry).
>>> dict2['name'] = 'venus'
>>> dict2['port'] = 6969
>>> dict2['arch'] = 'sunos5'
dictionary method
dict.clear()
dict.get(key,default=None)
dict.has_key(key)
dict.items()
dict.keys()
dict.update(dict2)
dict.values()
Operation
removes all elements of dictionary dict
for key key, returns value or default if
key not in dictionary
returns 1 if key in dictionary dict, 0
otherwise
returns a list of dict's (key, value) tuple
pairs
returns list of dictionary dict's keys
adds dictionary dict2's key-values pairs
to dict
returns list of dictionary dict's values
While Loop
It is used to repeat executing a set of statements.
Syntax
while expression:
block_to_repeat
Example
>>> i=0
>>> while i<10:
print i;
i=i+1;
The above code prints values from 0 to 9
For Loop
It is also used to repeat executing a set of statements. It will be much
clearer than while loop.
Syntax
for item in sequence:
block_to_repeat
Example 1
>>> for letter in 'Hello':
print 'Current Letter ', letter
Current Letter H
Current Letter e
Current Letter l
Current Letter l
Current Letter o
Example 2
>>> for x in range(5): # prints 5 values from 0 to 4
print x;
0
1
2
3
4
Example 3
>>> for x in range(1,5): # prints 4 values from 1 to 4
print x;
1
2
3
4
range() function
syntax
range(start,end,step=1)
start beginning value
end final value
step increment value [default is 1]
break Statement
break statement is used to break a running loop.
continue Statement
continue statement is used to skip remaining of the current iteration and
move on to the next iteration.
pass Statement
pass statement does absolutely nothing. pass is also useful in places
where code will be written, but has not been written yet.
else for While
else can also be used along with while to take an alternate path if while
initially fails.
File Handling
File handling is a very important aspect of any programming language.
File Objects
File objects can be used not only to access normal disk files, but also any
other type of "file" that uses that abstraction. Once the proper "hooks" are installed,
you can access other objects with file-like interfaces in the same manner you would
access normal files.
open()
open() returns a file object on a successful opening of the file or else results in an
error situation. When a failure occurs, Python generates or raises an IOError
exception.
Syntax
file_object = open(file_name, access_mode='r', buffering=-1)
default mode is r (read) and buffering =-1 forces Systems default buffering method
to be used.
File Mode
r
w
a
r+
w+
a+
rb, wb, ab
rb+, wb+, ab+
Operation
open for read
open for write (truncate if necessary)
open for append (start at EOF, create if necessary)
open for read and write
open for write and read
open for append and read
Similar to r, w, and a but works with binary
Similar to r+, w+ and a+, but works with binary
write() opposite functionality of read() and readline().It takes a string which can
consist of one or more lines of text data or a block of bytes and writes the data to
the file.
writelines() takes a list of strings and writes them out to a file
seek(off,whence)
The seek() method moves the file pointer to different positions within the file.
off number of bytes to move (Offset value)
whence 0 seek from beginning of file, 1 seek from current position, 2 seek from
end of file
tell()
the tell() method tells the current location of the file bytes from the beginning of the
file.
close()
The close() method completes access to a file by closing it.
Example
fname=raw_input("Enter file name");
f=open(fname,"r");
alllines=f.readlines();
print "Contents of FILE are \n";
for line in alllines:
print line
Output will be as follows
Enter file name a.txt
Contents of FILE are
This is python
This is from file
File system
try-except Statement
Syntax
try:
try_block
except Exception:
handling block# handling code
Example 1
>>> try:
f = open('blah')
except IOError:
print 'could not open file'
Example 2
try:
x=float('a');
print x;
except ValueError:
print 'Cant convert an alphabet';
print 'Done';
Output will be
>>>
Cant convert an alphabet
Done
try Statement with Multiple excepts
Syntax
try:
try_block
except E1:
handling_block1
except E2:
handling_block2
.
.
except En:
handling_block_n
except with multiple Exceptions
except (Exception1, Exception2):
block_for_both_Exception1_and_Exception2
except with No exceptions named
try:
try_suite
except:
except_suite # handles all exceptions
try-finally Statement
The try-finally statement differs from its try-except brethren in that it is not used to
handle exceptions. Instead it is used to maintain consistent behavior regardless of
whether or not exceptions occur. The finally suite executes regardless of an
exception being triggered within the try suite.
Syntax
try:
try_suite
finally:
finally_suite # executes regardless of exceptions
Raising Exceptions
The interpreter was responsible for raising all of the exceptions which we
have seen so far. Python provides a mechanism for the programmer to explicitly
generate an exception: the raise statement.
Raise statement
The raise statement is quite flexible with the arguments which it supports,
translating to a large number of different formats supported syntactically.
Syntax
raise Exception
assert Statement
Functions
Functions are the structured or procedural programming way of organizing the logic
in your programs. Large blocks of code can be neatly segregated into manageable
chunks, and space is saved by putting oft-repeated code in functions as opposed to
multiple copies everywhere.
A function that does not return any value can be termed as procedure.
Example
>>> def hello():
print "Hello";
>>> hello();
Hello
Invoking a function
Syntax
function-name()
Returning a value from function
return statement can be used to return a value to the caller of the function
Example1
def sayHello(name):
return Hello: + name;
sayHello(Ram);
output will be Hello Ram
Example 2
def add(a,b):
c=int(a)+int(b);
return c;
res=add(10,20);
Modules
A module allows you to logically organize your Python code. When code gets to be
large enough, the tendency is to break it up into organized pieces which can still
interact with each other at a functioning level. The process of associating attributes
from other modules with your module is called importing.
Importing Module
import module1[,module2,.,moduleN]
Example
import re #imports a module named re
Import with rename
import re as regex #imports a module named re and renames as regex
Packages
Packages are a way of structuring Pythons module namespace by using
dotted module names. For example, the module name A.B designates a sub
module named B in a package named A. Just like the use of modules saves the
authors of different modules from having to worry about each others global
variable names.
Package contains collection of modules in directory
every package or sub package must have __init__.py file
May contain sub packages
# constructor
self.items = []
def push(self, x):
self.items.append(x)
def pop(self):
x = self.items[-1]
del self.items[-1]
return x
def empty(self):
return len(self.items) == 0 # returns true or false
Creating Instance
To create an instance, simply call the class object: new operator Is not required in
python.
x = MyStack()
Calling methods
x.empty() # displays 1 items empty
x.push(1) #LIST items contains [1]
x.empty() # -> displays 0 items not empty
x.push("hello")
x.pop()
Subclassing
class FancyStack(MyStack):
"stack with added ability to inspect inferior stack items"
def peek(self):
print Subclass Fancy stack;
Class and Instance Variable
class Connection:
a=0
# a is class variable