Coding


There are loads of content and age old story telling way of explain classes , I take it the nerdy way and explain on the technical part of it , in this post .

Defining a class

class ClassName:   {statement-1}   .   .   .   {statement-N}

The statements can be simple statements or it can be methods .Normally the contain methods.

Class Objects:

These supports ===> attribute references and instantiation

To understand , those two lets consider a simple class definition :

class YouNity:    "My first class"    bond = 007    def hi(self):        return 'hello world'

Attribute reference ==> YouNity.bond or YouNity.hi()

Instantiation ===> all = YouNity () , creates a new instance of the class and assigns this object to the local variable all .Hence , we can access varibales and methods of the class , as all.bond or all.hi()

__init__() ans self

This method is very much similar to the Java constructor , lets see how it can be used ?!

>>> class Who:...     def __init__(self, first, last):...         self.firstName = first...         self.lastName = last... >>> name = Who("hemanth", "hm")>>> name.first,name.last(hemanth,hm)

In the above example , the __init__ method is called when the class is instantiated , the first argumentto the method is called "self" , the name self has absolutely no special meaning to Python , but can beunderstood as the current variables reference.

Inheritance


The child must follow the parent class , that is Derived followed by Base class in the declaration.

class DerivedClassName(BaseClassName):   {statement-1}   .   .   .   {statement-N}

If the Base is in some other package then ? 

class DerivedClassName(modname.BaseClassName):

Multiple parents to a single child !!!

class DerivedClassName(Base1, Base2, Base3):   {statement-1}   .   .   .   {statement-N}






There are loads of content and age old story telling way of explain classes , I take it the nerdy way and explain on the technical part of it , in this post .

Defining a class

class ClassName:   {statement-1}   .   .   .   {statement-N}

The statements can be simple statements or it can be methods .Normally the contain methods.

Class Objects:

These supports ===> attribute references and instantiation

To understand , those two lets consider a simple class definition :

class YouNity:    "My first class"    bond = 007    def hi(self):        return 'hello world'

Attribute reference ==> YouNity.bond or YouNity.hi()

Instantiation ===> all = YouNity () , creates a new instance of the class and assigns this object to the local variable all .Hence , we can access varibales and methods of the class , as all.bond or all.hi()

__init__() ans self

This method is very much similar to the Java constructor , lets see how it can be used ?!

>>> class Who:...     def __init__(self, first, last):...         self.firstName = first...         self.lastName = last... >>> name = Who("hemanth", "hm")>>> name.first,name.last(hemanth,hm)

In the above example , the __init__ method is called when the class is instantiated , the first argumentto the method is called "self" , the name self has absolutely no special meaning to Python , but can beunderstood as the current variables reference.

Inheritance


The child must follow the parent class , that is Derived followed by Base class in the declaration.

class DerivedClassName(BaseClassName):   {statement-1}   .   .   .   {statement-N}

If the Base is in some other package then ? 

class DerivedClassName(modname.BaseClassName):

Multiple parents to a single child !!!

class DerivedClassName(Base1, Base2, Base3):   {statement-1}   .   .   .   {statement-N}






Reading or Writing to an I/O device is very much easier than reading Human mind!

The first on amongst the many functions in Python which helps in I/O is raw_input()

raw_input(); the name itself suggests , the input is in the raw format , that is it’s simply returns the string read from the user {ending with new line char}.
An argument to it , is displayed as a prompt before the user enters the data.

Ex :

print raw_input(‘What is your name?’)

o/p : What is your name ? { waits until user types and hits enter }

Next up is input() , it uses raw_input to read a string of data, and then attempts to evaluate the same and return the value of evaluation.

Ex:

x = input(‘Give me 5 random numbers please’)
if the user enters 1 2 3 4 5 , the input function will return me a list {1,2,3,4,5} !!

File Input

File can be handled very easily in python , the following example makes it clear.

for
line in open(‘try.txt’, ‘r’):

print
line[0]

Two lines to open read and print the lines in the file , on to the console!!

Line one is to open the file , it can be ‘r’, ‘w’, or ‘rw’, or any combination of them and the read data is stored in the line variable and is looped till EOF .

Line two as simple as it is , printing the data read in the loop.

P.S : The looping can be done in other was also


__stdin__, __stdout__, and __stderr__ are standard file objected defined in sys module .

The simple example on how to use sys module is shown below :

import sysfor line in sys.stdin:print line

