Functions

The Concept of a Functions Pictorially
Explain the concept of a functions pictorially
Example
Explain the concept of a functions pictorially
Solution
  1. It is not a function since 3 and 6 remain unmapped.
  2. It is not a function because 2 has two images ( 5 and 6)
  3. It is a function because each of 1, 2, 3 and 4 is connected to exactly one of 5, 6 or 7.
Functions
Identify functions
TESTING FOR FUNCTIONS:
If a line parallel to the y-axis is drawn and it passes through two or more points on the graph of the relation then the relation is not a function.
If it passes through only one point then the relation is a function
Example
Identify functions
Exercise


1. Which of the following relations are functions?
2. Let A = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
and B ={ 2, 3, 5, 7 }
Draw an arrow diagram to illustrate the relation “ is a multiple of ‘ is it a function ? why?
3. let A = {1,-1 ,2,-2} and
B = {1, 2, 3, 4 } which of the following relations are functions ?
  1. { ( x , y ) : x < y }
  2. { ( x , y ) : x > y}
  3. { ( x , y ) : y = x2}

Domain and Range of a Function
The Domain of a Function
State the domain of a function
If y = f (x),that is y is a function of x ,then domain is a set of x values that satisfy the equation y = f (x).
The Range of Function
State the range of function
If y = f (x),that is y is a function of x , then therange is a set of y value satisfying the equation y = f (x).
Example
State the range of function
Solution
f (x) = y = 3x -5
When x = -2
f(-2) = y = 3x(-2)-5 = -11 , so (x,y)=(-2,-11)
f(3) =y= 3×3-5 = 4, so when x = 3 , y = 4
Therefore y is found in between – 11 and 4
Range ={ y: – 11≤ y≤ 4}
Example
State the range of function
Solutions;
Domain = all real numbers
Range:
f(x) = y = x2 – 3
Make x the subject
y+ 3 = x2
Exercise


1. For each of the following functions, state the domain and range
  1. f(x) = 2x + 7 for 2 £ x £ 5
  2. f(x) = x – 1 for -4 £ x £ 6
  3. f(x) = 5 – 3x such that -2 £ f(x) < 8
2. for each of the following functions state the domain and range
  1. f(x) = x2
  2. f(x) = x2+2
  3. f(x) = 2x + 1
  4. f(x) = 1 – x2
Exercise


1.The range of the function
f(x) 3 – 2x for 0 ³0 x £7 is;
  1. y: -18£ y £3
  2. y: -3£ y £18
  3. y: 3 £y £18
  4. y: -18 £ y £-3
2. The range of the function
f(x)=2x+1 is y: -3£ y £17 what is the domain of this function?
  1. x: – 3£ x £17
  2. x: – 2£ x £8
  3. x: -17 £ x £3
3.Which of the following relations represents a function:
  1. R = (x, y) : y = for x ≥0
  2. R= (x, y) : y= x-2 for x ≥0
  3. R= (x, y) : y = for x ≥0 and y ≥0
  4. R= (x, y) : x = 7 for all values of y
4.Which of the following relations is a function:
  1. R = (x, y): -2 £ x £6, 3 £ y<8 and x<y, Where both x and y are integers
  2. R= (x, y): -2 £ x £6, 3 £ y<8 and x<y, Where both x and y are integers
  3. R= (x,y): y = √(x+2) for x ≥-2.
  4. R = (x, y): y=√(2-x) for x ≤2 and y ≤0
5.Let f (x) = x+ 1. Which of the following is true?
  1. f (-2) < f (0)
  2. f (3)> f (-4)
  3. f (-5) = f (5)
  4. The function crosses , y – axis at 1
One to one and many to one functions:
One to functions;
A one to one function is a function in which one element from the domain is mapped to exactly one element in the range:
That is if a ≠b then f (a) ≠f (b)
Many to one function;
This is another type of function with a property that two or more elements from the domain can have one image (the same image).
Examples of one to one functions
  1. f (x) = 3x + 2
  2. f (x) = x + 6
  3. f (x) = x3 + 1 etc
Examples of many to one function
  1. f(x) = x2 +1
  2. f(x) = x4 – 2 etc
NB. All functions with odd degrees are one to one function and all functions with even degrees are many to one functions.
Example
State the range of function
Example
State the range of function
Q = {-1, 0, 1, 2, 3}
g(x) = x + 1, is g one to one function?
Solution:
g (x) is one to one function because every element in P has only one image in Q
NB: In example 1, f(x) is not a one to one function because -2 and 2 in A have the same image in B, that is 4 is the image of both 2 and -2.
Also 1 is the image of both 1 nd -1.
Example
State the range of function
Solution:
Draw a line parallel to the x axis and see if it crosses the graph at more than one points. If it does, then, the function is many to one and if it crosses at only one point then the graph represents a one to one function.

Graphic Function
Graphs of Functions
Draw graphs of functions
Many functions are given as equations, this being the case, drawing a graph of the equation is obtaining the graph of the equation which defines the function.
Note that, you can draw a graph of a function if you know the limits of its independent variables as well as dependent variables. i.e you must know the domain and range of the given function.
Example
Draw graphs of functions
  1. f(x) = 3x -1
  2. g (x) = x2 – 2x -1
  3. h (x) = x3
Solution
f(x) = 3x – 1
The domain and range of f are the sets of all real numbers
f(x) = y = 3x – 1
So y = 3x – 1
Table of value :
g(x) = x2 -2x -1
y=x2-2-1
a=-1, b=-2 1 and c=-1
forh(x) = x3
Solution:
The first graph is the graph of linear function, the second one is called the graph of a quadratic function and the last graph is for cubic function.
Example
Draw graphs of functions
f(x) = -1 + 6x-x2
Solution:
a=-1, b=6, c=-1
Exercise


1.Which of the following are one to one function?
  1. f(x) = 3x – x2
  2. g (x) = x-1
  3. k(x) =x3+1
  4. f(x) =x+x2+x3
  5. k(x)=x4
2. Draw the graph of the following functions:
  1. f(x) = 3x – x2
  2. h (x) = x+1
  3. g(x) =x 3– x 2+3
3. At what values of x does the graph of the function f(x) = x2+x-6 cross thex- axis?
  1. x=-3 and x=7
  2. x=8 and x=-6
  3. x=-3 and x=2
  4. x=4 and x=-1
4. Which of the following function is one to one function?
  1. f(x)=x2+2
  2. f(x) =x4-x2
  3. f(x)=x5-7
  4. f(x)=x2+x+2
Functions with more than one part.
Some functions consist of more than one part. When drawing their graphs draw the parts separately.
If the graph includes an end point, indicate it with a solid dot if it does not include the end point indicate it with a hollow dot.
E.g. draw the graphs of the functions
(a) F(x) x+1 for x>0
(b) f(x)=x+1for x³0
Example
Draw graphs of functions
(c) Sketch its graph
(d) State the domain and range of f
Solution:
Exercise


Absolute value functions (Modulus functions)
The absolute function is defined
Table of values
Example
Draw graphs of functions
Solution
table of values.
Step functions:
Example
Draw graphs of functions
Note that the graph obtained is like steps such functions are called steps functions
Exercise


1. Draw the graph of

Inverse of a Function
The Inverse of a Function
Explain the inverse of a function
In the discussion about relation we defined the inverse of relation.
It is true that the inverse of the relation is also a relation.
Similarly because a function is also relation then every function has its inverse
The Inverse of a Function Pictorially
Show the inverse of a function pictorially
According to the definition of function the inverse of a function is also a function if and only if the function is one to one
The Inverse of a Function
Find the inverse of a function
If the function f is one to one function given by an equation, then its inverse is denoted by f-1 which is obtained by inter changing the variables x and y then making y the subject of the formula.
I.e. If y=f(x), then x = f-1 (y)
Example
Find the inverse of a function
  1. F(x) = 3x-6
  2. F(x) =x3
Solution:
A Graph of the Inverse of a Function
Draw a graph of the inverse of a function
Example
Draw a graph of the inverse of a function
solution:
Domain = {All real numbers}
Range = {All real numbers}
NB: if a function f takes a domain A to a range B, then the inverse f-1 takes B back to A.
Hence the domain of f-1 is the range of f, and the range of f-1 is the domain of f.
The Domain and Range of Inverse of Functions
State the domain and range of inverse of functions
Example
State the domain and range of inverse of functions
Solutions:
1. Given that f(x) = x2-2[x] +3, what is the value of f (-4)?

PYTHON STRINGS

PYTHON STRINGS

Python string is a built-in type text sequence. It is used to handle textual data in python. Python Strings are immutable sequences of Unicode points. Creating Strings are simplest and easy to use in Python.

We can simply create Python String by enclosing a text in single as well as double quotes. Python treat both single and double quotes statements same.

Accessing Python Strings
In Python, Strings are stored as individual characters in a contiguous memory location.
The benefit of using String is that it can be accessed from both the directions (forward and backward).
Both forward as well as backward indexing are provided using Strings in Python.
Forward indexing starts with 0,1,2,3,….
Backward indexing starts with -1,-2,-3,-4,….

Example

str[0]=’P’=str[-6] ,
str[1]=’Y’ = str[-5]  ,
str[2] = ‘T’ = str[-4]  , 
str[3] = ‘H’ = str[-3] 
str[4] = ‘O’ = str[-2]  , 
str[5] = ‘N’ = str[-1]. 

