January 2009


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

Variables , can be considered as cups , which can had different things , it may be water , juice , or rather anything you like.

To be more technical , a variable is a name that may be bound to a value , and need not remain the same.

They can be numerical , char , strings , combination of them , interestingly Python also supports complex numbers ! {P+iJ}

Examples :

Numericals :

myNum = 7

print myNum , would output “7″ on the terminal .

You also assign multiple variables like :
myNum = urNum = hisNum = 7
Characters :

alpha = a
beta = b

Stings :

myName = “hemanth”
myName = ‘hemanth’
myName = “‘hemanth”‘

{Yes it can be single , double and even triple quoted !!}

Variables , can be considered as cups , which can had different things , it may be water , juice , or rather anything you like.

To be more technical , a variable is a name that may be bound to a value , and need not remain the same.

They can be numerical , char , strings , combination of them , interestingly Python also supports complex numbers ! {P+iJ}

Examples :

Numericals :

myNum = 7

print myNum , would output “7″ on the terminal .

You also assign multiple variables like :
myNum = urNum = hisNum = 7
Characters :

alpha = a
beta = b

Stings :

myName = “hemanth”
myName = ‘hemanth’
myName = “‘hemanth”‘

{Yes it can be single , double and even triple quoted !!}

What is Python ?
You guessed it wrong , if you are thinking of this :

Python is a great object-oriented, interpreted, and interactive programming language.



Why Python?
Cleaner and more elegant , scripting language.

{You need to taste Honey , to know how it feels , same way you need to try python to know why python.}

The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren’t special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one– and preferably only one –obvious way to do it.
Although that way may not be obvious at first unless you’re Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it’s a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea — let’s do more of those!

How Python?
Steps:
1. Create a file with .py extension
2. chmod a+x on it.
3. python

Nuts and blots of Python :
{Shall i rather call it , skin and teeth of python ;) }

Python holds a record , in the world of programing language with one of the shortest “HELLO WORLD” program.
In the terminal type “python” , to start the interpreter , there you type in the code

print “Hello ,World !!”

Thats it , you said Hello to the whole World !!

What is Python ?
You guessed it wrong , if you are thinking of this :

Python is a great object-oriented, interpreted, and interactive programming language.



Why Python?
Cleaner and more elegant , scripting language.

{You need to taste Honey , to know how it feels , same way you need to try python to know why python.}

The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren’t special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one– and preferably only one –obvious way to do it.
Although that way may not be obvious at first unless you’re Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it’s a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea — let’s do more of those!

How Python?
Steps:
1. Create a file with .py extension
2. chmod a+x on it.
3. python

Nuts and blots of Python :
{Shall i rather call it , skin and teeth of python ;) }

Python holds a record , in the world of programing language with one of the shortest “HELLO WORLD” program.
In the terminal type “python” , to start the interpreter , there you type in the code

print “Hello ,World !!”

Thats it , you said Hello to the whole World !!

I had not written , something colorful like this from a long time , have tried to tie up all the basics in a single code.
Say i name it as fun.sh , and execute it , lets see what happens :O)

#!/bin/bash

# Variable(s)
user=”";

# Function,can be defined without the function keyword !!
# Simple function to “read” user input

read_info()
{
echo “What is your name ? “
# read data from keyboard to user variable
read user
# Say hi to the user
echo “Hi $user”
}
ask()
{
echo “Which OS do you like ?”
echo “1) Linux”
echo “2) Windows”
echo “3) MAC”
echo “4) None”
echo “5) You wont tell me”

read case;

case $case in
1) echo “The best , Happy Hacking :);;
2) echo “Who needs Gates and Windows , when you have freedom “;;
3) echo “You need an Apple?”;;
4) echo“None!!!, What are you using now then!”;;
5) exit
esac

}

# Note the spaces in after if condition and within [ ] , if you are using
# if [ $# -eq 0 ] or better go for if test $# -eq 0
# $# gives number fo command line args

if test $# -eq 0
then
echo “Number of command line arguments is $# !!”
else
# loop till the end of arguments and echo themall using “for” loop

echo “There are $# number of agrs they are {using for loop} : “
for arg in $*
do
echo $arg
done

# We can also do this:
# for args in “$@”
# do
# echo ${args}
# done

#
# loop till the end of arguments and echo themall using “while” loop

echo “There are $# number of agrs they are {using while loop} : “
while [ -n "$1" ]
do
echo $1
shift
# Yes,shift can be used to parse through the command line array
done

fi

read_info
ask

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
$ ./fun 1 2 3

Output :

There are 3 number of agrs they are {using for loop} :
1
2
3
There are 3 number of agrs they are {using while loop} :
1
2
3
Waht is your name ?
hemanth
Hi hemanth
Which OS do you like ?
1) Linux
2) Windows
3) MAC
4) None
5) You wont tell me
1
The best , Happy Hacking :)

I had not written , something colorful like this from a long time , have tried to tie up all the basics in a single code.
Say i name it as fun.sh , and execute it , lets see what happens :O)

#!/bin/bash

# Variable(s)
user=”";

# Function,can be defined without the function keyword !!
# Simple function to “read” user input

read_info()
{
echo “What is your name ? “
# read data from keyboard to user variable
read user
# Say hi to the user
echo “Hi $user”
}
ask()
{
echo “Which OS do you like ?”
echo “1) Linux”
echo “2) Windows”
echo “3) MAC”
echo “4) None”
echo “5) You wont tell me”

read case;

case $case in
1) echo “The best , Happy Hacking :);;
2) echo “Who needs Gates and Windows , when you have freedom “;;
3) echo “You need an Apple?”;;
4) echo“None!!!, What are you using now then!”;;
5) exit
esac

}

# Note the spaces in after if condition and within [ ] , if you are using
# if [ $# -eq 0 ] or better go for if test $# -eq 0
# $# gives number fo command line args

if test $# -eq 0
then
echo “Number of command line arguments is $# !!”
else
# loop till the end of arguments and echo themall using “for” loop

echo “There are $# number of agrs they are {using for loop} : “
for arg in $*
do
echo $arg
done

# We can also do this:
# for args in “$@”
# do
# echo ${args}
# done

#
# loop till the end of arguments and echo themall using “while” loop

echo “There are $# number of agrs they are {using while loop} : “
while [ -n "$1" ]
do
echo $1
shift
# Yes,shift can be used to parse through the command line array
done

fi

read_info
ask

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
$ ./fun 1 2 3

Output :

There are 3 number of agrs they are {using for loop} :
1
2
3
There are 3 number of agrs they are {using while loop} :
1
2
3
Waht is your name ?
hemanth
Hi hemanth
Which OS do you like ?
1) Linux
2) Windows
3) MAC
4) None
5) You wont tell me
1
The best , Happy Hacking :)

Next Page »