This reads line form user and prints it on the stdout , it's read from stdin.Different functions in the sys library can be found in : sysSimilarly sys.stdout.write can be used to write

import syswrite = sys.stdout.writewrite('h')write('e')write('m')write('a')write('n')

the o/p will be : heman

This is just a simple post , an glimpse on the giant mountain called I/O in python.

Reading or Writing to an I/O device is very much easier than reading Human mind!

The first on amongst the many functions in Python which helps in I/O is raw_input()

raw_input(); the name itself suggests , the input is in the raw format , that is it’s simply returns the string read from the user {ending with new line char}.
An argument to it , is displayed as a prompt before the user enters the data.

Ex :

print raw_input(‘What is your name?’)

o/p : What is your name ? { waits until user types and hits enter }

Next up is input() , it uses raw_input to read a string of data, and then attempts to evaluate the same and return the value of evaluation.

Ex:

x = input(‘Give me 5 random numbers please’)
if the user enters 1 2 3 4 5 , the input function will return me a list {1,2,3,4,5} !!

File Input

File can be handled very easily in python , the following example makes it clear.

for
line in open(‘try.txt’, ‘r’):

print
line[0]

Two lines to open read and print the lines in the file , on to the console!!

Line one is to open the file , it can be ‘r’, ‘w’, or ‘rw’, or any combination of them and the read data is stored in the line variable and is looped till EOF .

Line two as simple as it is , printing the data read in the loop.

P.S : The looping can be done in other was also


__stdin__, __stdout__, and __stderr__ are standard file objected defined in sys module .

The simple example on how to use sys module is shown below :

import sysfor line in sys.stdin:print line

This reads line form user and prints it on the stdout , it's read from stdin.Different functions in the sys library can be found in : sysSimilarly sys.stdout.write can be used to write

import syswrite = sys.stdout.writewrite('h')write('e')write('m')write('a')write('n')

the o/p will be : heman

This is just a simple post , an glimpse on the giant mountain called I/O in python.

To create a Modules in Python, you use the def keyword, followed by the function name and argument list, and a colon to begin the function body.

General Syntax :

def (argument_list):
….}=> Body

P.S : Indentation must be taken care

Ok , now lets see few eliminator examples of modules .

import sys

def main():print "\nTill which level do you want to see the sequence ? "n = int(sys.stdin.readline()) # read from the user fibonacci(n) # call to the method with parameter 

def fibonacci(n):a,b = 0,1for i in range(0,n):print aa,b, = b,a+b

if __name__ == '__main__':main()

Here the main method , calls the Fibonacci method , which prints the sequence of Fibonacci numbers.

A method can “RETURN” ?

As Python passes all arguments using “pass by reference” , the changes on the arguments in the method is always reflected on them .

A module can return an kind of data types , those which we had seen in the earlier post .

Keeping this in mind , here a small code which everything clear :

a, b, c = 0, 0, 0def Giveabc():a = "Hello"b = "Python"c = "!"return a,b,c #defines a tuple on the fly

def GiveTuple():a,b,c = 1,2,3return (a,b,c)

def GiveList():a,b,c = (3,4),(4,5),(5,6)return [a,b,c]

a,b,c = Giveabc():d,e,f = GiveTuple():g,h,i = GiveList():

Different variations can be used to return what is required, based on our need :) Lambda Expressions (Anonymous Functions) !!!

“In Python you can define a one-line mini-functions on the fly.
Borrowed from Lisp, these so-called lambda functions can be used anywhere a function is required.”

The below is an wonderful example from the book Dive Into Python”.

>>> def f(x):...     return x*2...     >>> f(3)6>>> g = lambda x: x*2  >>> g(3)6>>> (lambda x: x*2)(3) 6


This is a lambda function that accomplishes the same thing as the normal function above it. Note the abbreviated syntax here: there are no parentheses around the argument list, and the return keyword is missing (it is implied, since the entire function can only be one expression). Also, the function has no name, but it can be called through the variable it is assigned to.

You can use a lambda function without even assigning it to a variable. This may not be the most useful thing in the world, but it just goes to show that a lambda is just an in-line function.


I had to borrow it from there because, this is the best way we can know how lambda function can be really useful for us , in a simple one-line.


To create a Modules in Python, you use the def keyword, followed by the function name and argument list, and a colon to begin the function body.

General Syntax :

def (argument_list):
….}=> Body

P.S : Indentation must be taken care