Python String Example
Here, we are creating a simple program to retrieve String in reverse as well as normal form.

name=”Rajat” 
length=len(name) 
i=0 
for n in range(-1,(-length-1),-1): 
    print name[i],”\t”,name[n] 
    i+=1 
Output:
>>>
R       t
a       a
j       j
a       a
t       R
>>>

Python Strings Operators
To perform operation on string, Python provides basically 3 types of Operators that are given below.

Basic Operators.
Membership Operators.
Relational Operators.

Python String Basic Operators
There are two types of basic operators in String “+” and “*”.

String Concatenation Operator (+)
The concatenation operator (+) concatenates two Strings and creates a new String.

Python String Concatenation Example
>>> “ratan” + “jaiswal”
Output:
‘ratanjaiswal’
>>>

Expression
Output
’10’ + ’20’
‘1020’
“s” + “007”
‘s007’
‘abcd123’ + ‘xyz4’
‘abcd123xyz4’

NOTE: Both the operands passed for concatenation must be of same type, else it will show an error.

Eg:
‘abc’ + 3
>>>
output:
Traceback (most recent call last):
  File “”, line 1, in
    ‘abc’ + 3
TypeError: cannot concatenate ‘str’ and ‘int’ objects
>>>

Python String Replication Operator (*)
Replication operator uses two parameters for operation, One is the integer value and the other one is the String argument.

The Replication operator is used to repeat a string number of times. The string will be repeated the number of times which is given by the integer value.

Python String Replication Example
>>> 5*”Vimal” 
Output:
‘VimalVimalVimalVimalVimal’

Expression
Output
“soono”*2
‘soonosoono’
3*’1′
‘111’
‘$’*5
‘$$$$$’

NOTE: We can use Replication operator in any way i.e., int * string or string * int. Both the parameters passed cannot be of same type.

Python String Membership Operators
Membership Operators are already discussed in the Operators section. Let see with context of String.

There are two types of Membership operators
1) in:”in” operator returns true if a character or the entire substring is present in the specified string, otherwise false.

2) not in:”not in” operator returns true if a character or entire substring does not exist in the specified string, otherwise false.

Python String membership operator Example

>>> str1=”javatpoint” 
>>> str2=’sssit’ 
>>> str3=”seomount” 
>>> str4=’java’ 
>>> st5=”it” 
>>> str6=”seo” 
>>> str4 in str1 
True 
>>> str5 in str2 
>>> st5 in str2 
True 
>>> str6 in str3 
True 
>>> str4 not in str1 
False 
>>> str1 not in str4 
True 

Python Relational Operators
All the comparison (relational) operators i.e., (=,==,!=,) are also applicable for strings. The Strings are compared based on the ASCII value or Unicode(i.e., dictionary Order).

Python Relational Operators Example
>>> “RAJAT”==”RAJAT” 
True 
>>> “afsha”>=’Afsha’ 
True 
>>> “Z””z” 
True 

Explanation:
The ASCII value of a is 97, b is 98, c is 99 and so on. The ASCII value of A is 65,B is 66,C is 67 and so on. The comparison between strings are done on the basis on ASCII value.

Python String Slice Notation
Python String slice can be defined as a substring which is the part of the string. Therefore further substring can be obtained from a string.

There can be many forms to slice a string, as string can be accessed or indexed from both the direction and hence string can also be sliced from both the directions.

Python String Slice Syntax
[startIndex:endIndex], 
[:endIndex], 
[startIndex:] 

Python String Slice Example 1
>>> str=”Nikhil” 
>>> str[0:6] 
‘Nikhil’ 
>>> str[0:3] 
‘Nik’ 
>>> str[2:5] 
‘khi’ 
>>> str[:6] 
‘Nikhil’ 
>>> str[3:] 
‘hil’ 

Note: startIndex in String slice is inclusive whereas endIndex is exclusive.

String slice can also be used with Concatenation operator to get whole string.

Python String Slice Example 2
>>> str=”Mahesh” 
>>> str[:6]+str[6:] 
‘Mahesh’ 
//here 6 is the length of the string.

Python String Functions and Methods
Python provides various predefined or built-in string functions. They are as follows:

capitalize()
It capitalizes the first character of the String.
count(string,begin,end)
It Counts number of times substring occurs in a String between begin and end index.
endswith(suffix ,begin=0,end=n)
It returns a Boolean value if the string terminates with given suffix between begin and end.
find(substring ,beginIndex, endIndex)
It returns the index value of the string where substring is found between begin index and end index.
index(subsring, beginIndex, endIndex)
It throws an exception if string is not found and works same as find() method.
isalnum()
It returns True if characters in the string are alphanumeric i.e., alphabets or numbers and there is at least 1 character. Otherwise it returns False.
isalpha()
It returns True when all the characters are alphabets and there is at least one character, otherwise False.
isdigit()
It returns True if all the characters are digit and there is at least one character, otherwise False.
islower()
It returns True if the characters of a string are in lower case, otherwise False.
isupper()
It returns False if characters of a string are in Upper case, otherwise False.
isspace()
It returns True if the characters of a string are whitespace, otherwise false.
len(string)
It returns the length of a string.
lower()
It converts all the characters of a string to Lower case.
upper()
It converts all the characters of a string to Upper Case.
startswith(str ,begin=0,end=n)
It returns a Boolean value if the string starts with given str between begin and end.
swapcase()
It inverts case of all characters in a string.
lstrip()
It removes all leading whitespace of a string and can also be used to remove particular character from leading.
rstrip()
It removes all trailing whitespace of a string and can also be used to remove particular character from trailing.

Python String capitalize() Method Example
This method capitalizes the first character of the String.

1.    >>> ‘abc’.capitalize() 
Output:
‘Abc’

Python String count(string) Method Example
This method counts number of times substring occurs in a String between begin and end index.

msg = “welcome to sssit”; 
substr1 = “o”; 
print  msg.count(substr1, 4, 16) 
substr2 = “t”; 
print  msg.count(substr2) 
Output:
>>>
2
2
>>>

Python String endswith(string) Method Example
This method returns a Boolean value if the string terminates with given suffix between begin and end.

string1=”Welcome to SSSIT”; 
substring1=”SSSIT”; 
substring2=”to”; 
substring3=”of”; 
print string1.endswith(substring1); 
print string1.endswith(substring2,2,16); 
print string1.endswith(substring3,2,19); 
print string1.endswith(substring3); 
Output:
>>>
True
False
False
False
>>>

Python String find(string) Method Example
This method returns the index value of the string where substring is found between begin index and end index.

str=”Welcome to SSSIT”; 
substr1=”come”; 
substr2=”to”; 
print str.find(substr1); 
print str.find(substr2); 
print str.find(substr1,3,10); 
print str.find(substr2,19); 

Output:
>>>
3
8
3
-1
>>>

Python String index() Method Example
This method returns the index value of the string where substring is found between begin index and end index.

str=”Welcome to world of SSSIT”; 
substr1=”come”; 
substr2=”of”; 
print str.index(substr1); 
print str.index(substr2); 
print str.index(substr1,3,10); 
print str.index(substr2,19); 

Output:
>>>
3
17
3
Traceback (most recent call last):
  File “C:/Python27/fin.py”, line 7, in
    print str.index(substr2,19);
ValueError: substring not found
>>>

Python String isalnum() Method Example
This method returns True if characters in the string are alphanumeric i.e., alphabets or numbers and there is at least 1 character. Otherwise it returns False.

str=”Welcome to sssit”; 
    print str.isalnum(); 
str1=”Python47″; 
print str1.isalnum(); 

Output:
>>>
False
True
>>>

Python String isalpha() Method Example
It returns True when all the characters are alphabets and there is at least one character, otherwise False.

string1=”HelloPython”;  
 # Even space is not allowed 
print string1.isalpha(); 
string2=”This is Python2.7.4″ 
print string2.isalpha(); 

Output:
>>>
True
False
>>>

Python String isdigit() Method Example
This method returns True if all the characters are digit and there is at least one character, otherwise False.

string1=”HelloPython”;  
print string1.isdigit(); 
string2=”98564738″ 
print string2.isdigit(); 

Output:
>>>
False
True
>>>

Python String islower() Method Example
This method returns True if the characters of a string are in lower case, otherwise False.

string1=”Hello Python”;  
print string1.islower(); 
string2=”welcome to ” 
print string2.islower(); 

Output:
>>>
False
True
>>>

Python String isupper() Method Example
This method returns False if characters of a string are in Upper case, otherwise False.

string1=”Hello Python”;  
print string1.isupper(); 
string2=”WELCOME TO” 
print string2.isupper(); 

Output:
>>>
False
True
>>>

Python String isspace() Method Example
This method returns True if the characters of a string are whitespace, otherwise false.

string1=”    “;  
print string1.isspace(); 
string2=”WELCOME TO WORLD OF PYT” 
print string2.isspace(); 

Output:
>>>
True
False
>>>

Python String len(string) Method Example
This method returns the length of a string.

string1=”    “;  
print len(string1); 
string2=”WELCOME TO SSSIT” 
print len(string2); 

Output:
>>>
4
16
>>>

Python String lower() Method Example
It converts all the characters of a string to Lower case.

string1=”Hello Python”;  
print string1.lower(); 
string2=”WELCOME TO SSSIT” 
print string2.lower(); 

Output:
>>>
hello python
welcome to sssit
>>>

Python String upper() Method Example
This method converts all the characters of a string to upper case.

