unit 1 python
unit 1 python
PYTHON
CS:26 Programming in Python 1
What is Python?
Python is a high-level, interpreted, interactive and object-oriented scripting language. Python is
designed to be highly readable. It uses English keywords frequently where as other languages
use punctuation, and it has fewer syntactical constructions than other languages. It was created
by Guido van Rossum in 1991 and further developed by the Python Software Foundation .
▪ Python is Interpreted: Python is processed at runtime by the interpreter. You do not
need to compile your program before executing it. This is similar to PERL and PHP.
▪ Python is Interactive: You can actually sit at a Python prompt and interact with the
interpreter directly to write your programs.
▪ Python is Object-Oriented: Python supports Object-Oriented style or technique of
programming that encapsulates code within objects.
▪ Python is a Beginner's Language: Python is a great language for the beginner-level
programmers and supports the development of a wide range of applications from simple
text processing to WWW browsers to games.
We don't need to use data types to declare variable because it is dynamically typed so we can
write a=10 to declare an integer value in a variable. Python makes the development and
debugging fast because there is no compilation step included in python development and edit-
test-debug cycle is very fast.
2) Expressive Language:
Python language is more expressive. The code is easily understandable.
3) Interpreted Language:
Python is an interpreted language i.e. interpreter executes the code line by line at a time. This
makes debugging easy and thus suitable for beginners.
4) Cross-platform language:
Python can run equally on different platforms such as Windows, Linux, Unix, Macintosh etc.
Thus, Python is a portable language.
6) Object-Oriented language:
Python supports object oriented language. Concept of classes and objects comes into existence.
7) Extensible:
It implies that other languages such as C/C++ can be used to compile the code and thus it can be
used further in your python code.
9) GUI Programming:
Graphical user interfaces can be developed using Python.
10) Integrated:
It can be easily integrated with languages like C, C++, JAVA etc.
Disadvantages of Python
▪ Python isn't the best for memory intensive tasks.
▪ Python is interpreted language & is slow compared to C/C++ or java.
▪ Python not a great choice for a high-graphic 3d game that takes up a lot of CPU.
▪ Python is evolving continuously, with constant evolution there is little substantial
documentation available for the language.
▪ Python is not a very good language for mobile development.
▪ Python is not good for multi-processor/multi-core work.
Python Version
Mainly there are 3 versions:
▪ Python 3.0 - December 3, 2008
▪ Python 2.0 - October 16, 2000
▪ Python 1.0 - January 1994
Executing Python
There are three different ways to start Python −
Interactive Interpreter
You can start Python from Unix, DOS, or any other system that provides you a command -line
interpreter or shell window.
Enter “py” in the command line. Start coding right away in the interactive interpreter.
Script from the Command-line
A Python script can be executed at command line by invoking the interpreter on your
application,like “py script.py”.
Integrated Development Environment
You can run Python from a Graphical User Interface (GUI) environment as well, if you have a
GUI application on your system that supports Python.
Python Variables
Variable is a name of the memory location where data is stored. Once a variable is stored that
means a space is allocated in memory.
Multiple Assignment:
Multiple assignment can be done in Python at a time.
There are two ways to assign values in Python:
Reserved Words
The following list shows the Python keywords. These are reserved words and you cannot use
them as constant or variable or any other identifier names. All the Python keywords contain
lowercase letters only.
And Exec not
Assert Finally or
Break For pass
Class From print
Continue Global raise
Def If return
Del Import try
Elif In while
Else Is with
Except Lambda yield
1) Python Numbers
Number data types store numeric values. Number objects are created when you assign a value to
them. Numbers can be integer, long, float and complex. For example –
var1 = 1
var2 = 10.6
2) Python Strings
Python allows for either pairs of single or double quotes. Subsets of strings can be taken using
the slice operator ([ ] and [:] ) with indexes starting at 0 in the beginning of the string .
Eg:
str = 'Hello World!'
print (str) # prints complete string
Output:
Hello World!
3) Python Lists
A list contains items separated by commas and enclosed within square brackets ([]). To some
extent, lists are similar to arrays in C. One difference between them is that all the items
belonging to a list can be of different data type.
Eg:
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tinylist = [123, 'john']
print (list) # prints complete list
print (list[0]) # prints first element of the list
print(list[1:3]) # prints elements starting from 2nd till 3rd
print(list[2:]) # print elements starting from 3rd element
print(tinylist * 2) # prints list two times
print(list + tinylist) # prints concatenated lists
Output:
['abcd', 786, 2.23, 'john', 70.2]
abcd
[786, 2.23]
5) Python Dictionary
Python's dictionaries are kind of hash table type. They consist of key -value pairs. A dictionary
key can be almost any Python type, but are usually numbers or strings. Values, on the other hand,
can be any arbitrary Python object.
Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed using
square braces ([]).
Eg:
dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"
tinydict = {'name': 'john','code':6734, 'dept': 'sales'}
print (dict['one']) # prints value for 'one' key
print(dict[2]) # prints value for 2 key
print(tinydict) # prints complete dictionary
print(tinydict.keys()) # prints all the keys
print(tinydict.values()) # prints all the values
Output:
This is one
This is two
{'dept': 'sales', 'code': 6734, 'name': 'john'}
['dept', 'code', 'name']
['sales', 6734, 'john']
Branching in python
Python If Statements
The if statement in python is same as c language which is used to test a condition. If condition is
true, statement of if block is executed otherwise it is skipped.
Syntax of python if statement:
if(condition):
statements
Example of if statement in python
a=10
if a==10:
print ( "Hello User" )
Output:
Hello User
elif statement:
Body
else:
Body
Example:
a=10
if a>=20:
print "Condition is True"
else:
if a>=15:
print ("Checking second value" )
else:
print ("All Conditions are false" )
Output:
All Conditions are false.
output:
3 - Got a true expression value
100
Good bye
Python Strings
Strings are the simplest and easy to use in Python.
String pythons are immutable.
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.
Strings Operators
There are basically 3 types of Operators supported by String:
1. Basic Operators.
2. Membership Operators.
3. Relational Operators.
Basic Operators:
There are two types of basic operators in String. They are "+" and "*".
String Concatenation Operator :(+)
The concatenation operator (+) concatenate two Strings and forms a new String.
eg:
>>> "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
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.
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 return true if a character or the entire substring is present in the specified
string, otherwise false.
2) not in:"not in" operator return true if a character or entire substring does not exist in the
specified string, otherwise false.
Eg:
>>> 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
Relational Operators:
All the comparison operators i.e., (<,><=,>=,==,!=,<>) are also applicable to strings. The Strings
are compared based on the ASCII value or Unicode(i.e., dictionary Order).
Eg:
>>> "RAJAT"=="RAJAT"
True
>>> "Z"=="z"
False
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.
Slice Notation:
String slice can be defined as substring which is the part of string.
startIndex in String slice is inclusive whereas endIndex is exclusive.
Syntax:
<string_name>[startIndex:endIndex],
<string_name>[:endIndex],
<string_name>[startIndex:]
Example:
>>> str="Nikhil"
>>> str[0:6]
'Nikhil'
>>> str[0:3]
'Nik'
>>> str[2:5]
'khi'
>>> str[:6]
'Nikhil'
>>> str[3:]
'hil'
find(substring ,beginIndex, It returns the index value of the string where substring is found
endIndex) between begin index and end index.
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) len() returns the length of a string.
lower() Converts all the characters of a string to Lower case.
upper() Converts all the characters of a string to Upper Case.
swapcase() Inverts case of all characters in a string.
lstrip() Remove all leading whitespace of a string. It can also be used to
remove particular character from leading.
rstrip() Remove all trailing whitespace of a string. It can also be used to
remove particular character from trailing.
Examples:
1) capitalize()
It capitalizes the first character of the String.
>>> 'abc'.capitalize()
Output:
'Abc'
2) count(string)
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
3) find(string)
It 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
4) 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.
str="Welcome to sssit"
print (str.isalnum())
str1="Python47"
print (str1.isalnum())
Output:
False
True
5) isalpha()
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
6) isdigit()
It 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
7) islower()
It 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
8) isupper()
It 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
9) isspace()
It 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
10) len(string)
len() returns the length of a string.
string1=" "
print (len(string1))
string2="WELCOME TO SSSIT"
print (len(string2))
Output:
4
16
11) lower()
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
12) upper()
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
13) swapcase()
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
14) lstrip()
Remove all leading whitespace of a string. It 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
15) rstrip()
Remove all trailing whitespace of a string. It 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
It is possible to specify the starting value by adding a parameter: range(2, 6), which means values
from 2 to 6 (but not including 6):
Example
for x in range(2, 5):
print(x)
Output:
2
3
4
It is possible to specify the increment value by adding a third parameter: range(2, 10, 2):
Example
Break statement
break statement is a jump statement that is used to pass the control to the end of the loop.
When break statement is applied the control points to the line following the body of the loop ,
hence applying break statement makes the loop to terminate and controls goes to next line
pointing after loop body.
eg:
for i in [1,2,3,4,5]:
if i==4:
print ("Element found“)
break
print (i)
Output:
1
2
3
Element found
Continue Statement
continue Statement is a jump statement that is used to skip the present iteration and forces next
iteration of loop to take place. It can be used in while as well as for loop statements.
eg:
a=0
while a<=5:
a=a+1
if a%2==0:
continue
print (a)
print ("End of Loop")
Output:
1
3
5
End of Loop
Python Operators
Operators are particular symbols which operate on some values and produce an output.
The values are known as Operands.
Eg:
4+5=9
Here 4 and 5 are Operands and (+) , (=) signs are the operators. They produce the output 9.
Python supports the following operators:
1. Arithmetic Operators.
2. Relational Operators.
3. Assignment Operators.
4. Logical Operators.
5. Membership Operators.
6. Identity Operators.
Arithmetic Operators:
Operators Description
// Perform Floor division(gives integer value after division)
+ To perform addition
- To perform subtraction
* To perform multiplication
/ To perform division
% To return remainder after division(Modulus)
** Perform exponent(raise to power)
eg:
>>> 10+20
30
>>> 20-10
10
>>> 10*2
20
>>> 10/2
5
>>> 10%3
1
>>> 2**3
8
>>> 10//3
3
>>>
Relational Operators:
Operators Description
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
== Equal to
!= Not equal to
<> Not equal to(similar to !=)
eg:
>>> 10<20
True
>>> 10>20
False
>>> 10<=10
True
>>> 20>=15
True
>>> 5==6
False
>>> 5!=6
True
>>> 10<>2
True
>>>
Assignment Operators:
Operators Description
= Assignment
/= Divide and Assign
+= Add and assign
-= Subtract and Assign
*= Multiply and assign
%= Modulus and assign
**= Exponent and assign
//= Floor division and assign
eg:
>>> c=10
>>> c
10
>>> c+=5
>>> c
15
>>> c-=5
>>> c
10
>>> c*=2
>>> c
20
>>> c/=2
>>> c
10
>>> c%=3
>>> c
1
>>> c=5
>>> c**=2
>>> c
25
>>> c//=2
>>> c
12
>>>
Logical Operators:
Operators Description
And Logical AND(When both conditions are true output will be true)
Or Logical OR (If any one condition is true output will be true)
Not Logical NOT(Compliment the condition i.e., reverse)
eg:
a=5>4 and 3>2
print a
b=5>4 or 3<2
print b
c=not(5>4)
print c
Output:
True
True
False
Membership Operators:
Operators Description
In Returns true if a variable is in sequence of another variable, else false.
not in Returns true if a variable is not in sequence of another variable, else false.
eg:
a=10
b=20
list=[10,20,30,40,50]
if (a in list):
print "a is in given list"
else:
print "a is not in given list"
if(b not in list):
print "b is not given in list"
else:
print "b is given in list"
Output:
a is in given list
b is given in list
Identity Operators:
Operators Description
Is Returns true if identity of two operands are same, else false
is not Returns true if identity of two operands are not same, else false.
Example:
a=20
b=20
if( a is b):
print “a,b have same identity”
else:
print “a, b are different”
b=10
if( a is not b):
print “a,b have different identity”
else:
print “a,b have same identity”
Output:
a,b have same identity
a,b have different identity
Python List
1).Python lists are the data structure that is capable of holding different type of data.
2).Python lists are mutable i.e., Python will not create a new list if we modify an element in the
list.
3).It is a container that holds other objects in a given order. Different operation like insertion and
deletion can be performed on lists.
4).A list can be composed by storing a sequence of different type of values separated by commas.
5).A python list is enclosed between square([]) brackets.
6).The elements are stored in the index basis with starting index as 0.
eg:
data1=[1,2,3,4]
data2=['x','y','z']
data3=[12.5,11.6]
data4=['raman','rahul']
data5=[]
data6=['abhinav',10,56.4,'a']
Accessing Lists
A list can be created by putting the value inside the square bracket and separated by comma.
Syntax:
<list_name>=[value1,value2,value3,...,valuen]
Elements in a Lists:
Data=[1,2,3,4,5]
Output:
1
[1, 2]
['x', 'y']
[1, 2, 3, 4]
['x', 'y']
List Operations:
Various Operations can be performed on List. Operations performed on List are given as:
a) Adding Lists:
Lists can be added by using the concatenation operator(+) to join two lists.
Eg:
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.
Eg:
list1=[10,20]
list1+30
print( list1)
Output:
Traceback (most recent call last):
File "C:/Python27/lis.py", line 2, in <module>
list1+30
b) Replicating lists:
Replicating means repeating . It can be performed by using '*' operator by a specific number of
time.
Eg:
list1=[10,20]
print( list1*2 )
Output:
[10, 20,10,20]
c) List slicing:
A subpart of a list can be retrieved on the basis of index. This subpart is known as list slice.
Eg:
list1=[1,2,4,5,7]
print( list1[0:2] )
print( list1[4] )
list1[1]=9
print( list1 )
Output:
[1, 2]
7
[1, 9, 4, 5, 7]
Note: If the index provided in the list slice is outside the list, then it raises an IndexError
exception.
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:
a) Updating elements in a List:
To update or change the value of particular index of a list, assign the value to that particular
index of the List.
Syntax:
<list_name>[index]=<value>
Eg:
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]
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
2) max(list):
Eg:
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
3) len(list):
Eg:
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
4) list(sequence):
Eg:
seq=(145,"abcd",'a')
data=list(seq)
print( "List formed is : ",data )
Output:
List formed is : [145, 'abcd', 'a']
popped object.
insert(index,object) Insert 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() Reverse the position of all the elements of a list.
sort() It is used to sort the elements of the List.
1) index(object):
Eg:
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
2) count(object):
Eg:
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
3) pop()/pop(int):
Eg:
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]
4) insert(index,object):
Eg:
data=['abc',123,10.5,'a']
data.insert(2,'hello')
print( data )
Output:
5) extend(sequence):
Eg:
data1=['abc',123,10.5,'a']
data2=['ram',541]
data1.extend(data2)
print( data1 )
print( data2 )
Output:
['abc', 123, 10.5, 'a', 'ram', 541]
['ram', 541]
6) remove(object):
Eg:
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]
7) reverse():
Eg:
list1=[10,20,30,40,50]
list1.reverse()
print( list1 )
Output:
[50, 40, 30, 20, 10]
8) sort():
Eg:
list1=[10,50,13]
list1.sort()
print( list1 )
Output:
Python Tuple
A tuple is a sequence of immutable objects, therefore tuple cannot be changed.
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 have mutable objects whereas Tuple have immutable objects.
eg:
>>> 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.
eg:
tuple1=()
For a single valued tuple, there must be a comma at the end of the value.
eg:
Tuple1=(10,)
Tuples can also be nested.
eg:
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
Tuple can be accessed in the same way as List.
Some examples are given below:
eg:
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 Tuple
Data=(1,2,3,4,5,10,19,17)
Tuple Operations
Various Operations can be performed on Tuple. Operations performed on Tuple are given as:
a) Adding Tuple:
Tuple can be added by using the concatenation operator(+) to join two tuples.
eg:
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')
b) Replicating Tuple:
Replicating means repeating. It can be performed by using '*' operator by a specific number of
time.
Eg:
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)
c) Tuple slicing:
A subpart of a tuple can be retrieved on the basis of index. This subpart is known as tuple slice.
Eg:
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.
Other Operations:
a) Updating elements in a Tuple:
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.
Eg:
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
Functions of Tuple:
There are following in-built Type Functions:
Function Description
min(tuple) Returns the minimum value from a tuple.
max(tuple) Returns the maximum value from the tuple.
len(tuple) Gives the length of a tuple
tuple(sequence) Converts the sequence into tuple.
1) min(tuple):
Eg:
data=(10,20,'rahul',40.6,'z')
print( min(data) )
Output:
10
2) max(tuple):
Eg:
data=(10,20,40.6)
print( max(data) )
data1=(‘a’,’A’)
print(max(data1))
Output:
40.6
a
3) len(tuple):
Eg:
data=(10,20,'rahul',40.6,'z')
print( len(data) )
Output:
5
4) tuple(sequence):
Eg:
dat=[10,20,30,40]
data=tuple(dat)
print( data )
Output:
(10, 20, 30, 40)
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.
eg:
data={100:'Ravi' ,101:'Vijay' ,102:'Rahul'}
print( data )
Output:
{100: 'Ravi', 101: 'Vijay', 102: 'Rahul'}
Accessing Values
Since Index is not defined, a Dictionaries value can be accessed by their keys.
Syntax:
[key]
Eg:
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
Updation
The item i.e., key-value pair can be updated. Updating means new item can be added. The values
can be modified.
Eg:
Deletion
del statement is used for performing deletion operation.
An item can be deleted from a dictionary using the key.
Syntax:
del [key]
Whole of the dictionary can also be deleted using the del statement.
Eg:
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'}
Dictionary Methods:
Methods Description
keys() Return all the keys element of a dictionary.
values() Return all the values element of a dictionary.
items() Return 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.
copy() It returns an ordered copy of the data.
get(key) Returns the value of the given key. If key is not present it
returns none.
1) keys ():
Eg:
data1= {100:'Ram', 101:'Suraj', 102:'Alok'}
print (data1.keys())
Output:
[100, 101, 102]
2) values():
Eg:
data1={100:'Ram', 101:'Suraj', 102:'Alok'}
print( data1.values())
Output:
['Ram', 'Suraj', 'Alok']
3) items():
Eg:
data1={100:'Ram', 101:'Suraj', 102:'Alok'}
print( data1.items())
Output:
[(100, 'Ram'), (101, 'Suraj'), (102, 'Alok')]
4) update(dictionary2):
Eg:
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'}
5) clear():
Eg:
data1={100:'Ram', 101:'Suraj', 102:'Alok'}
print( data1)
data1.clear()
print( data1)
Output:
{100: 'Ram', 101: 'Suraj', 102: 'Alok'}
{}
6) copy():
Eg:
data={'Id':100 , 'Name':'Aakash' , 'Age':23}
data1=data.copy()
print( data1)
Output:
{'Age': 23, 'Id': 100, 'Name': 'Aakash'}
7) get(key):
Eg:
data={'Id':100 , 'Name':'Aakash' , 'Age':23}
print( data.get('Age'))
print( data.get('Email'))
Output:
23
None
Python Functions
▪ A Function is a self-block of code.
▪ A 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.
▪ A 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. We have used many predefined functions in
Python.
b) User- Defined: Functions that are created according to the requirements.
Defining a Function:
A Function defined in Python should follow the following format:
1) Keyword def is used to start the Function Definition. 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.
Syntax:
def <function_name>([parameters]):
eg:
def sum(a,b):
4) Before writing a code, an Indentation (space) is provided before every statement. It should be
same for all statements inside the function.
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 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, it is to be called.
Syntax:
<function_name>(parameters)
eg:
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:
eg:
#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.
return Statement:
return[expression] is used to 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.
Eg:
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
Eg:
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
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.
Eg:
#Function definition of sum
def sum(a,b):
"Function having two parameters"
c=a+b
print( c)
sum(10,20)
sum(20)
Output:
30
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 print(ed.
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.
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.
Eg:
#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
print(ed.
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.
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.
Eg:
def msg(id,name):
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.
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) 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.
Eg:
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
b) Global Variable:
Variable defined outside the function is called Global Variable. Global variable is accessed all
over program thus global variable have widest accessibility.
Eg:
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
* in Function Calls
A * can appear in function calls as well, as we have just seen in the previous exercise: The
semantics is in this case "inverse" to a star in a function definition. An argument will be
unpacked and not packed. In other words, the elements of the list or tuple are singularized:
def f(x,y,z):
print(x,y,z)
p = (47,11,12)
f(*p)
output:
(47, 11, 12)
Recursion
Recursion is the process of defining something in terms of itself.
A physical world example would be to place two parallel mirrors facing each other. Any object
in between them would be reflected recursively.
Example:
# An example of a recursive function to
# find the factorial of a number
def calc_factorial(x):
if x == 1:
return 1
else:
return (x * calc_factorial(x-1))
num = 4
print("The factorial of", num, "is", calc_factorial(num))
Advantages of Recursion
1. Recursive functions make the code look clean and elegant.
2. A complex task can be broken down into simpler sub-problems using recursion.
3. Sequence generation is easier with recursion than using some nested iteration.
Disadvantages of Recursion
1. Sometimes the logic behind recursion is hard to follow through.
2. Recursive calls are expensive (inefficient) as they take up a lot of memory and time.
3. Recursive functions are hard to debug.
Python Modules
What is a Module?
Consider a module to be the same as a code library.
A file containing a set of functions you want to include in your application.
Create a Module
To create a module just save the code you want in a file with the file extension .py:
Example
Save this code in a file named mymodule.py
def greeting(name):
print("Hello, " + name)
Use a Module
Now we can use the module we just created, by using the import statement:
Example
Import the module named mymodule, and call the greeting function:
import mymodule
mymodule.greeting("BCA6")
Output:
Hello, BCA6
Note: When using a function from a module, use the syntax: module_name.function_name.
Variables in Module
The module can contain functions, as already described, but also variables of all types (lists,
dictionaries, objects etc):
Example
Save this code in the file mymodule.py
person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}
Import the module named mymodule, and access the person1 dictionary:
import mymodule
a = mymodule.person1["age"]
print(a)
Output:
36
Naming a Module
You can name the module file whatever you like, but it must have the file extension .py
Re-naming a Module
You can create an alias when you import a module, by using the as keyword:
Example
Create an alias for mymodule called mx:
import mymodule as mx
a = mx.person1["age"]
print(a)
Output:
36
Built-in Modules
There are several built-in modules in Python, which you can import whenever you like.
Example
Import and use the platform module:
import platform
x = platform.system()
print(x)
Output:
Windows
Note: The dir() function can be used on all modules, also the ones you create yourself.
File Handling
File handling is an important part of any web application.
Python has several functions for creating, reading, updating, and deleting files.
Syntax
To open a file for reading it is enough to specify the name of the file:
f = open("demofile.txt")
The code above is the same as:
f = open("demofile.txt", "rt")
Because "r" for read, and "t" for text are the default values, you do not need to specify them.
Note: Make sure the file exists, or else you will get an error.
Read Lines
You can return one line by using the readline() method:
Example
Read one line of the file:
f = open("demofile.txt", "r")
print(f.readline())
By calling readline() two times, you can read the two first lines:
Example
Read two lines of the file:
f = open("demofile.txt", "r")
print(f.readline())
print(f.readline())
By looping through the lines of the file, you can read the whole file, line by line:
Example
Loop through the file line by line:
f = open("demofile.txt", "r")
for x in f:
print(x)
Example
Create a new file if it does not exist:
f = open("myfile.txt", "w")
os.remove("demofile.txt")
else:
print("The file does not exist")
Delete Folder
To delete an entire folder, use the os.rmdir() method:
Example
Remove the folder "myfolder":
import os
os.rmdir("myfolder")
Note: You can only remove empty folders.