Ok , now lets see few eliminator examples of modules .

import sys

def main():print "\nTill which level do you want to see the sequence ? "n = int(sys.stdin.readline()) # read from the user fibonacci(n) # call to the method with parameter 

def fibonacci(n):a,b = 0,1for i in range(0,n):print aa,b, = b,a+b

if __name__ == '__main__':main()

Here the main method , calls the Fibonacci method , which prints the sequence of Fibonacci numbers.

A method can “RETURN” ?

As Python passes all arguments using “pass by reference” , the changes on the arguments in the method is always reflected on them .

A module can return an kind of data types , those which we had seen in the earlier post .

Keeping this in mind , here a small code which everything clear :

a, b, c = 0, 0, 0def Giveabc():a = "Hello"b = "Python"c = "!"return a,b,c #defines a tuple on the fly

def GiveTuple():a,b,c = 1,2,3return (a,b,c)

def GiveList():a,b,c = (3,4),(4,5),(5,6)return [a,b,c]

a,b,c = Giveabc():d,e,f = GiveTuple():g,h,i = GiveList():

Different variations can be used to return what is required, based on our need :) Lambda Expressions (Anonymous Functions) !!!

“In Python you can define a one-line mini-functions on the fly.
Borrowed from Lisp, these so-called lambda functions can be used anywhere a function is required.”

The below is an wonderful example from the book Dive Into Python”.

>>> def f(x):...     return x*2...     >>> f(3)6>>> g = lambda x: x*2  >>> g(3)6>>> (lambda x: x*2)(3) 6


This is a lambda function that accomplishes the same thing as the normal function above it. Note the abbreviated syntax here: there are no parentheses around the argument list, and the return keyword is missing (it is implied, since the entire function can only be one expression). Also, the function has no name, but it can be called through the variable it is assigned to.

You can use a lambda function without even assigning it to a variable. This may not be the most useful thing in the world, but it just goes to show that a lambda is just an in-line function.


I had to borrow it from there because, this is the best way we can know how lambda function can be really useful for us , in a simple one-line.


Variables can be organized in a particular pattern called Arrays .

There are four basic types of arrays :

  1. List
  2. Tuples
  3. Dicitionary
  4. Sets

LIST :

  • List is an ordered collection of variables .
  • A list is created using square brackets [ ] .
  • List is indexed , so you can accesses the objects/elements in the list using them.
  • len() , append() , insert () , del , are the few common functions which are used to operate on the list to find its length , append new elements , insert elements and delete the whole list or specific index respectively .

Examples :

#creating a list
>>> colors = ["red","green","blue",3]

#printing the contents of the list
>>> colors
['red', 'green', 'blue', 3]

# indexed access
>>> colors[0]
‘red’

# 0 is the first element , -1 is the last !
>>> colors[-1]
3

# Starting from 0 print two elements
>>> colors[0:2]
['red', 'green']

>>> colors[-2]
‘blue’

# Error !
>>> colors[-9]
Traceback (most recent call last): File “”, line 1, in ? colors[-9] IndexError: list index out of range

# Appending an element to the list >>> colors.append(‘white’)
>>> colors
['red', 'green', 'blue', 3, 'white']

# Most common mistake , while using len()
>>> colors.len()
Traceback (most recent call last): File “”, line 1, in ? colors.len() AttributeError: ‘list’ object has no attribute ‘len’ # The correct way
>>> len(colors)
5

# Most common error while deleting
>>> del colors[len(colors)]
Traceback (most recent call last): File “”, line 1, in ? del colors[len(colors)] IndexError: list assignment index out of range

# The correct way
>>> del colors[len(colors)-1]
>>> colors
['red', 'green', 'blue', 3]

# Inserting an element
>>> colors.insert(0,’black’)
>>> colors
['black', 'red', 'green', 'blue', 3]

TUPLES :

Tuples are twins brother of List , they don’t obey to you unlike his brother List , they are not flexible , you can’t modify them once defined.

To define a tuple we use commas “,” ; Parenthesis may also be used to make it more clear.

Examples :

>>> binary = ‘1′,’0′

# or
>>> binary = (‘1′,’0′)

>>> binary

# for both the output is
>>> (‘1′, ‘0′)

Rather interesting , we can group them up to form meaning full tuple

>>> ego = ‘i’,'me’,'myself’,(‘bad’,'very bad’,'worst’)

>>> ego

# o/p will be

