Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 21

Strings

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

>>> a = 'Hello World!'


>>> b = "Python is cool!"
>>> print a
Hello World!
>>> print b
Python is cool!

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'

# update existing entry


# update existing entry
# add new entry

Removing Dictionary Elements


del dict1['name']
dict1.clear()
del dict1

# remove entry with key 'name'


# remove all entries in dict1
# delete entire dictionary

Comparisons of Dictionaries [ cmp() ]


Comparisons of dictionaries are based on an algorithm which starts with
Sizes of dictionaries first, then keys, and finally values.
Returns -1 when dict1 is smaller than dict2
Returns 0 when dict1 is equal to dict2
Returns 1 when dict1 is larger than dict2
>>> dict1 = {}
>>> dict2 = { 'host': 'earth', 'port': 80 }
>>> cmp(dict1, dict2)
-1

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

CONDITIONALS & LOOPS


if elif else
Syntax
if expression1:
expr1_true_suite
elif expression2:
expr2_true_suite
.
.
elif expressionN:
exprN_true_suite
else:
none_of_the_above_suite
Example
a=1
b=2
if a>b:
print a is bigger;
elif a==b:
print Both are equal;
else:
print b is bigger;

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

Reading Data (Input)


read() reads bytes directly into a string, reading at most the number of bytes
indicated. If no size is given, the default value is set to -1, meaning that the file is
read to the end.
readline() reads one line of the open file
readlines() similar, but reads all remaining lines as strings
Writing Data (Output)

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

Access to file System normally happens using os module.


os module functions are described below,
remove()/ unlink() deletes the file
rename() renames the file
listdir() lists files in the current directory
mkdir() creates directories
rmdir() removes directories
os.path module functions are described below,
basename() remove directory path and return file name
dirname() remove file name and returns directory path
getsize() return file size (in bytes)

Errors And Exceptions


Errors are an everyday occurrence in the life of a programmer. Any time an error
occurred, execution was halted until the error was corrected and code was reexecuted.
Exceptions in Python
1) NameError: attempt to access an undeclared variable
>>> foo
Traceback (innermost last):
File "<interactive input>", line 0, in ?
NameError: foo
2) ZeroDivisionError: division by any numeric zero
>>> 12.4/0.0
Traceback (innermost last):
File "<interactive input>", line 0, in ?
ZeroDivisionError: float division
3) SyntaxError: Python interpreter syntax error
>>> for
File "<string>", line 1
for
^
SyntaxError: invalid syntax
4) IndexError: request for an out-of-range index for sequence
>>> aList = []
>>> aList[0]
Traceback (innermost last):
File "<stdin>", line 1, in ?

IndexError: list index out of range

5) KeyError: request for a non-existent dictionary key


>>> aDict = {'host': 'earth', 'port': 80}
>>> print aDict['server']
Traceback (innermost last):
File "<stdin>", line 1, in ?
KeyError: server
6) IOError: input/output error
>>> f = open("blah")
Traceback (innermost last):
File "<interactive input>", line 1, in ?
IOError: [Errno 2] No such file or directory: 'blah'
Detecting and Handling Exceptions

try-except Statement
Syntax
try:
try_block

# exception may occur here

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

# exception may occur here

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

# watch for exceptions here

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

The assert statement evaluates a Python expression, taking no action if


the assertion succeeds (similar to a pass statement), but otherwise raises an
AssertionError exception.
Syntax assert expression[, arguments]

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);

print ('Addition is ',res);


Output will be Addition is 30

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

Classes and Objects


class name:
"documentation"
statements
-orclass name(base1, base2, ...):
...
Most, statements are method definitions:
def name(self, arg1, arg2, ...):
...
May also be class variable assignments
Example
class MyStack:
"A well-known data structure"
def __init__(self):

# constructor

self.items = []
def push(self, x):
self.items.append(x)

# adds element to the list items

def pop(self):
x = self.items[-1]

#tests for empty

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()

#LIST items contains [1, "hello"]

# -> displays "hello" and LIST items contains [1]

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

def __init__(self, h):


self.b = h

# self.b is instance variable

You might also like