string1=”Hello Python”;  
print string1.upper(); 
string2=”welcome to SSSIT” 
print string2.upper(); 

Output:
>>>
HELLO PYTHON
WELCOME TO SSSIT
>>>

Python String startswith(string) Method Example
This method returns a Boolean value if the string starts with given str between begin and end.

string1=”Hello Python”;  
print string1.startswith(‘Hello’); 
string2=”welcome to SSSIT” 
print string2.startswith(‘come’,3,7); 

Output:
>>>
True
True
>>>

Python String swapcase() Method Example
It inverts case of all characters in a string.

string1=”Hello Python”;  
print string1.swapcase(); 
string2=”welcome to SSSIT” 
print string2.swapcase(); 

Output:
>>>
hELLO pYTHON
WELCOME TO sssit
>>>

Python String lstrip() Method Example
It removes all leading whitespace of a string and can also be used to remove particular character from leading.

string1=”    Hello Python”;  
print string1.lstrip(); 
string2=”@@@@@@@@welcome to SSSIT” 
print string2.lstrip(‘@’); 

Output:
>>>
Hello Python
welcome to world to SSSIT
>>>

Python String rstrip() Method Example
It removes all trailing whitespace of a string and can also be used to remove particular character from trailing.

string1=”    Hello Python     “;  
print string1.rstrip(); 
string2=”@welcome to SSSIT!!!” 
print string2.rstrip(‘!’); 

Output:
>>>
          Hello Python
@welcome to SSSIT
>>> 

 

Python List

Python List

Python list is a data structure which is used to store various types of data.In Python, lists are mutable i.e., Python will not create a new list if we modify an element of the list.

It works as a container that holds other objects in a given order. We can perform various operations like insertion and deletion on list.A list can be composed by storing a sequence of different type of values separated by commas.

Python list is enclosed between square([]) brackets and elements are stored in the index basis with starting index 0.

Python List Example
data1=[1,2,3,4]; 
data2=[‘x’,’y’,’z’]; 
data3=[12.5,11.6]; 
data4=[‘raman’,’rahul’]; 
data5=[]; 
data6=[‘abhinav’,10,56.4,’a’]; 

A list can be created by putting the value inside the square bracket and separated by comma.

Python List Syntax
=[value1,value2,value3,…,valuen]; 

Syntax to Access Python List
[index] 
Python allows us to access value from the list by various ways.

Python Accessing List Elements Example
data1=[1,2,3,4]; 
data2=[‘x’,’y’,’z’]; 
print data1[0] 
print data1[0:2] 
print data2[-3:-1] 
print data1[0:] 
print data2[:2] 

Output:
>>>
>>>
1
[1, 2]
[‘x’, ‘y’]
[1, 2, 3, 4]
[‘x’, ‘y’]
>>>

Elements in a Lists:
Following are the pictorial representation of a list. We can see that it allows to access elements from both end (forward and backward).

Data=[1,2,3,4,5]; 

Data[0]=1=Data[-5] ,
Data[1]=2=Data[-4] ,
Data[2]=3=Data[-3] ,  
Date[3]=4=Data[-2] ,
Data[4]=5=Data[-1]. 

Note: Internal Memory Organization:
List do not store the elements directly at the index. In fact a reference is stored at each index which subsequently refers to the object stored somewhere in the memory. This is due to the fact that some objects may be large enough than other objects and hence they are stored at some other memory location.

Python List Operations
Apart from creating and accessing elements from the list, Python allows us to perform various other operations on the list. Some common operations are given below

a) Adding Python Lists
In Python, lists can be added by using the concatenation operator(+) to join two lists.

Add lists Example 1
list1=[10,20] 
    list2=[30,40] 
    list3=list1+list2 
    print list3 

Output:
>>>  
    [10, 20, 30, 40] 
    >>> 

Note: ‘+’operator implies that both the operands passed must be list else error will be shown.

Add lists Example 2
list1=[10,20] 
list1+30 
print list1 

Output:
Traceback (most recent call last): 
        File “C:/Python27/lis.py”, line 2, in  
            list1+30 

b) Python Replicating lists
Replicating means repeating, It can be performed by using ‘*’ operator by a specific number of time.

Python list Replication Example
list1=[10,20] 
print list1*1 

Output:
>>>  
[10, 20] 
>>> 

c)Python List Slicing
A subpart of a list can be retrieved on the basis of index. This subpart is known as list slice. This feature allows us to get sub-list of specified start and end index.

Python List Slicing Example
list1=[1,2,4,5,7] 
print list1[0:2] 
print list1[4] 
list1[1]=9 
print list1 

Output:
>>>  
[1, 2] 

[1, 9, 4, 5, 7] 
>>> 

Note: If the index provided in the list slice is outside the list, then it raises an IndexError exception.

Python List Other Operations
Apart from above operations various other functions can also be performed on List such as Updating, Appending and Deleting elements from a List.

Python Updating List
To update or change the value of particular index of a list, assign the value to that particular index of the List.

Python Updating List Example
data1=[5,10,15,20,25] 
print “Values of list are: ” 
print data1 
data1[2]=”Multiple of 5″ 
print “Values of list are: ” 
print data1 

Output:
>>>  
Values of list are:  
[5, 10, 15, 20, 25] 
Values of list are:  
[5, 10, ‘Multiple of 5’, 20, 25] 
>>> 

Appending Python List
Python provides, append() method which is used to append i.e., add an element at the end of the existing elements.

Python Append List Example

list1=[10,”rahul”,’z’] 
print “Elements of List are: ” 
print list1 
list1.append(10.45) 
print “List after appending: ” 
print list1 

Output:
>>>  
Elements of List are:  
[10, ‘rahul’, ‘z’] 
List after appending:  
[10, ‘rahul’, ‘z’, 10.45] 
>>> 

Deleting Elements
In Python, del statement can be used to delete an element from the list. It can also be used to delete all items from startIndex to endIndex.

Python delete List Example
list1=[10,’rahul’,50.8,’a’,20,30] 
print list1 
del list1[0] 
print list1 
del list1[0:3] 
print list1 

Output:
>>>  
[10, ‘rahul’, 50.8, ‘a’, 20, 30] 
[‘rahul’, 50.8, ‘a’, 20, 30] 
[20, 30] 
>>> 

Python lists Method
Python provides various Built-in functions and methods for Lists that we can apply on the list.

Following are the common list functions.
Function
Description
min(list)
It returns the minimum value from the list given.
max(list)
It returns the largest value from the given list.
len(list)
It returns number of elements in a list.
cmp(list1,list2)
It compares the two list.
list(sequence)
It takes sequence types and converts them to lists.

Python List min() method Example
This method is used to get min value from the list.

list1=[101,981,’abcd’,’xyz’,’m’] 
list2=[‘aman’,’shekhar’,100.45,98.2] 
print “Minimum value in List1: “,min(list1) 
print “Minimum value in List2: “,min(list2) 

Output:
>>>  
Minimum value in List1:  101 
Minimum value in List2:  98.2 
>>> 

Python List max() method Example
This method is used to get max value from the list.

list1=[101,981,’abcd’,’xyz’,’m’] 
list2=[‘aman’,’shekhar’,100.45,98.2] 
print “Maximum value in List : “,max(list1) 
print “Maximum value in List : “,max(list2) 

Output:
>>>  
Maximum value in List :  xyz 
Maximum value in List :  shekhar 
>>> 

Python List len() method Example
This method is used to get length of the the list.
list1=[101,981,’abcd’,’xyz’,’m’] 
list2=[‘aman’,’shekhar’,100.45,98.2] 
print “No. of elements in List1: “,len(list1) 
print “No. of elements in List2: “,len(list2) 

Output:
>>>  
No. of elements in List1 :  5 
No. of elements in List2 :  4 
>>> 

Python List cmp() method Example

Explanation: If elements are of the same type, perform the comparison and return the result. If elements are different types, check whether they are numbers.
If numbers, perform comparison.
If either element is a number, then the other element is returned.
Otherwise, types are sorted alphabetically .
If we reached the end of one of the lists, the longer list is “larger.” If both list are same it returns 0.

Python List cmp() method Example

list1=[101,981,’abcd’,’xyz’,’m’] 
list2=[‘aman’,’shekhar’,100.45,98.2] 
list3=[101,981,’abcd’,’xyz’,’m’] 
print cmp(list1,list2) 
print cmp(list2,list1) 
print cmp(list3,list1) 

Output:
>>>  
-1 


>>> 

Python List list(sequence) method Example
This method is used to form a list from the given sequence of elements.

seq=(145,”abcd”,’a’) 
data=list(seq) 
print “List formed is : “,data 

Output:
>>>  
List formed is :  [145, ‘abcd’, ‘a’] 
>>> 

There are following built-in methods of List

Methods
Description
index(object)
It returns the index value of the object.
count(object)
It returns the number of times an object is repeated in list.
pop()/pop(index)
It returns the last object or the specified indexed object. It removes the popped object.
insert(index,object)
It inserts an object at the given index.
extend(sequence)
It adds the sequence to existing list.
remove(object)
It removes the object from the given List.
reverse()
It reverses the position of all the elements of a list.
sort()
It is used to sort the elements of the List.

Python List index() Method Example
data = [786,’abc’,’a’,123.5] 
print “Index of 123.5:”, data.index(123.5) 
print “Index of a is”, data.index(‘a’) 

Output:
>>>  
Index of 123.5 : 3 
Index of a is 2 
>>> 