(‘i’, ‘me’, ‘myself’, (‘bad’, ‘very bad’, ‘worst’))

DICTIONARIES :

Dictionaries cousins of lists, and they are mutable i.e once declared and defined can be modified.

Properties of dictionaries :

  • Elements in a dictionary are not bound to numbers.
  • {Key:value} pair makes up an element of a dictionary.
  • Call the key , you get the value.

Examples :

# creating
>>> places = {“Bangalore”: “India”, “NY” : “US”,”London”:”UK”}

# displaying
>>> places
{‘NY’: ‘US’, ‘Bangalore’: ‘India’, ‘London’: ‘UK’}

# retrieving
>>> places["Bangalore"]
‘India’

# note it’s case sensitive , therefore a KeyError
>>> places["bangalore"]
Traceback (most recent call last):
File “”, line 1, in
KeyError: ‘bangalore’

# resetting the value of the key
>>> places["NY"] = “India”

>>> places
{‘NY’: ‘India’, ‘Bangalore’: ‘India’, ‘London’: ‘UK’}

SETS :

An unordered “list” , which does not allow duplicate values are know as sets .

Properties of sets :

  • Elements of a set are neither bound to a number nor to a keys.
  • Are faster for huge number of items than a list or tuple and sets provide fast data manipulations.

Examples :
>>> luckyNum = set([(1,3,5,7),'lucky',(0,0,13),'unlucky'])

>>> luckyNum
set([(0, 0, 13), 'unlucky', (1, 3, 5, 7), 'lucky'])

This was just a toddler on Arrays , there are loads more to do with them :)


Simple math with python , is as easy as counting your fingers ;0)

Basic operations : The reference are been linked to wikipedia

a+b a + b\, addition
a-b a - b\, subtraction
a*b a \times b\, multiplication
a/b a \div b\, division
a//b a \div b\, floor division {only in Python 2.2 and higher versions}
a%b a \bmod b\, modulo
-a -a\, negation
abs(a) |a|\, absolute value
a**b a^b\, exponent
sqrt(a) \sqrt{a}\, square root

To use sqrt( ) , we need to explicitly import the function , to do so we follow this :

from
math import sqrt

You can also use the round () as , round( the number , number of decimal places to be rounded)

Examples :

>>> from math import sqrt

>>> sqrt(9)
3.0

>>> 3+5
8

>>> 5-6
-1

>>> -0
0

>>> 6*8
48

>>> 1**2
1

>>> 2**1
2

>>> 2**2
4

>>> 2/3
0

>>> 3/2
1

>>> 0/0
Traceback (most recent call last):
File “”, line 1, in ?
ZeroDivisionError: integer division or modulo by zero

>>> 3/0
Traceback (most recent call last):
File “”, line 1, in ?
ZeroDivisionError: integer division or modulo by zero

>>> 6/8
0

>>> 6//8
0

>>> 7/3
2

>>> 7//3
2

>>> .6/.2
2.9999999999999996

>>> .6//.2
2.0

>>> round(2.9,10)
2.8999999999999999

>>> 22/7
3

>>> 22 // 7
3

>>> 22/7
3

>>> 3.45 * 5
17.25

>>> 4-5
-1

>>> abs(-9)
9

>>> 9%7
2

Variables can be organized in a particular pattern called Arrays .

There are four basic types of arrays :

  1. List
  2. Tuples
  3. Dicitionary
  4. Sets

LIST :

  • List is an ordered collection of variables .
  • A list is created using square brackets [ ] .
  • List is indexed , so you can accesses the objects/elements in the list using them.
  • len() , append() , insert () , del , are the few common functions which are used to operate on the list to find its length , append new elements , insert elements and delete the whole list or specific index respectively .

Examples :

#creating a list
>>> colors = ["red","green","blue",3]

#printing the contents of the list
>>> colors
['red', 'green', 'blue', 3]

# indexed access
>>> colors[0]
‘red’

# 0 is the first element , -1 is the last !
>>> colors[-1]
3

# Starting from 0 print two elements
>>> colors[0:2]
['red', 'green']

>>> colors[-2]
‘blue’

# Error !
>>> colors[-9]
Traceback (most recent call last): File “”, line 1, in ? colors[-9] IndexError: list index out of range

# Appending an element to the list >>> colors.append(‘white’)
>>> colors
['red', 'green', 'blue', 3, 'white']

