Wednesday, July 20, 2011

How to get user input in python?

In Python we can use the raw_input() and input() to take inputs from user.

Example for raw_input()..
>>> lastName = raw_input("What is your Last Name?")
What is your Last Name?pk
>>> firstName = raw_input("What is your First Name?")
What is your First Name?amala
>>> print("Is your name {0} {1}?".format(firstName, lastName))
Is your name amala pk?
>>>

Example for input()..
>>> x = input("Enter a number:")
Enter a number:6
>>> print x
6

Now let's think how these inputs are interpreted....
Using raw_input, the data is always interpreted as a string...Using input, the data is always interpreted as integer type...

We can check this...

>>> a=raw_input()
5
>>> print type(a)
>>> digit=int(a)
>>> print type(digit)
>>>

also

>>> a=input()
6
>>> print type(a)
>>> string=str(a)
>>> print type(string)

Thus we can use int() and str() to convert to integer type and string type respectively.



Tuesday, July 12, 2011

Some Programs involving Recursion

We can find a^b using recursion.The code is..

def power(a, b):
if (b == 0):
return 1
else:
a=a*power(a, b-1)
return a

print power(3, 9)


We can optimise the above program and reduce the time complexity.
Here is the code for that..

def power(a, b):
if(b == 0):
return 1
else:
if(b%2 == 0):
v = power(a, b/2)
return v**2
else:
v = power(a, (b-1)/2)
return a*v**2

print power(3, 5)


Next we can move on to finding the nth element of Fibonacci series.
For that we have a recursive code..

def fib(n):
if n<2 :
return n
else:

return fib(n-1)+fib(n-2)

print fib(6)


We can optimise the above code using the technique of memorisation.
Then the code will be..

def fib(n):
if not n in memory:
memory[n] = fib(n-1) + fib(n-2)
return memory[n]

memory={0:0,1:1}
print fib (250)





Thursday, July 7, 2011

Object-Oriented Programming

One of the way of organising our program is to combine data and functionality and wrap it inside an object. This is called the object oriented programming paradigm. This way is used when we want to write large programs or have a solution that is better suited to it.

Classes and objects are the two main aspects of object oriented programming. A class creates a new type where objects are instances of the class. Even integers are treated as objects (of the int class)

Objects can store data using ordinary variables that belong to the object. Variables that belong to an object or class are called as fields. Objects can also have functionality by using functions that belong to a class. Such functions are called methods of the class. This terminology is important because it helps us to differentiate between functions and variables which are separate by itself and those which belong to a class or object. Collectively, the fields and methods can be referred to as the attributes of that class.

Fields are of two types - they can belong to each instance/object of the class or they can belong to the class itself. They are called instance variables and class variables respectively.

A class is created using the class keyword. The fields and methods of the class are listed in an indented block.

Class methods have only one specific difference from ordinary functions - they must have an extra first name that has to be added to the beginning of the parameter list, but you do do not give a value for this parameter when you call the method, Python will provide it. This particular variable refers to the object itself, and by convention, it is given the name self.

Although, you can give any name for this parameter, it is strongly recommended that you use the name self - any other name is definitely frowned upon.

>>> class person:
... pass
...
>>> p=person()
>>> print p
<__main__.person instance at 0xb776586c>

We have already discussed that classes/objects can have methods just like
functions except that we have an extra
self variable. We will now see
an example.


>>> class person:

... def sayHi(self):
... print "Hai,friend"
...
>>> p=person()
>>> p.sayHi()
Hai,friend
>>>


The __init__ method
There are many method names which have special significance in Python classes.

The __init__ method is run as soon as an object of a class is instantiated. The method is useful to do any initialization you want to do with your object. Notice the double underscore both in the beginning and at the end in the name.

>>> class person:
... def __init__(self,name):
... self.name=name
... def sayHi(self):
... print "Hai, my name is",self.name
...
>>> p=person('amala')
>>> p.sayHi()
Hai, my name is amala

Here, we define the __init__ method as taking a parameter name (along with the usual self). Here, we just create a new field also called name. Notice these are two different variables even though they have the same name. The dotted notation allows us to differentiate between them.

Most importantly, notice that we do not explicitly call the __init__ method but pass the arguments in the parentheses following the class name when creating a new instance of the class. This is the special significance of this method.


Sunday, July 3, 2011

Exception Handling

Error reporting and processing through exceptions is one of Python’s key features. In Python a programmer can raise an exception at any point in a program. When the exception is raised, program execution is interrupted as the interpreter searches back up the stack to find a context with an exception handler.

Lets start with a simple program.

>>> a=6
>>> b=0
>>> c=a/b

Python "crashes" on divide by zero.

Traceback (most recent call last):
File "", line 1, in
ZeroDivisionError: integer division or modulo by zero

Now let's try that with exception handling:

>>> a=6
>>> b=0
>>> try:
... print " a = ",a
... print " b = ",b
... c=a/b
... print " c = ",c
... except:
... print " division failed !!!"
... c=0
... print " c default to ",c
... else:
... print "division went very well"
...
This time the program will not crash, we will get an error message printed instead. Our program will continue to execute.

Our output looks like this:

a = 6
b = 0
division failed !!!
c default to 0

The statements in the try: block are attempted.The first failure jumps to the except: block If nothing in the try block fails, the program jumps to the else: block. The 1st two print statements execute, but then the try block fails, so - print 'c=',c - does not. The except block executes.The else block does not execute.