Python List count(object) Method Example
data = [786,’abc’,’a’,123.5,786,’rahul’,’b’,786] 
print “Number of times 123.5 occured is”,
data.count(123.5) 
print “Number of times 786 occured is”,
data.count(786) 

Output:
>>>  
Number of times 123.5 occured is 1 
Number of times 786 occured is 3 
>>> 

Python List pop()/pop(int) Method Example
data = [786,’abc’,’a’,123.5,786] 
print “Last element is”, data.pop() 
print “2nd position element:”, data.pop(1) 
print data 

Output:
>>>  
Last element is 786 
2nd position element:abc 
[786, ‘a’, 123.5] 
>>> 

Python List insert(index,object) Method Example
data=[‘abc’,123,10.5,’a’] 
data.insert(2,’hello’) 
print data 

Output:
>>>  
[‘abc’, 123, ‘hello’, 10.5, ‘a’] 
>>> 

Python List extend(sequence) Method Example
1.    data1=[‘abc’,123,10.5,’a’] 
2.    data2=[‘ram’,541] 
3.    data1.extend(data2) 
4.    print data1 
5.    print data2 

Output:
>>>  
[‘abc’, 123, 10.5, ‘a’, ‘ram’, 541] 
[‘ram’, 541] 
>>> 

Python List remove(object) Method Example
data1=[‘abc’,123,10.5,’a’,’xyz’] 
data2=[‘ram’,541] 
print data1 
data1.remove(‘xyz’) 
print data1 
print data2 
data2.remove(‘ram’) 
print data2 

Output:
>>>  
[‘abc’, 123, 10.5, ‘a’, ‘xyz’] 
[‘abc’, 123, 10.5, ‘a’] 
[‘ram’, 541] 
[541] 
>>> 

Python List reverse() Method Example
list1=[10,20,30,40,50] 
list1.reverse() 
print list1 

Output:
>>>  
[50, 40, 30, 20, 10] 
>>> 

Python List sort() Method Example
1.    list1=[10,50,13,’rahul’,’aakash’] 
2.    list1.sort() 
3.    print list1 

Output:
>>>  
[10, 13, 50, ‘aakash’, ‘rahul’] 
>>>   

Python Tuple

Python Tuple

A tuple is a sequence of immutable objects, therefore tuple cannot be changed. It can be used to collect different types of object.The objects are enclosed within parenthesis and separated by comma.

Tuple is similar to list. Only the difference is that list is enclosed between square bracket, tuple between parenthesis and List has mutable objects whereas Tuple has immutable objects.

Python Tuple Example
>>> data=(10,20,’ram’,56.8) 
>>> data2=”a”,10,20.9 
>>> data 
(10, 20, ‘ram’, 56.8) 
>>> data2 
(‘a’, 10, 20.9) 
>>> 

NOTE: If Parenthesis is not given with a sequence, it is by default treated as Tuple.
There can be an empty Tuple also which contains no object. Lets see an example of empty tuple.

Python Empty Tuple Example
tuple1=() 

Python Single Object Tuple Example
For a single valued tuple, there must be a comma at the end of the value.
Tuple1=(10,) 

Python Tuple of Tuples Example
Tuples can also be nested, it means we can pass tuple as an element to create a new tuple. See, the following example in which we have created a tuple that contains tuples an the object.

tupl1=’a’,’mahesh’,10.56 
    tupl2=tupl1,(10,20,30) 
    print tupl1 
    print tupl2 

Output:
>>>  
(‘a’, ‘mahesh’, 10.56) 
((‘a’, ‘mahesh’, 10.56), (10, 20, 30)) 
>>> 

Accessing Tuple
Accessing of tuple is prity easy, we can access tuple in the same way as List. See, the following example.

Accessing Tuple Example
data1=(1,2,3,4) 
data2=(‘x’,’y’,’z’) 
print data1[0] 
print data1[0:2] 
print data2[-3:-1] 
print data1[0:] 
print data2[:2] 

Output:
>>>  

(1, 2) 
(‘x’, ‘y’) 
(1, 2, 3, 4) 
(‘x’, ‘y’) 
>>> 

Elements in a Tuple

Data=(1,2,3,4,5,10,19,17)

Data[0]=1=Data[-8] ,
Data[1]=2=Data[-7] ,
Data[2]=3=Data[-6] ,  
Data[3]=4=Data[-5] ,
Data[4]=5=Data[-4] ,
Data[5]=10=Data[-3], 
Data[6]=19=Data[-2],
Data[7]=17=Data[-1] 

Python Tuple Operations
Python allows us to perform various operations on the tuple. Following are the common tuple operations.

Adding Tuples Example
Tuple can be added by using the concatenation operator(+) to join two tuples.

data1=(1,2,3,4) 
data2=(‘x’,’y’,’z’) 
data3=data1+data2 
print data1 
print data2 
print data3 

Output:
>>>
(1, 2, 3, 4)
(‘x’, ‘y’, ‘z’)
(1, 2, 3, 4, ‘x’, ‘y’, ‘z’)
>>>

Note: The new sequence formed is a new Tuple.

Replicating Tuple Example
Replicating means repeating. It can be performed by using ‘*’ operator by a specific number of time.

tuple1=(10,20,30); 
tuple2=(40,50,60); 
print tuple1*2 
print tuple2*3 

Output:
>>>
(10, 20, 30, 10, 20, 30)
(40, 50, 60, 40, 50, 60, 40, 50, 60)
>>>

Python Tuple Slicing Example
A subpart of a tuple can be retrieved on the basis of index. This subpart is known as tuple slice.

data1=(1,2,4,5,7) 
print data1[0:2] 
print data1[4] 
print data1[:-1] 
print data1[-5:] 
print data1 

Output:
>>>
(1, 2)
7
(1, 2, 4, 5)
(1, 2, 4, 5, 7)
(1, 2, 4, 5, 7)
>>>

Note: If the index provided in the Tuple slice is outside the list, then it raises an IndexError exception.

Python Tuple other Operations
Updating elements in a List
Elements of the Tuple cannot be updated. This is due to the fact that Tuples are immutable. Whereas the Tuple can be used to form a new Tuple.

Example
data=(10,20,30) 
data[0]=100 
print data 

Output:

>>>
Traceback (most recent call last):
         File “C:/Python27/t.py”, line 2, in
        data[0]=100
TypeError: ‘tuple’ object does not
support item assignment
>>>

Creating Tuple from Existing Example
We can create a new tuple by assigning the existing tuple, see the following example.

data1=(10,20,30) 
data2=(40,50,60) 
data3=data1+data2 
print data3 

Output:
>>>
(10, 20, 30, 40, 50, 60)
>>>

Python Tuple Deleting Example
Deleting individual element from a tuple is not supported. However the whole of the tuple can be deleted using the del statement.

data=(10,20,’rahul’,40.6,’z’) 
print data 
del data     
#will delete the tuple data 
print data 
#will show an error since tuple data is already deleted 

Output:
>>>
(10, 20, ‘rahul’, 40.6, ‘z’)
Traceback (most recent call last):
        File “C:/Python27/t.py”, line 4, in
        print data
NameError: name ‘data’ is not defined
>>>

Functions of Tuple
There are following in-built Type Functions

Function
Description
min(tuple)
It returns the minimum value from a tuple.
max(tuple)
It returns the maximum value from the tuple.
len(tuple)
It gives the length of a tuple
cmp(tuple1,tuple2)
It compares the two Tuples.
tuple(sequence)
It converts the sequence into tuple.

Python Tuple min(tuple) Method Example
This method is used to get min value from the sequence of tuple.

data=(10,20,’rahul’,40.6,’z’) 
print min(data) 

Output:
>>>
10
>>>

Python Tuple max(tuple) Method Example
This method is used to get max value from the sequence of tuple.

data=(10,20,’rahul’,40.6,’z’) 
print max(data) 

Output:
>>>
z
>>>

Python Tuple len(tuple) Method Example
This method is used to get length of the tuple.

data=(10,20,’rahul’,40.6,’z’) 
print len(data) 

Output:
>>>
5
>>>

Python Tuple cmp(tuple1,tuple2) Method Example
This method is used to compare tuples.

Explanation:If elements are of the same type, perform the comparison and return the result. If elements are different types, check whether they are numbers.
If numbers, perform comparison.
If either element is a number, then the other element is returned.
Otherwise, types are sorted alphabetically .
If we reached the end of one of the lists, the longer list is “larger.” If both list are same it returns 0.

data1=(10,20,’rahul’,40.6,’z’) 
data2=(20,30,’sachin’,50.2) 
print cmp(data1,data2) 
print cmp(data2,data1) 
data3=(20,30,’sachin’,50.2) 
print cmp(data2,data3) 

Output:
>>>
-1
1
0
>>>

5) tuple(sequence):
Eg:
dat=[10,20,30,40] 
data=tuple(dat) 
print data 

Output:
>>>
(10, 20, 30, 40)
>>>

Why should wee use Tuple? (Advantages of Tuple)

Processing of Tuples are faster than Lists.
It makes the data safe as Tuples are immutable and hence cannot be changed.
Tuples are used for String formatting.

Python Functions

Python Functions

A Function is a self block of code which is used to organize the functional code.Function can be called as a section of a program that is written once and can be executed whenever required in the program, thus making code reusability.Function is a subprogram that works on data and produces some output.