# Most common mistake , while using len()
>>> colors.len()
Traceback (most recent call last): File “”, line 1, in ? colors.len() AttributeError: ‘list’ object has no attribute ‘len’ # The correct way
>>> len(colors)
5

# Most common error while deleting
>>> del colors[len(colors)]
Traceback (most recent call last): File “”, line 1, in ? del colors[len(colors)] IndexError: list assignment index out of range

# The correct way
>>> del colors[len(colors)-1]
>>> colors
['red', 'green', 'blue', 3]

# Inserting an element
>>> colors.insert(0,’black’)
>>> colors
['black', 'red', 'green', 'blue', 3]

TUPLES :

Tuples are twins brother of List , they don’t obey to you unlike his brother List , they are not flexible , you can’t modify them once defined.

To define a tuple we use commas “,” ; Parenthesis may also be used to make it more clear.

Examples :

>>> binary = ‘1′,’0′

# or
>>> binary = (‘1′,’0′)

>>> binary

# for both the output is
>>> (‘1′, ‘0′)

Rather interesting , we can group them up to form meaning full tuple

>>> ego = ‘i’,'me’,'myself’,(‘bad’,'very bad’,'worst’)

>>> ego

# o/p will be

(‘i’, ‘me’, ‘myself’, (‘bad’, ‘very bad’, ‘worst’))

DICTIONARIES :

Dictionaries cousins of lists, and they are mutable i.e once declared and defined can be modified.

Properties of dictionaries :

  • Elements in a dictionary are not bound to numbers.
  • {Key:value} pair makes up an element of a dictionary.
  • Call the key , you get the value.

Examples :

# creating
>>> places = {“Bangalore”: “India”, “NY” : “US”,”London”:”UK”}

# displaying
>>> places
{‘NY’: ‘US’, ‘Bangalore’: ‘India’, ‘London’: ‘UK’}

# retrieving
>>> places["Bangalore"]
‘India’

# note it’s case sensitive , therefore a KeyError
>>> places["bangalore"]
Traceback (most recent call last):
File “”, line 1, in
KeyError: ‘bangalore’

# resetting the value of the key
>>> places["NY"] = “India”

>>> places
{‘NY’: ‘India’, ‘Bangalore’: ‘India’, ‘London’: ‘UK’}

SETS :

An unordered “list” , which does not allow duplicate values are know as sets .

Properties of sets :

  • Elements of a set are neither bound to a number nor to a keys.
  • Are faster for huge number of items than a list or tuple and sets provide fast data manipulations.

Examples :
>>> luckyNum = set([(1,3,5,7),'lucky',(0,0,13),'unlucky'])

>>> luckyNum
set([(0, 0, 13), 'unlucky', (1, 3, 5, 7), 'lucky'])

This was just a toddler on Arrays , there are loads more to do with them :)


Simple math with python , is as easy as counting your fingers ;0)

Basic operations : The reference are been linked to wikipedia

a+b a + b\, addition
a-b a - b\, subtraction
a*b a \times b\, multiplication
a/b a \div b\, division
a//b a \div b\, floor division {only in Python 2.2 and higher versions}
a%b a \bmod b\, modulo
-a -a\, negation
abs(a) |a|\, absolute value
a**b a^b\, exponent
sqrt(a) \sqrt{a}\, square root

To use sqrt( ) , we need to explicitly import the function , to do so we follow this :

from
math import sqrt

You can also use the round () as , round( the number , number of decimal places to be rounded)

Examples :

>>> from math import sqrt

>>> sqrt(9)
3.0

>>> 3+5
8

>>> 5-6
-1

>>> -0
0

>>> 6*8
48

>>> 1**2
1

>>> 2**1
2

>>> 2**2
4

>>> 2/3
0

>>> 3/2
1

>>> 0/0
Traceback (most recent call last):
File “”, line 1, in ?
ZeroDivisionError: integer division or modulo by zero

>>> 3/0
Traceback (most recent call last):
File “”, line 1, in ?
ZeroDivisionError: integer division or modulo by zero

>>> 6/8
0

>>> 6//8
0

>>> 7/3
2

>>> 7//3
2

>>> .6/.2
2.9999999999999996

>>> .6//.2
2.0

>>> round(2.9,10)
2.8999999999999999

>>> 22/7
3

>>> 22 // 7
3

>>> 22/7
3

>>> 3.45 * 5
17.25

>>> 4-5
-1

>>> abs(-9)
9

>>> 9%7
2

Next Page »