Types of Functions:
There are two types of Functions.
a) Built-in Functions: Functions that are predefined and organized into a library. We have used many predefined functions in Python.
b) User- Defined: Functions that are created by the programmer to meet the requirements.

Defining a Function
A Function defined in Python should follow the following format:
1) Keyword def is used to start and declare a function. Def specifies the starting of function block.
2) def is followed by function-name followed by parenthesis.
3) Parameters are passed inside the parenthesis. At the end a colon is marked.

Python Function Syntax

def (parameters): 
 

Example
def sum(a,b): 

4) Python code requires indentation (space) of code to keep it associate to the declared block.
5) The first statement of the function is optional. It is ?Documentation string? of function.
6) Following is the statement to be executed.

Syntax:


Invoking a Python Function

To execute a function it needs to be called. This is called function calling.
Function Definition provides the information about function name, parameters and the definition what operation is to be performed. In order to execute the function definition, we need to call the function.

Python Function Syntax
(parameters) 
 

Python Function Example
sum(a,b)  
Here, sum is the function and a, b are the parameters passed to the function definition.
Let?s have a look over an example.

Python Function Example 2

#Providing Function Definition 
def sum(x,y): 
     “Going to add x and y” 
      s=x+y 
     print “Sum of two numbers is” 
       print s 
       #Calling the sum Function 
      sum(10,20) 
      sum(20,30)  

Output:
>>>  
Sum of two numbers is 
30 
Sum of two numbers is 
50 
>>>  

NOTE: Function call will be executed in the order in which it is called.

Python Function return Statement
return[expression] is used to return response to the caller function. We can use expression with the return keyword. send back the control to the caller with the expression.In case no expression is given after return it will return None.In other words return statement is used to exit the function definition.

Python Function return Example
def sum(a,b): 
            “Adding the two values” 
         print “Printing within Function” 
print a+b 
            return a+b 
def msg(): 
            print “Hello” 
            return 
 
total=sum(10,20) 
print ?Printing Outside: ?,total 
msg() 
print “Rest of code” 

Output:
>>>  
Printing within Function 
30 
Printing outside:  30 
Hello 
Rest of code 
>>> 

Python Function Argument and Parameter
There can be two types of data passed in the function.

1) The First type of data is the data passed in the function call. This data is called ?arguments?.
2) The second type of data is the data received in the function definition. This data is called ?parameters?.
Arguments can be literals, variables and expressions. Parameters must be variable to hold incoming values.
Alternatively, arguments can be called as actual parameters or actual arguments and parameters can be called as formal parameters or formal arguments.

Python Function Example
def addition(x,y): 
            print x+y 
x=15 
addition(x ,10) 
addition(x,x) 
y=20 
addition(x,y) 

Output:
>>>  
25 
30 
35 
>>> 

Passing Parameters

Apart from matching the parameters, there are other ways of matching the parameters.
Python supports following types of formal argument:
1) Positional argument (Required argument).
2) Default argument.
3) Keyword argument (Named argument)

Positional/Required Arguments:
When the function call statement must match the number and order of arguments as defined in the function definition. It is Positional Argument matching.

Python Function Positional Argument Example
#Function definition of sum  
def sum(a,b): 
            “Function having two parameters” 
         c=a+b 
              print c 
 
sum(10,20) 
sum(20) 

Output:
>>>  
30 
 
Traceback (most recent call last): 
    File “C:/Python27/su.py”, line 8, in  
        sum(20) 
TypeError: sum() takes exactly 2 arguments (1 given) 
>>> 
 

Explanation:
1) In the first case, when sum() function is called passing two values i.e., 10 and 20 it matches with function definition parameter and hence 10 and 20 is assigned to a and b respectively. The sum is calculated and printed.
2) In the second case, when sum() function is called passing a single value i.e., 20 , it is passed to function definition. Function definition accepts two parameters whereas only one value is being passed, hence it will show an error.

Python Function Default Arguments
Default Argument is the argument which provides the default values to the parameters passed in the function definition, in case value is not provided in the function call default value is used.

Python Function Default Argument Example
#Function Definition 
def msg(Id,Name,Age=21): 
            “Printing the passed value” 
            print Id 
         print Name 
         print Age 
         return 
#Function call 
msg(Id=100,Name=’Ravi’,Age=20) 
msg(Id=101,Name=’Ratan’) 

Output:
>>>  
100 
Ravi 
20 
101 
Ratan 
21 
>>> 

Explanation:
1) In first case, when msg() function is called passing three different values i.e., 100 , Ravi and 20, these values will be assigned to respective parameters and thus respective values will be printed.
2) In second case, when msg() function is called passing two values i.e., 101 and Ratan, these values will be assigned to Id and Name respectively. No value is assigned for third argument via function call and hence it will retain its default value i.e, 21.

Python Keyword Arguments
Using the Keyword Argument, the argument passed in function call is matched with function definition on the basis of the name of the parameter.

Python keyword Argument Example
def msg(id,name): 
         “Printing passed value” 
               print id 
               print name 
           return 
msg(id=100,name=’Raj’) 
msg(name=’Rahul’,id=101) 

Output:
>>>  
100 
Raj 
101 
Rahul 
>>> 

Explanation:
1) In the first case, when msg() function is called passing two values i.e., id and name the position of parameter passed is same as that of function definition and hence values are initialized to respective parameters in function definition. This is done on the basis of the name of the parameter.
2) In second case, when msg() function is called passing two values i.e., name and id, although the position of two parameters is different it initialize the value of id in Function call to id in Function Definition. same with name parameter. Hence, values are initialized on the basis of name of the parameter.

Python Anonymous Function
Anonymous Functions are the functions that are not bond to name. It means anonymous function does not has a name.
Anonymous Functions are created by using a keyword “lambda”.
Lambda takes any number of arguments and returns an evaluated expression.
Lambda is created without using the def keyword.

Python Anonymous Function Syntax

lambda arg1,args2,args3,?,argsn :expression 

Python Anonymous Function Example
#Function Definiton 
square=lambda x1: x1*x1 
 
#Calling square as a function 
print “Square of number is”,square(10) 

Output:
>>>  
Square of number is 100 
>>> 

Difference between Normal Functions and Anonymous Function:
Have a look over two examples:

Example:

o    Normal function:
#Function Definiton 
def square(x): 
    return x*x 
     
#Calling square function 
print “Square of number is”,square(10) 

o    Anonymous function:
#Function Definiton 
square=lambda x1: x1*x1 
 
#Calling square as a function 
print “Square of number is”,square(10) 

Explanation:
Anonymous is created without using def keyword.
lambda keyword is used to create anonymous function.
It returns the evaluated expression.

Scope of Variable:
Scope of a variable can be determined by the part in which variable is defined. Each variable cannot be accessed in each part of a program. There are two types of variables based on Scope:

1) Local Variable.
2) Global Variable.

1) Python Local Variables
Variables declared inside a function body is known as Local Variable. These have a local access thus these variables cannot be accessed outside the function body in which they are declared.

Python Local Variables Example
def msg(): 
           a=10 
           print “Value of a is”,a 
           return 
 
msg() 
print a #it will show error since variable is local 

Output:
>>>  
Value of a is 10 
 
Traceback (most recent call last): 
    File “C:/Python27/lam.py”, line 7, in  
     print a #it will show error since variable is local 
NameError: name ‘a’ is not defined 
>>> 
 

b) Python Global Variable
Variable defined outside the function is called Global Variable. Global variable is accessed all over program thus global variable have widest accessibility.

Python Global Variable Example
b=20 
def msg(): 
           a=10 
           print “Value of a is”,a 
           print “Value of b is”,b 
           return 
 
           msg() 
           print b 

Output:
>>>  
Value of a is 10 
Value of b is 20 
20 
>>> 

Python Dictionary

Python Dictionary

Dictionary is an unordered set of key and value pair. It is a container that contains data, enclosed within curly braces.The pair i.e., key and value is known as item. The key passed in the item must be unique.

The key and the value is separated by a colon(:). This pair is known as item. Items are separated from each other by a comma(,). Different items are enclosed within a curly brace and this forms Dictionary.

Python Dictionary Example
data={100:’Ravi’ ,101:’Vijay’ ,102:’Rahul’} 
print data  

Output:
>>>
{100: ‘Ravi’, 101: ‘Vijay’, 102: ‘Rahul’}
>>>

Note:
Dictionary is mutable i.e., value can be updated.
Key must be unique and immutable. Value is accessed by key. Value can be updated while key cannot be changed.
Dictionary is known as Associative array since the Key works as Index and they are decided by the user.

Python Dictionary Example
plant={} 
plant[1]=’Ravi’ 
plant[2]=’Manoj’ 
plant[‘name’]=’Hari’ 
plant[4]=’Om’ 
print plant[2] 
print plant[‘name’] 
print plant[1] 
print plant  

Output:
>>>
Manoj
Hari
Ravi
{1: ‘Ravi’, 2: ‘Manoj’, 4: ‘Om’, ‘name’: ‘Hari’}
>>>

Accessing Dictionary Values
Since Index is not defined, a Dictionary values can be accessed by their keys only. It means, to access dictionary elements we need to pass key, associated to the value.

Python Accessing Dictionary Element Syntax
[key] 
 

Accessing Elements Example
data1={‘Id’:100, ‘Name’:’Suresh’, ‘Profession’:’Developer’} 
data2={‘Id’:101, ‘Name’:’Ramesh’, ‘Profession’:’Trainer’} 
print “Id of 1st employer is”,data1[‘Id’] 
print “Id of 2nd employer is”,data2[‘Id’] 
print “Name of 1st employer:”,data1[‘Name’] 
print “Profession of 2nd employer:”,data2[‘Profession’] 

Output:
>>>
Id of 1st employer is 100
Id of 2nd employer is 101
Name of 1st employer is Suresh
Profession of 2nd employer is Trainer
>>>

Updating Python Dictionary Elements
The item i.e., key-value pair can be updated. Updating means new item can be added. The values can be modified.

Example
data1={‘Id’:100, ‘Name’:’Suresh’, ‘Profession’:’Developer’} 
data2={‘Id’:101, ‘Name’:’Ramesh’, ‘Profession’:’Trainer’} 
data1[‘Profession’]=’Manager’ 
data2[‘Salary’]=20000 
data1[‘Salary’]=15000 
print data1 
print data2 

Output:
>>>
{‘Salary’: 15000, ‘Profession’: ‘Manager’,’Id’: 100, ‘Name’: ‘Suresh’}
{‘Salary’: 20000, ‘Profession’: ‘Trainer’, ‘Id’: 101, ‘Name’: ‘Ramesh’}
>>>

Deleting Python Dictionary Elements Example
del statement is used for performing deletion operation.
An item can be deleted from a dictionary using the key only.

Delete Syntax
1.    del  [key] 
2.     

Whole of the dictionary can also be deleted using the del statement.

Example
data={100:’Ram’, 101:’Suraj’, 102:’Alok’} 
del data[102] 
print data   
del data 
print data 
#will show an error since dictionary is deleted. 

Output:
>>>
{100: ‘Ram’, 101: ‘Suraj’}

Traceback (most recent call last):
         File “C:/Python27/dict.py”, line 5, in
          print data
NameError: name ‘data’ is not defined
>>>

Python Dictionary Functions and Methods
Python Dictionary supports the following Functions

Python Dictionary Functions

Functions
Description
len(dictionary)
It returns number of items in a dictionary.
cmp(dictionary1,
dictionary2)
It compares the two dictionaries.
str(dictionary)
It gives the string representation of a string.

Python Dictionary Methods

Methods
Description
keys()
It returns all the keys element of a dictionary.
values()
It returns all the values element of a dictionary.
items()
It returns all the items(key-value pair) of a dictionary.
update(dictionary2)
It is used to add items of dictionary2 to first dictionary.
clear()
It is used to remove all items of a dictionary. It returns an empty dictionary.
fromkeys(sequence,value1)
/ fromkeys(sequence)
It is used to create a new dictionary from the sequence where sequence elements forms the key and all keys share the values ?value1?. In case value1 is not give, it set the values of keys to be none.
copy()
It returns an ordered copy of the data.
has_key(key)
It returns a boolean value. True in case if key is present in the dictionary ,else false.
get(key)
It returns the value of the given key. If key is not present it returns none.

Python Dictionary len(dictionary) Example
It returns length of the dictionary.

data={100:’Ram’, 101:’Suraj’, 102:’Alok’} 
print data 
print len(data) 

Output:
>>>
{100: ‘Ram’, 101: ‘Suraj’, 102: ‘Alok’}
3
>>>

Python Dictionary cmp(dictionary1,dictionary2) Example
The comparison is done on the basis of key and value.

If, dictionary1 == dictionary2, returns 0. 
      dictionary1 < dictionary2, returns -1. 
     dictionary1 > dictionary2, returns 1. 
data1={100:’Ram’, 101:’Suraj’, 102:’Alok’} 
data2={103:’abc’, 104:’xyz’, 105:’mno’} 
data3={‘Id’:10, ‘First’:’Aman’,’Second’:’Sharma’} 
data4={100:’Ram’, 101:’Suraj’, 102:’Alok’} 
print cmp(data1,data2) 
print cmp(data1,data4) 
print cmp(data3,data2) 

Output:
>>>
-1
0
1
>>>

Python Dictionary str(dictionary) Example
This method returns string formation of the value.

data1={100:’Ram’, 101:’Suraj’, 102:’Alok’} 
print str(data1) 

Output:
>>>
{100: ‘Ram’, 101: ‘Suraj’, 102: ‘Alok’}
>>>

Python Dictionary keys() Method Example
This method returns all the keys element of a dictionary.

data1={100:’Ram’, 101:’Suraj’, 102:’Alok’} 
print data1.keys() 

Output:
>>>
[100, 101, 102]
>>>

Python Dictionary values() Method Example
This method returns all the values element of a dictionary.

data1={100:’Ram’, 101:’Suraj’, 102:’Alok’} 
print data1.values() 

Output:
>>>
[‘Ram’, ‘Suraj’, ‘Alok’]
>>>

Python Dictionary items() Method Example
This method returns all the items(key-value pair) of a dictionary.

data1={100:’Ram’, 101:’Suraj’, 102:’Alok’} 
print data1.items() 

Output:
>>>
[(100, ‘Ram’), (101, ‘Suraj’), (102, ‘Alok’)]
>>>

Python Dictionary update(dictionary2) Method Example
This method is used to add items of dictionary2 to first dictionary.

data1={100:’Ram’, 101:’Suraj’, 102:’Alok’} 
data2={103:’Sanjay’} 
data1.update(data2) 
print data1 
print data2 

Output:
>>>
{100: ‘Ram’, 101: ‘Suraj’, 102: ‘Alok’, 103: ‘Sanjay’}
{103: ‘Sanjay’}
>>>

Python Dictionary clear() Method Example
It returns an ordered copy of the data.

data1={100:’Ram’, 101:’Suraj’, 102:’Alok’} 
print data1 
data1.clear() 
print data1 

Output:
>>>
{100: ‘Ram’, 101: ‘Suraj’, 102: ‘Alok’}
{}
>>>

Python Dictionary fromkeys(sequence)/ fromkeys(seq,value) Method Example
This method is used to create a new dictionary from the sequence where sequence elements forms the key and all keys share the values ?value1?. In case value1 is not give, it set the values of keys to be none.

sequence=(‘Id’ , ‘Number’ , ‘Email’) 
data={} 
data1={} 
data=data.fromkeys(sequence) 
print data 
data1=data1.fromkeys(sequence,100) 
print data1 

Output:
>>>
{‘Email’: None, ‘Id’: None, ‘Number’: None}
{‘Email’: 100, ‘Id’: 100, ‘Number’: 100}
>>>

Python Dictionary copy() Method Example
This method returns an ordered copy of the data.

data={‘Id’:100 , ‘Name’:’Aakash’ , ‘Age’:23} 
data1=data.copy() 
print data1 

Output:
>>>
{‘Age’: 23, ‘Id’: 100, ‘Name’: ‘Aakash’}
>>>

Python Dictionary has_key(key) Method Example
It returns a boolean value. True in case if key is present in the dictionary, else false.

data={‘Id’:100 , ‘Name’:’Aakash’ , ‘Age’:23} 
print data.has_key(‘Age’) 
print data.has_key(‘Email’) 

Output:
>>>
True
False
>>>

Python Dictionary get(key) Method Example
This method returns the value of the given key. If key is not present it returns none.

data={‘Id’:100 , ‘Name’:’Aakash’ , ‘Age’:23} 
print data.get(‘Age’) 
print data.get(‘Email’) 

Output:
>>>
23
None
>>>

Python Input And Output

Python Input And Output

Python provides methods that can be used to read and write data. Python also provides supports of reading and writing data to Files.

Python “print” Statement
“print” statement is used to print the output on the screen.print statement is used to take string as input and place that string to standard output.Whatever you want to display on output place that expression inside the inverted commas. The expression whose value is to printed place it without inverted commas.
Syntax:

print “expression” or print expression. 

Exampple
a=10 
print “Welcome to the world of Python” 
print a 

Output:
>>>  
Welcome to the world of Python 
10 
>>>      

Input from Keyboard:
Python offers two built-in functions for taking input from user, given below:

1) input()
2) raw_input()
1) input() functioninput() function is used to take input from the user. Whatever expression is given by the user, it is evaluated and result is returned back.

Python input() Syntax:
1.    input(“Expression”) 

Python input() Function Example
n=input(“Enter your expression “); 
print “The evaluated expression is “, n 

Output:
>>>  
Enter your expression 10*2 
The evaluated expression is  20 
>>>     

Python raw_input()
2) raw_input()raw_input() function is used to take input from the user. It takes the input from the Standard input in the form of a string and reads the data from a line at once.

Syntax:
1.    raw_input(?statement?) 

Python raw_input() Example
n=raw_input(“Enter your name “); 
print “Welcome “, n 

Output:
>>>  
Enter your name Rajat 
Welcome  Rajat 
>>>    

raw_input() function returns a string. Hence in case an expression is to be evaluated, then it has to be type casted to its following data type. Some of the examples are given below:

Program to calculate Simple Interest.
prn=int(raw_input(“Enter Principal”)) 
r=int(raw_input(“Enter Rate”)) 
t=int(raw_input(“Enter Time”)) 
si=(prn*r*t)/100 
print “Simple Interest is “,si   

Output:
>>>  
Enter Principal1000 
Enter Rate10 
Enter Time2 
Simple Interest is  200 
>>>   

Program to enter details of an user and print them.
name=raw_input(“Enter your name “) 
math=float(raw_input(“Enter your marks in Math”)) 
physics=float(raw_input(“Enter your marks in Physics”)) 
chemistry=float(raw_input(“Enter your marks in Chemistry”)) 
rollno=int(raw_input(“Enter your Roll no”)) 
print “Welcome “,name 
print “Your Roll no is “,rollno 
print “Marks in Maths is “,math 
print “Marks in Physics is “,physics 
print “Marks in Chemistry is “,chemistry 
print “Average marks is “,(math+physics+chemistry)/3  

Output:
>>>  
Enter your name rajat 
Enter your marks in Math76.8 
Enter your marks in Physics71.4 
Enter your marks in Chemistry88.4 
Enter your Roll no0987645672 
Welcome  rajat 
Your Roll no is  987645672 
Marks in Maths is  76.8 
Marks in Physics is  71.4 
Marks in Chemistry is  88.4 
Average marks is  78.8666666667 
>>> 

Python File Handling
Python provides the facility of working on Files. A File is an external storage on hard disk from where data can be stored and retrieved.

Operations on Files:
1) Opening a File: Before working with Files you have to open the File. To open a File, Python built in function open() is used. It returns an object of File which is used with other functions. Having opened the file now you can perform read, write, etc. operations on the File.

Syntax:
obj=open(filename , mode , buffer)  
here,
filename:It is the name of the file which you want to access.
mode:It specifies the mode in which File is to be opened.There are many types of mode. Mode depends the operation to be performed on File. Default access mode is read.

2) Closing a File:Once you are finished with the operations on File at the end you need to close the file. It is done by the close() method. close() method is used to close a File.
Syntax:
fileobject.close()  

3) Writing to a File:write() method is used to write a string into a file.
Syntax:
1.    fileobject.write(string str) 

4) Reading from a File:read() method is used to read data from the File.
Syntax:
fileobject.read(value) 

here, value is the number of bytes to be read. In case, no value is given it reads till end of file is reached.

Program to read and write data from a file.
obj=open(“abcd.txt”,”w”) 
obj.write(“Welcome to the world of Python”) 
obj.close() 
obj1=open(“abcd.txt”,”r”) 
s=obj1.read() 
print s 
obj1.close() 
obj2=open(“abcd.txt”,”r”) 
s1=obj2.read(20) 
print s1 
obj2.close() 

Output:
>>>  
Welcome to the world of Python 
Welcome to the world 
>>> 

Attributes of File:
There are following File attributes.

Attribute
Description
Name
Returns the name of the file.
Mode
Returns the mode in which file is being opened.
Closed
Returns Boolean value. True, in case if file is closed else false.

Example
obj = open(“data.txt”, “w”) 
print  obj.name 
print  obj.mode 
print  obj.closed 

Output:
>>>  
data.txt 

False 
>>> 

Modes of File:
There are different modes of file in which it can be opened. They are mentioned in the following table.

A File can be opened in two modes:

1) Text Mode.
2) Binary Mode.

Mode
Description
R
It opens in Reading mode. It is default mode of File. Pointer is at beginning of the file.
rb
It opens in Reading mode for binary format. It is the default mode. Pointer is at beginning of file.
r+
Opens file for reading and writing. Pointer is at beginning of file.
rb+
Opens file for reading and writing in binary format. Pointer is at beginning of file.
W
Opens file in Writing mode. If file already exists, then overwrite the file else create a new file.
wb
Opens file in Writing mode in binary format. If file already exists, then overwrite the file else create a new file.
w+
Opens file for reading and writing. If file already exists, then overwrite the file else create a new file.
wb+
Opens file for reading and writing in binary format. If file already exists, then overwrite the file else create a new file.
a
Opens file in Appending mode. If file already exists, then append the data at the end of existing file, else create a new file.
ab
Opens file in Appending mode in binary format. If file already exists, then append the data at the end of existing file, else create a new file.
a+
Opens file in reading and appending mode. If file already exists, then append the data at the end of existing file, else create a new file.
ab+
Opens file in reading and appending mode in binary format. If file already exists, then append the data at the end of existing file, else create a new file.

Methods:
There are many methods related to File Handling. They are given in the following table:

There is a module “os” defined in Python that provides various functions which are used to perform various operations on Files. To use these functions ‘os’ needs to be imported.

Method
Description
rename()
It is used to rename a file. It takes two arguments, existing_file_name and new_file_name.
remove()
It is used to delete a file. It takes one argument. Pass the name of the file which is to be deleted as the argument of method.
mkdir()
It is used to create a directory. A directory contains the files. It takes one argument which is the name of the directory.
chdir()
It is used to change the current working directory. It takes one argument which is the name of the directory.
getcwd()
It gives the current working directory.
rmdir()
It is used to delete a directory. It takes one argument which is the name of the directory.
tell()
It is used to get the exact position in the file.

1) rename():
Syntax:
os.rename(existing_file_name, new_file_name) 

eg:
import os 
os.rename(‘mno.txt’,’pqr.txt’) 

2) remove():
Syntax:
1.    os.remove(file_name) 

eg:
1.    import os 
2.    os.remove(‘mno.txt’) 

3) mkdir()
Syntax:
os.mkdir(“file_name”)

eg:
import os 
os.mkdir(“new”) 

4) chdir()
Syntax:
os.chdir(“file_name”)

Example
import os 
os.chdir(“new”) 

5) getcwd()
Syntax:
os.getcwd()

Example
import os 
print os.getcwd() 

6) rmdir()
Syntax:
os.rmdir(“directory_name)

Example
import os 
os.rmdir(“new”) 

NOTE: In order to delete a directory, it should be empty. In case directory is not empty first delete the files.

Python Module

Python Module

Modules are used to categorize Pyhton code into smaller parts. A module is simply a Python file, where classes, functions and variables are defined.

Grouping similar code into a single file makes it easy to access. Have a look at below example.If the content of a book is not indexed or categorized into individual chapters, the book might have turned boring and hectic. Hence, dividing book into chapters made it easy to understand.

In the same sense python modules are the files which have similar code. Thus module is simplify a python code where classes, variables and functions are defined.

Python Module Advantage

Python provides the following advantages for using module:

1) Reusability: Module can be used in some other python code. Hence it provides the facility of code reusability.

2) Categorization: Similar type of attributes can be placed in one module.

Importing a Module:

There are different ways by which you we can import a module. These are as follows:

1) Using import statement:

“import” statement can be used to import a module.

Syntax:

import  
 

Example

def add(a,b): 
    c=a+b 
    print c 
    return 
Save the file by the name addition.py. To import this file “import” statement is used.

import addition 
addition.add(10,20) 
addition.add(30,40) 

Create another python file in which you want to import the former python file. For that, import statement is used as given in the above example. The corresponding method can be used by file_name.method (). (Here, addition. add (), where addition is the python file and add () is the method defined in the file addition.py)

Output:

>>>  
30 
70 
>>> 

NOTE: You can access any function which is inside a module by module name and function name separated by dot. It is also known as period. Whole notation is known as dot notation.

Python Importing Multiple Modules Example

1) msg.py:

def msg_method(): 
    print “Today the weather is rainy” 
    return 

2) display.py:

def display_method(): 
    print “The weather is Sunny” 
    return 

3) multiimport.py:

import msg,display 
msg.msg_method() 
display.display_method() 

Output:

>>>  
Today the weather is rainy 
The weather is Sunny 
>>>      

2) Using from.. import statement:

from..import statement is used to import particular attribute from a module. In case you do not want whole of the module to be imported then you can use from ?import statement.

Syntax:

from  import
            <attribute1,attribute2,..attributen>    
</attribute1,attribute2,attribute3,…attributen></module_name> 

Python from.. import Example

def circle(r): 
    print 3.14*r*r 
    return 
 
def square(l): 
    print l*l 
    return 
 
def rectangle(l,b): 
    print l*b 
    return 
 
def triangle(b,h): 
    print 0.5*b*h 
    return 

2) area1.py

from area import square,rectangle 
square(10) 
rectangle(2,5) 

Output:

>>>  
100 
10 
>>> 

3) To import whole module:

You can import whole of the module using “from? import *”

Syntax:

from import * 
 
Using the above statement all the attributes defined in the module will be imported and hence you can access each attribute.

1) area.py

Same as above example

2) area1.py

from area import * 
square(10) 
rectangle(2,5) 
circle(5) 
triangle(10,20) 

Output:

>>>  
100 
10 
78.5 
100.0 
>>> 

Built in Modules in Python:

There are many built in modules in Python. Some of them are as follows: math, random , threading , collections , os , mailbox , string , time , tkinter etc..

Each module has a number of built in functions which can be used to perform various functions.

Let?s have a look over each module:

1) math:

Using math module , you can use different built in mathematical functions.

Functions:

Function
Description
ceil(n)
It returns the next integer number of the given number
sqrt(n)
It returns the Square root of the given number.
exp(n)
It returns the natural logarithm e raised to the given number
floor(n)
It returns the previous integer number of the given number.
log(n,baseto)
It returns the natural logarithm of the number.
pow(baseto, exp)
It returns baseto raised to the exp power.
sin(n)
It returns sine of the given radian.
cos(n)
It returns cosine of the given radian.
tan(n)
It returns tangent of the given radian.

Python Math Module Example

import math 
a=4.6 
print math.ceil(a) 
print math.floor(a) 
b=9 
print math.sqrt(b) 
print math.exp(3.0) 
print math.log(2.0) 
print math.pow(2.0,3.0) 
print math.sin(0) 
print math.cos(0) 
print math.tan(45) 

Output:

>>>  
5.0 
4.0 
3.0 
20.0855369232 
0.69314718056 
8.0 
0.0 
1.0 
1.61977519054 
>>> 

Constants:

The math module provides two constants for mathematical Operations:

Constants
Descriptions
Pi
Returns constant ? = 3.14159…
ceil(n)
Returns constant e= 2.71828…

Example

import math 
 
print math.pi 
print math.e 

Output:

>>>  
3.14159265359 
2.71828182846 
>>> 

2) random:

The random module is used to generate the random numbers. It provides the following two built in functions:

Function
Description
random()
It returns a random number between 0.0 and 1.0 where 1.0 is exclusive.
randint(x,y)
It returns a random number between x and y where both the numbers are inclusive.

Python Module Example

import random 
 
print random.random() 
print random.randint(2,8) 

Output:

>>>  
0.797473843839 

>>> 
Other modules will be covered in their respective topics.

Python Package

A Package is simply a collection of similar modules, sub-packages etc..

Steps to create and import Package:

1) Create a directory, say Info

2) Place different modules inside the directory. We are placing 3 modules msg1.py, msg2.py and msg3.py respectively and place corresponding codes in respective modules. Let us place msg1() in msg1.py, msg2() in msg2.py and msg3() in msg3.py.

3) Create a file __init__.py which specifies attributes in each module.

4) Import the package and use the attributes using package.

Have a look over the example:

1) Create the directory:

import os 
os.mkdir(“Info”) 

2) Place different modules in package: (Save different modules inside the Info package)

msg1.py

def msg1(): 
    print “This is msg1” 

msg2.py

def msg2(): 
    print “This is msg2” 

msg3.py

def msg3(): 
    print “This is msg3” 

3) Create __init__.py file:

from msg1 import msg1 
from msg2 import msg2 
from msg3 import msg3 

4)Import package and use the attributes:

import Info 
Info.msg1() 
Info.msg2() 
Info.msg3() 

Output:

>>>  
This is msg1 
This is msg2 
This is msg3 
>>> 

What is __init__.py file?

__init__.py is simply a file that is used to consider the directories on the disk as the package of the Python. It is basically used to initialize the python packages.

Python OOPs Concepts

Python OOPs Concepts

Python is an object-oriented programming language. It allows us to develop applications using Object Oriented approach. In Python, we can easily create and use classes and objects.
Major principles of object-oriented programming system are given below
Object
Class
Method
Inheritance
Polymorphism
Data Abstraction
Encapsulation
Object
Object is an entity that has state and behavior. It may be anything. It may be physical and logical. For example: mouse, keyboard, chair, table, pen etc.
Everything in Python is an object, and almost everything has attributes and methods. All functions have a built-in attribute __doc__, which returns the doc string defined in the function source code.
Class
Class can be defined as a collection of objects. It is a logical entity that has some specific attributes and methods. For example: if you have an employee class then it should contain an attribute and method i.e. an email id, name, age, salary etc.

Syntax:
class ClassName: 
     
    . 
    . 
    . 
     
Method
Method is a function that is associated with an object. In Python, method is not unique to class instances. Any object type can have methods.
Inheritance
Inheritance is a feature of object-oriented programming. It specifies that one object acquires all the properties and behaviors of parent object. By using inheritance you can define a new class with a little or no changes to the existing class. The new class is known as derived class or child class and from which it inherits the properties is called base class or parent class.
It provides re-usability of the code.
Polymorphism
Polymorphism is made by two words “poly” and “morphs”. Poly means many and Morphs means form, shape. It defines that one task can be performed in different ways. For example: You have a class animal and all animals talk. But they talk differently. Here, the “talk” behavior is polymorphic in the sense and totally depends on the animal. So, the abstract “animal” concept does not actually “talk”, but specific animals (like dogs and cats) have a concrete implementation of the action “talk”.
Encapsulation
Encapsulation is also the feature of object-oriented programming. It is used to restrict access to methods and variables. In encapsulation, code and data are wrapped together within a single unit from being modified by accident.
Data Abstraction
Data abstraction and encapsulation both are often used as synonyms. Both are nearly synonym because data abstraction is achieved through encapsulation.
Abstraction is used to hide internal details and show only functionalities. Abstracting something means to give names to things, so that the name captures the core of what a function or a whole program does.
Object-oriented vs Procedure-oriented Programming languages

Object-oriented Programming
Procedural Programming
Object-oriented programming is an problem solving approach and used where computation is done by using objects.
Procedural programming uses a list of instructions to do computation step by step.
It makes development and maintenance easier.
In procedural programming, It is not easy to maintain the codes when project becomes lengthy.
It simulates the real world entity. So real world problems can be easily solved through oops.
It doesn’t simulate the real world. It works on step by step instructions divided in small parts called functions.
It provides data hiding. so it is more secure than procedural languages. You cannot access private data from anywhere.
Procedural language doesn’t provide any proper way for data binding so it is less secure.
Example of object-oriented programming languages are: C++, Java, .Net, Python, C# etc.
Example of procedural languages are: C, Fortran, Pascal, VB etc.

Python Exception Handling

Python Exception Handling

Exception can be said to be any abnormal condition in a program resulting to the disruption in the flow of the program.Whenever an exception occurs the program halts the execution and thus further code is not executed. Thus exception is that error which python script is unable to tackle with.

Exception in a code can also be handled. In case it is not handled, then the code is not executed further and hence execution stops when exception occurs.

Common Exceptions
ZeroDivisionError: Occurs when a number is divided by zero.
NameError: It occurs when a name is not found. It may be local or global.
IndentationError: If incorrect indentation is given.
IOError: It occurs when Input Output operation fails.
EOFError: It occurs when end of the file is reached and yet operations are being performed.
etc..

Exception Handling:
The suspicious code can be handled by using the try block. Enclose the code which raises an exception inside the try block. The try block is followed except statement. It is then further followed by statements which are executed during exception and in case if exception does not occur.

Syntax:
try: 
    malicious code 
except Exception1: 
    execute code 
except Exception2: 
    execute code 
…. 
…. 
except ExceptionN: 
    execute code 
else: 
    In case of no exception, execute the
                                       else block code. 

Python Exception Handling Example
try: 
    a=10/0 
    print a 
except ArithmeticError: 
        print “This statement is raising an exception” 
else: 
    print “Welcome” 

Output:
>>>  
This statement is raising an exception 
>>> 

Explanation:
The malicious code (code having exception) is enclosed in the try block.
Try block is followed by except statement. There can be multiple except statement with a single try block.
Except statement specifies the exception which occurred. In case that exception is occurred, the corresponding statement will be executed.
At the last you can provide else statement. It is executed when no exception is occurred.

Python Exception(Except with no Exception) Example
Except statement can also be used without specifying Exception.

Syntax:
try: 
        code 
    except: 
        code to be executed in case exception occurs. 
    else: 
        code to be executed in
              case exception does not occur.  

Example
try: 
    a=10/0; 
except: 
    print “Arithmetic Exception” 
else: 
    print “Successfully Done” 

Output:
>>>  
Arithmetic Exception 
>>> 

Declaring Multiple Exception in Python
Python allows us to declare multiple exceptions using the same except statement.

Syntax:
try: 
    code 
except Exception1,Exception2 ,..,ExceptionN 
    execute this code in case any Exception of these occur. 
else: 
    execute code in case no exception occurred. 

Example
try: 
    a=10/0; 
except ArithmeticError,StandardError: 
    print “Arithmetic Exception” 
else: 
    print “Successfully Done” 

Output:
>>>  
Arithmetic Exception 
>>> 

Finally Block:
In case if there is any code which the user want to be executed, whether exception occurs or not then that code can be placed inside the finally block. Finally block will always be executed irrespective of the exception.

Syntax:
try: 
    Code 
finally:  
    code which is must to be executed. 

Example
try: 
    a=10/0; 
    print “Exception occurred” 
finally: 
    print “Code to be executed” 

Output:
>>>  
Code to be executed 
Traceback (most recent call last): 
  File “C:/Python27/noexception.py”, line 2, in  
    a=10/0; 
ZeroDivisionError: integer division or modulo by zero 
>>> 
In the above example finally block is executed. Since exception is not handled therefore exception occurred and execution is stopped.

Raise an Exception:
You can explicitly throw an exception in Python using ?raise? statement. raise will cause an exception to occur and thus execution control will stop in case it is not handled.

Syntax:
raise Exception_class, 

Example
try: 
    a=10 
    print a 
    raise NameError(“Hello”) 
except NameError as e: 
        print “An exception occurred” 
        print e 

Output:
>>>  
10 
An exception occurred 
Hello 
>>> 

Explanation:
i) To raise an exception, raise statement is used. It is followed by exception class name.
ii) Exception can be provided with a value that can be given in the parenthesis. (here, Hello)
iii) To access the value “as” keyword is used. “e” is used as a reference variable which stores the value of the exception.

Custom Exception:

Refer to this section after visiting Class and Object section:
Creating your own Exception class or User Defined Exceptions are known as Custom Exception.

Example
class ErrorInCode(Exception): 
     def __init__(self, data): 
   self.data = data 
     def __str__(self): 
        return repr(self.data) 
 
try: 
    raise ErrorInCode(2000) 
except ErrorInCode as ae: 
    print “Received error:”, ae.data 

Output:
>>>  
Received error : 2000 
>>>