Python Notes
Python Notes
Eg:
3+5j
10+5.5j
0.5+0.1j
In the real part if we use int value then we can specify that either by decimal,octal,binary
or hexa decimal form.
But imaginary part should be specified only by using decimal form.
>>> a=0B11+5j
>>> a
(3+5j)
>>> a=3+0B11j
SyntaxError: invalid syntax
>>> a=10+1.5j
>>> b=20+2.5j
>>> c=a+b
>>> print(c)
(30+4j)
>>> type(c)
<class 'complex'>
14 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Note: Complex data type has some inbuilt attributes to retrieve the real part
and imaginary part
c=10.5+3.6j
c.real==>10.5
c.imag==>3.6
b=True
type(b) =>bool
Eg:
a=10
b=20
c=a<b
print(c)==>True
True+True==>2
True-False==>1
str type:
str represents String data type.
s1='durga'
s1="durga"
By using single quotes or double quotes we cannot represent multi line string literals.
s1="durga
15 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
soft"
For this requirement we should go for triple single quotes(''') or triple double quotes(""")
s1='''durg
a
soft'''
s1="""durga
soft"""
We can also use triple quotes to use single quote or double quote in our String.
Slicing of Strings:
slice means a piece
[ ] operator is called slice operator,which can be used to retrieve parts of String.
In Python Strings follows zero based index.
The index can be either +ve or -ve.
+ve index means forward direction from Left to Right
-ve index means backward direction from Right to Left
-5 -4 -3 -2 -1
d u r g a
0 1 2 3 4
>>> s="durga"
>>> s[0]
'd'
>>> s[1]
'u'
>>> s[-1]
'a'
>>> s[40]
16 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
>>> s[1:40]
'urga'
>>> s[1:]
'urga'
>>> s[:4]
'durg'
>>> s[:]
'durga'
>>>
10)
11)
>>> s*3
'durgadurgadurga'
>>> len(s)
5
Note:
In Python the following data types are considered as Fundamental Data types
int
float
complex
bool
str
In Python,we can represent char values also by using str type and explicitly char type is
not available.
Eg:
>>> c='a'
>>> type(c)
<class 'str'>
long Data Type is available in Python2 but not in Python3. In Python3 long values also
we can represent by using int type only.
In Python we can present char Value also by using str Type and explicitly char Type is
not available.
17 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Type Casting
We can convert one type value to another type. This conversion is called Typecasting
or Type coersion.
The following are various inbuilt functions for type casting.
int()
float()
complex()
bool()
str()
1.int():
We can use this function to convert values from other types to int
Eg:
>>> int(123.987)
123
>>> int(10+5j)
TypeError: can't convert complex to int
>>> int(True)
1
>>> int(False)
0
>>> int("10")
10
>>> int("10.5")
ValueError: invalid literal for int() with base 10: '10.5'
>>> int("ten")
ValueError: invalid literal for int() with base 10: 'ten'
>>> int("0B1111")
ValueError: invalid literal for int() with base 10: '0B1111'
Note:
18 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
2. float():
We can use float() function to convert other type values to float type.
>>> float(10)
10.0
>>> float(10+5j)
TypeError: can't convert complex to float
>>> float(True)
1.0
>>> float(False)
0.0
>>> float("10")
10.0
>>> float("10.5")
10.5
>>> float("ten")
ValueError: could not convert string to float: 'ten'
>>> float("0B1111")
ValueError: could not convert string to float: '0B1111'
Note:
We can convert any type value to float type except complex type.
Whenever we are trying to convert str type to float type compulsary str should be
either integral or floating point literal and should be specified only in base-10.
3.complex():
Form-1: complex(x)
We can use this function to convert x into complex number with real part x and
imaginary part 0.
Eg:
complex(10)==>10+0j
complex(10.5)===>10.5+0j
complex(True)==>1+0j
complex(False)==>0j
complex("10")==>10+0j
complex("10.5")==>10.5+0j
complex("ten")
ValueError: complex() arg is a malformed string
19 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Form-2: complex(x,y)
We can use this method to convert x and y into complex number such that x will be
real part and y will be imaginary part.
Eg: complex(10,-2)==>10-2j
complex(True,False)==>1+0j
4. bool():
We can use this function to convert other type values to bool type.
Eg:
bool(0)==>False
bool(1)==>True
bool(10)===>True
bool(10.5)===>True
bool(0.178)==>True
bool(0.0)==>False
bool(10-2j)==>True
bool(0+1.5j)==>True
bool(0+0j)==>False
bool("True")==>True
bool("False")==>True
bool("")==>False
20 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
5. str():
We can use this method to convert other type values to str type
Eg:
>>> str(10)
'10'
>>> str(10.5)
'10.5'
>>> str(10+5j)
'(10+5j)'
>>> str(True)
'True'
All Fundamental Data types are immutable. i.e once we creates an object,we cannot
perform any changes in that object. If we are trying to change then with those changes a
new object will be created. This non-chageable behaviour is called immutability.
21 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
In Python if a new object is required, then PVM wont create object immediately. First it will
check is any object available with the required content or not. If available then existing
object will be reused. If it is not available then only a new object will be created. The
advantage of this approach is memory utilization and performance will be improved.
But the problem in this approach is,several references pointing to the same object,by
using one reference if we are allowed to change the content in the existing object then
the remaining references will be effected. To prevent this immutability concept is
required. According to this once creates an object we are not allowed to change content.
If we are trying to change with those changes a new object will be created.
Eg:
1) >>> a=10
2) >>> b=10
3) >>> a is b
4) True
5) >>> id(a)
6) 1572353952
7) >>> id(b)
8) 1572353952
9) >>>
22 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
bytes Data Type:
bytes data type represens a group of byte numbers just like an array.
Eg:
x = [10,20,30,40]
b = bytes(x)
type(b)==>bytes
print(b[0])==> 10
print(b[-1])==> 40
>>> for i in b : print(i)
10
20
30
40
Conclusion 1:
The only allowed values for byte data type are 0 to 256. By mistake if we are trying
to provide any other values then we will get value error.
Conclusion 2:
Once we creates bytes data type value, we cannot change its values,otherwise we will
get TypeError.
Eg:
>>> x=[10,20,30,40]
>>> b=bytes(x)
>>> b[0]=100
TypeError: 'bytes' object does not support item assignment
Eg 1:
x=[10,20,30,40]
b = bytearray(x)
for i in b : print(i)
10
23 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
20
30
40
b[0]=100
for i in b: print(i)
100
20
30
40
Eg 2:
>>> x =[10,256]
>>> b = bytearray(x)
ValueError: byte must be in range(0, 256)
If we want to represent a group of values as a single entity where insertion order required
to preserve and duplicates are allowed then we should go for list data type.
Eg:
list=[10,10.5,'durga',True,10]
print(list) # [10,10.5,'durga',True,10]
Eg:
list=[10,20,30,40]
>>> list[0]
10
>>> list[-1]
40
>>> list[1:3]
[20, 30]
>>> list[0]=100
>>> for i in list:print(i)
...
100
20
30
24 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
40
list is growable in nature. i.e based on our requirement we can increase or decrease the
size.
>>> list=[10,20,30]
>>> list.append("durga")
>>> list
[10, 20, 30, 'durga']
>>> list.remove(20)
>>> list
[10, 30, 'durga']
>>> list2=list*2
>>> list2
[10, 30, 'durga', 10, 30, 'durga']
tuple data type is exactly same as list data type except that it is immutable.i.e we
cannot chage values.
Eg:
t=(10,20,30,40)
type(t)
<class 'tuple'>
t[0]=100
TypeError: 'tuple' object does not support item assignment
>>> t.append("durga")
AttributeError: 'tuple' object has no attribute 'append'
>>> t.remove(10)
AttributeError: 'tuple' object has no attribute 'remove'
25 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Form-1: range(10)
generate numbers from 0 to 9
Eg:
r=range(10)
for i in r : print(i) 0 to 9
Form-2: range(10,20)
Eg:
s={100,0,10,200,10,'durga'}
s # {0, 100, 'durga', 200, 10}
s[0] ==>TypeError: 'set' object does not support indexing
set is growable in nature, based on our requirement we can increase or decrease the size.
>>> s.add(60)
>>> s
{0, 100, 'durga', 200, 10, 60}
>>> s.remove(100)
>>> s
{0, 'durga', 200, 10, 60}
>>> s={10,20,30,40}
>>> fs=frozenset(s)
>>> type(fs)
<class 'frozenset'>
>>> fs
frozenset({40, 10, 20, 30})
>>> for i in fs:print(i)
...
40
10
20
30
13)
>>> fs.add(70)
AttributeError: 'frozenset' object has no attribute 'add'
>>> fs.remove(10)
AttributeError: 'frozenset' object has no attribute 'remove'
27 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
dict Data Type:
Eg:
d={101:'durga',102:'ravi',103:'shiva'}
Duplicate keys are not allowed but values can be duplicated. If we are trying to insert
an entry with duplicate key then old value will be replaced with new value.
Eg:
>>> d={101:'durga',102:'ravi',103:'shiva'}
>>> d[101]='sunny'
>>> d
{101: 'sunny', 102: 'ravi', 103: 'shiva'}
5.
We can create empty dictionary as follows
d={ }
We can add key-value pairs as follows
d['a']='apple'
d['b']='banana'
print(d)
Note:
In general we can use bytes and bytearray data types to represent binary information
like images,video files etc
In Python2 long data type is available. But in Python3 it is not available and we can
represent long values also by using int type only.
In Python there is no char data type. Hence we can represent char values also by using
str type.
28 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Summary of Datatypes in Python3
Datatype Description Is Immutable Example
Int We can use to represent the Immutable >>> a=10
whole/integral numbers >>> type(a)
<class 'int'>
Float We can use to represent the Immutable >>> b=10.5
decimal/floating point >>> type(b)
numbers <class 'float'>
Complex We can use to represent the Immutable >>> c=10+5j
complex numbers >>> type(c)
<class 'complex'>
>>> c.real
10.0
>>> c.imag
5.0
Bool We can use to represent the Immutable >>> flag=True
logical values(Only allowed >>> flag=False
values are True and False) >>> type(flag)
<class 'bool'>
Str To represent sequence of Immutable >>> s='durga'
Characters >>> type(s)
<class 'str'>
>>> s="durga"
>>> s='''Durga Software Solutions
... Ameerpet'''
>>> type(s)
<class 'str'>
bytes To represent a sequence of Immutable >>> list=[1,2,3,4]
byte values from 0-255 >>> b=bytes(list)
>>> type(b)
<class 'bytes'>
bytearray To represent a sequence of Mutable >>> list=[10,20,30]
byte values from 0-255 >>> ba=bytearray(list)
>>> type(ba)
<class 'bytearray'>
range To represent a range of Immutable >>> r=range(10)
values >>> r1=range(0,10)
>>> r2=range(0,10,2)
list To represent an ordered Mutable >>> l=[10,11,12,13,14,15]
collection of objects >>> type(l)
<class 'list'>
tuple To represent an ordered Immutable >>> t=(1,2,3,4,5)
collections of objects >>> type(t)
<class 'tuple'>
set To represent an unordered Mutable >>> s={1,2,3,4,5,6}
collection of unique objects >>> type(s)
29 nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
<class 'set'>
frozenset To represent an unordered Immutable >>> s={11,2,3,'Durga',100,'Ramu'}
collection of unique objects >>> fs=frozenset(s)
>>> type(fs)
<class 'frozenset'>
dict To represent a group of key Mutable >>>
value pairs d={101:'durga',102:'ramu',103:'hari'}
>>> type(d)
<class 'dict'>
print(m1())
None
Escape Characters:
In String literals we can use esacpe characters to associate a special meaning.
>>> s="durga\nsoftware"
>>> print(s)
durga
software
>>> s="durga\tsoftware"
>>> print(s)
durga software
>>> s="This is " symbol"
File "<stdin>", line 1
s="This is " symbol"
^
SyntaxError: invalid syntax
>>> s="This is \" symbol"
>>> print(s)
This is " symbol
30 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
The following are various important escape characters in Python
\n==>New Line
\t===>Horizontal tab
\r ==>Carriage Return
\b===>Back space
\f===>Form Feed
\v==>Vertical tab
\'===>Single quote
\"===>Double quote
\\===>back slash symbol
....
Constants:
Constants concept is not applicable in Python.
But it is convention to use only uppercase characters if we don’t want to change value.
MAX_VALUE=10
31 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Operators
Operator is a symbol that performs certain operations.
Python provides the following set of operators
Arithmetic Operators
Relational Operators or Comparison Operators
Logical operators
Bitwise oeprators
Assignment operators
Special operators
1. Arithmetic Operators:
+ ==>Addition
- ==>Subtraction
* ==>Multiplication
==>Division operator %
===>Modulo operator
Eg: test.py:
a=10
b=2
print('a+b=',a+b)
print('a-b=',a-b)
print('a*b=',a*b)
print('a/b=',a/b)
print('a//b=',a//b)
print('a%b=',a%b)
print('a**b=',a**b)
0 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Output:
Eg:
a = 10.5
b=2
3)
a+b= 12.5
a-b= 8.5
a*b= 21.0
a/b= 5.25
a//b= 5.0
a%b= 0.5
a**b= 110.25
Eg:
10/2==>5.0
10//2==>5
10.0/2===>5.0
10.0//2===>5.0
Note: / operator always performs floating point arithmetic. Hence it will always
returns float value.
But Floor division (//) can perform both floating point and integral arithmetic. If
arguments are int type then result is int type. If atleast one argument is float type
then result is float type.
Note:
>>> "durga"+10
TypeError: must be str, not int
>>> "durga"+"10"
'durga10'
2 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
If we use * operator for str type then compulsory one argument should be int and
other argument should be str type.
2*"durga"
"durga"*2
2.5*"durga" ==>TypeError: can't multiply sequence by non-int of type 'float'
"durga"*"durga"==>TypeError: can't multiply sequence by non-int of type 'str'
10/0
10.0/0
.....
Relational Operators:
>,>=,<,<=
Eg 1:
a=10
b=20
print("a > b is ",a>b)
print("a >= b is ",a>=b)
print("a < b is ",a<b)
print("a <= b is ",a<=b)
a > b is False
a >= b is False
a < b is True
a <= b is True
Eg 2:
a="durga"
b="durga"
print("a > b is ",a>b)
print("a >= b is ",a>=b)
print("a < b is ",a<b)
3 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
print("a <= b is ",a<=b)
a > b is False
a >= b is True
a < b is False
a <= b is True
Eg:
print(True>True) False
print(True>=True) True
print(10 >True) True
print(False > True) False
print(10>'durga')
TypeError: '>' not supported between instances of 'int' and 'str'
Eg:
a=10
b=20
if(a>b):
print("a is greater than b")
else:
print("a is not greater than b")
Eg:
10<20 ==>True
10<20<30 ==>True
10<20<30<40 ==>True
10<20<30<40>50 ==>False
equality operators:
==,!=
We can apply these operators for any type even for incompatible types also
>>> 10==20
False
>>> 10!= 20
4 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
True
>>> 10==True
False
>>> False==False
True
>>> "durga"=="durga"
True
>>> 10=="durga"
False
Eg:
>>> 10==20==30==40
False
>>> 10==10==10==10
True
Logical Operators:
and, or ,not
0 means False
non-zero means True
empty string is always treated as False
x and y:
5 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Eg:
10 and 20
0 and 20
x or y:
10 or 20 ==> 10
0 or 20 ==> 20
not x:
not 10 ==>False
not 0 ==>True
Eg:
Bitwise Operators:
We can apply these operators bitwise.
These operators are applicable only for int and boolean types.
By mistake if we are trying to apply for any other type then we will get Error.
&,|,^,~,<<,>>
print(4&5) ==>valid
print(10.5 & 5.6) ==>
TypeError: unsupported operand type(s) for &: 'float' and 'float'
6 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
==> If both bits are 1 then only result is 1 otherwise result is 0 |
==> If atleast one bit is 1 then result is 1 otherwise result is 0
^ ==>If bits are different then only result is 1 otherwise result is 0
~ ==>bitwise complement operator
1==>0 & 0==>1 <<
==>Bitwise Left shift >>
==>Bitwise Right Shift
print(4&5) ==>4
print(4|5) ==>5
print(4^5) ==>1
Operator Description
If both bits are 1 then only result is 1 otherwise result is 0
| If atleast one bit is 1 then result is 1 otherwise result is 0
If bits are different then only result is 1 otherwise result is 0
bitwise complement operator i.e 1 means 0 and 0 means 1
Bitwise Left shift Operator
Bitwise Right shift Operator
Note:
The most significant bit acts as sign bit. 0 value represents +ve number where as
1 represents -ve value.
positive numbers will be repesented directly in the memory where as -ve numbers will
be represented indirectly in 2's complement form.
Shift Operators:
<< Left shift operator
After shifting the empty cells we have to fill with zero
print(10<<2)==>40
0 0 0 0 1 0 1 0
0 0 1 0 1 0 0 0
7 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
>> Right Shift operator
After shifting the empty cells we have to fill with sign bit.( 0 for +ve and 1 for -ve)
print(10>>2) ==>2
0 0 0 0 1 0 1 0
0 0 0 0 0 0 1 0
Assignment Operators:
We can use assignment operator to assign value to the variable.
Eg:
x=10
The following is the list of all possible compound assignment operators in Python
+=
-=
*=
/=
%=
//=
**=
&=
|=
^=
8 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
>>=
<<=
Eg:
x=10
x+=20
print(x) ==>30
Eg:
x=10
x&=5
print(x) ==>0
Ternary Operator:
Syntax:
x = firstValue if condition else secondValue
If condition is True then firstValue will be considered else secondValue will be considered.
Eg 1:
a,b=10,20
x=30 if a<b else 40
print(x) #30
Eg 2: Read two numbers from the keyboard and print minimum value
Output:
Enter First Number:10
Enter Second Number:30
Minimum Value: 10
9 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Q. Program for minimum of 3 numbers
Eg:
Output:
D:\python_classes>py test.py
Enter First Number:10
Enter Second Number:10
Both numbers are equal
D:\python_classes>py test.py
Enter First Number:10
Enter Second Number:20
First Number is Less than Second Number
D:\python_classes>py test.py
Enter First Number:20
Enter Second Number:10
First Number Greater than Second Number
10 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Special operators:
Python defines the following 2 special operators
Identity Operators
Membership operators
1. Identity Operators
We can use identity operators for address comparison.
2 identity operators are available
is
is not
Eg:
a=10
b=10
3) print(a is b) True
x=True
y=True
6) print( x is y) True
Eg:
a="durga"
b="durga"
print(id(a))
print(id(b))
print(a is b)
Eg:
list1=["one","two","three"]
list2=["one","two","three"]
print(id(list1))
print(id(list2))
print(list1 is list2) False
print(list1 is not list2) True
7) print(list1 == list2) True
11 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Note:
We can use is operator for address comparison where as == operator for
content comparison.
2. Membership operators:
We can use Membership operators to check whether the given object present in
the given collection.(It may be String,List,Set,Tuple or Dict)
in Returns True if the given object present in the specified Collection
not in Retruns True if the given object not present in the specified Collection
Eg:
Eg:
list1=["sunny","bunny","chinny","pinny"]
print("sunny" in list1) True
print("tunny" in list1) False
print("tunny" not in list1) True
Operator Precedence:
If multiple operators present then which operator will be evaluated first is decided
by operator precedence.
Eg:
print(3+10*2) 23
print((3+10)*2) 26
The following list describes operator precedence in Python
() Parenthesis
** exponential operator
~,- Bitwise complement operator,unary minus operator
*,/,%,// multiplication,division,modulo,floor division
+,- addition,subtraction
<<,>> Left and Right Shift
& bitwise And
12 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Bitwise X-OR |
Bitwise OR
>,>=,<,<=, ==, != ==>Relational or Comparison
operators =,+=,-=,*=... ==>Assignment operators
is , is not Identity Operators
in , not in Membership operators not
Logical not
and Logical and
or Logical or
Eg:
a=30
b=20
c=10
d=5
print((a+b)*c/d) 100.0
print((a+b)*(c/d)) 100.0
print(a+(b*c)/d)70.0
3/2*4+3+(10/5)**3-2
3/2*4+3+2.0**3-2
3/2*4+3+8.0-2
1.5*4+3+8.0-2
6.0+3+8.0-2
15.0
13 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Mathematical Functions (math Module)
A Module is collection of functions, variables and classes etc.
If we want to use any module in Python, first we have to import that module.
import math
Once we import a module then we can call any function of that module.
import math
print(math.sqrt(16))
print(math.pi)
4.0
3.141592653589793
import math as m
Once we create alias name, by using that we can access functions and variables of that
module
import math as m
print(m.sqrt(16))
print(m.pi)
14 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
important functions of math module:
ceil(x)
floor(x)
pow(x,y)
factorial(x)
trunc(x)
gcd(x,y)
sin(x)
cos(x)
tan(x)
....
15 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Input And Output Statements
Reading dynamic input from the keyboard:
In Python 2 the following 2 functions are available to read dynamic input from
the keyboard.
raw_input()
input()
raw_input():
This function always reads the data from the keyboard in the form of String Format. We
have to convert that string type to our required type by using the corresponding type
casting methods.
Eg:
x=raw_input("Enter First Number:")
print(type(x)) It will always print str type only for any input type
2. input():
input() function can be used to read data directly in our required format.We are
not required to perform type casting.
x=input("Enter Value)
type(x)
10 ===> int
"durga"===>str
10.5===>float
True==>bool
***Note: But in Python 3 we have only input() method and raw_input() method is not
available.
Python3 input() function behaviour exactly same as raw_input() method of Python2. i.e
every input value is treated as str type only.
1 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Eg:
Q. Write a program to read 2 numbers from the keyboard and print sum.
-----------------------------------------------------
-----------------------------------------------------------
Q. Write a program to read Employee data from the keyboard and print that data.
2 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
D:\Python_classes>py test.py
Enter Employee No:100
Enter Employee Name:Sunny
Enter Employee Salary:1000
Enter Employee Address:Mumbai
Employee Married ?[True|False]:True
Please Confirm Information
Employee No : 100
Employee Name : Sunny
Employee Salary : 1000.0
Employee Address : Mumbai
Employee Married ? : True
Note: split() function can take space as seperator by default .But we can pass
anything as seperator.
Q. Write a program to read 3 float numbers from the keyboard with , seperator and
print their sum.
eval():
eval Function take a String and evaluate the Result.
Eg: x = eval(“10+20+30”)
print(x)
Output: 60
Input. Eg: Write a Program to accept list from the keynboard on the display
l = eval(input(“Enter List”))
print (type(l))
print(l)
Within the Python Program this Command Line Arguments are available in argv. Which
is present in SYS Module.
test.py 10 20 30
Note: argv[0] represents Name of Program. But not first Command Line Argument.
argv[1] represent First Command Line Argument.
import argv
print(type(argv))
D:\Python_classes\py test.py
4 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
The List of Command Line Arguments: [‘test.py’, ‘10’,’20’,’30’]
Command Line Arguments one by one:
test.py
10
20
30
D:\Python_classes>py test.py 10 20 30 40
The Sum: 100
Note1: usually space is seperator between command line arguments. If our command
line argument itself contains space then we should enclose within double quotes(but not
single quotes)
Eg:
Note2: Within the Python program command line arguments are available in the
String form. Based on our requirement,we can convert into corresponding type by using
type casting methods.
Eg:
5 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
4)
D:\Python_classes>py test.py 10 20
1020
30
Note3: If we are trying to access command line arguments with out of range index
then we will get Error.
Eg:
Note:
In Python there is argparse module to parse command line arguments and display some
help messages whenever end user enters wrong input.
input()
raw_input()
output statements:
We can use print() function to display output.
Form-2:
print(String):
print("Hello World")
We can use escape characters also
print("Hello \n World")
print("Hello\tWorld")
We can use repetetion operator (*) in the string
print(10*"Hello")
print("Hello"*10)
We can use + operator also
print("Hello"+"World")
6 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Note:
If both arguments are String type then + operator acts as concatenation operator.
If one argument is string type and second is any other type like int then we will get Error If
both arguments are number type then + operator acts as arithmetic addition operator.
Note:
print("Hello"+"World")
print("Hello","World")
HelloWorld
Hello World
a,b,c=10,20,30
print("The Values are :",a,b,c)
By default output values are seperated by space.If we want we can specify seperator
by using "sep" attribute
a,b,c=10,20,30
print(a,b,c,sep=',')
print(a,b,c,sep=':')
D:\Python_classes>py test.py
10,20,30
10:20:30
print("Hello")
print("Durga")
print("Soft")
Output:
Hello
Durga
Soft
7 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
print("Hello",end=' ')
print("Durga",end=' ')
print("Soft")
Note: The default value for end attribute is \n,which is nothing but new line character.
We can pass any object (like list,tuple,set etc)as argument to the print() statement.
Eg:
l=[10,20,30,40]
t=(10,20,30,40)
print(l)
print(t)
We can use print() statement with String and any number of arguments.
Eg:
s="Durga"
a=48
s1="java"
s2="Python"
print("Hello",s,"Your Age is",a)
print("You are teaching",s1,"and",s2)
Output:
%i====>int
%d====>int
%f=====>float
%s======>String type
8 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Syntax:
a=10
b=20
c=30
print("a value is %i" %a)
print("b value is %d and c value is %d" %(b,c))
Output
a value is 10
b value is 20 and c value is 30
Eg 2:
s="Durga"
list=[10,20,30,40]
print("Hello %s ...The List of Items are %s" %(s,list))
Output Hello Durga ...The List of Items are [10, 20, 30, 40]
Eg:
name="Durga"
salary=10000
gf="Sunny"
print("Hello {0} your salary is {1} and Your Friend {2} is waiting".format(name,salary,gf))
print("Hello {x} your salary is {y} and Your Friend {z} is waiting".format(x=name,y=salary,z=
gf))
6)
Output
Hello Durga your salary is 10000 and Your Friend Sunny is waiting
Hello Durga your salary is 10000 and Your Friend Sunny is waiting
9 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Flow Control
Flow control describes the order in which statements will be executed at runtime.
Control Flow
1) if 1) break 1) for
2) if-elif 2) continue 2) while
3) if-elif-else 3) pass
Conditional Statements
if
if condition : statement
or
if condition :
statement-1
statement-2
statement-3
If condition is true then statements will be executed.
1 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Eg:
name=input("Enter Name:")
if name=="durga" :
print("Hello Durga Good Morning")
print("How are you!!!")
5)
D:\Python_classes>py test.py
Enter Name:durga
Hello Durga Good Morning
How are you!!!
10)
D:\Python_classes>py test.py
Enter Name:Ravi
How are you!!!
if-else:
if condition :
Action-1
else :
Action-2
if condition is true then Action-1 will be executed otherwise Action-2 will be executed.
Eg:
name=input("Enter Name:")
if name=="durga" :
print("Hello Durga Good Morning")
else:
print("Hello Guest Good Moring")
print("How are you!!!")
7)
D:\Python_classes>py test.py
Enter Name:durga
Hello Durga Good Morning
How are you!!!
12)
D:\Python_classes>py test.py
Enter Name:Ravi
Hello Guest Good Moring
How are you!!!
2 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
if-elif-else:
Syntax:
if condition1:
Action-1
elif condition2:
Action-2
elif condition3:
Action-3
elif condition4:
Action-4
...
else:
Default Action
Eg:
D:\Python_classes>py test.py
Enter Your Favourite Brand:RC
It is childrens brand
D:\Python_classes>py test.py
Enter Your Favourite Brand:KF
It is not that much kick
D:\Python_classes>py test.py
Enter Your Favourite Brand:KALYANI
Other Brands are not recommended
3 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Note:
Q. Write a program to find biggest of given 2 numbers from the commad prompt?
Q. Write a program to find biggest of given 3 numbers from the commad prompt?
4 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Enter Second Number:30
Enter Third Number:20
Biggest Number is: 30
n=int(input("Enter Number:"))
if n>=1 and n<=10 :
print("The number",n,"is in between 1 to 10")
else:
print("The number",n,"is not in between 1 to 10")
Write a program to take a single digit number from the key board and print is value in
English word?
0==>ZERO
1 ==>ONE
3)
n=int(input("Enter a digit from o to 9:"))
if n==0 :
print("ZERO")
elif n==1:
print("ONE")
elif n==2:
print("TWO")
elif n==3:
print("THREE")
elif n==4:
print("FOUR")
elif n==5:
print("FIVE")
elif n==6:
print("SIX")
elif n==7:
print("SEVEN")
elif n==8:
print("EIGHT")
elif n==9:
print("NINE")
else:
print("PLEASE ENTER A DIGIT FROM 0 TO 9")
5 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Iterative Statements
If we want to execute a group of statements multiple times then we should go
for Iterative statements.
for loop
while loop
for loop:
If we want to execute some action for every element present in some sequence(it may
be string or collection)then we should go for for loop.
Syntax:
for x in sequence :
body
s="Sunny Leone"
for x in s :
print(x)
4)
Output
S
u
n
n
y
11)
L
e
o
n
e
6 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Eg 2: To print characters present in string index wise:
for x in range(10) :
print("Hello")
for x in range(11) :
print(x)
for x in range(21) :
if (x%2!=0):
print(x)
for x in range(10,0,-1) :
print(x)
7 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Eg 7: To print sum of numbers presenst inside list
list=eval(input("Enter List:"))
sum=0;
for x in list:
sum=sum+x;
print("The Sum=",sum)
6)
D:\Python_classes>py test.py
Enter List:[10,20,30,40]
The Sum= 100
10)
D:\Python_classes>py test.py
Enter List:[45,67]
The Sum= 112
while loop:
If we want to execute a group of statements iteratively until some condition false,then
we should go for while loop.
Syntax:
while condition :
body
x=1
while x <=10:
print(x)
x=x+1
n=int(input("Enter number:"))
sum=0
i=1
while i<=n:
sum=sum+i
i=i+1
print("The sum of first",n,"numbers is :",sum)
8 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Eg: write a program to prompt user to enter some name until entering Durga
name=""
while name!="durga":
name=input("Enter Name:")
print("Thanks for confirmation")
Infinite Loops:
i=0;
while True :
i=i+1;
print("Hello",i)
Nested Loops:
Sometimes we can take a loop inside another loop,which are also known as nested loops.
Eg:
for i in range(4):
for j in range(4):
print("i=",i," j=",j)
Output
D:\Python_classes>py test.py
7) i= 0 j= 0
8) i= 0 j= 1
9) i= 0 j= 2
10) i= 0 j= 3
11) i= 1 j= 0
12) i= 1 j= 1
13) i= 1 j= 2
14) i= 1 j= 3
15) i= 2 j= 0
16) i= 2 j= 1
17) i= 2 j= 2
18) i= 2 j= 3
19) i= 3 j= 0
20) i= 3 j= 1
21) i= 3 j= 2
22) i= 3 j= 3
9 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Q. Write a program to dispaly *'s in Right angled triangled form
*
**
***
****
*****
******
*******
Alternative way:
*
**
***
****
*****
******
*******
8)
n = int(input("Enter number of rows:"))
for i in range(1,n+1):
print(" " * (n-i),end="")
print("* "*i)
10 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Transfer Statements
break:
We can use break statement inside loops to break loop execution based on
some condition.
Eg:
for i in range(10):
if i==7:
print("processing is enough..plz break")
break
print(i)
6)
D:\Python_classes>py test.py
0
1
2
3
4
5
6
processing is enough..plz break
Eg:
cart=[10,20,600,60,70]
for item in cart:
if item>500:
print("To place this order insurence must be required")
break
print(item)
7)
D:\Python_classes>py test.py
10
20
To place this order insurence must be required
11 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
continue:
We can use continue statement to skip current iteration and continue next iteration.
for i in range(10):
if i%2==0:
continue
print(i)
5)
D:\Python_classes>py test.py
1
3
5
7
9
Eg 2:
cart=[10,20,500,700,50,60]
for item in cart:
if item>=500:
print("We cannot process this item :",item)
continue
print(item)
7)
Output
D:\Python_classes>py test.py
10
20
We cannot process this item : 500
We cannot process this item : 700
50
60
Eg 3:
numbers=[10,20,0,5,0,30]
for n in numbers:
if n==0:
print("Hey how we can divide with zero..just skipping")
continue
print("100/{} = {}".format(n,100/n))
7)
12 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Output
100/10 = 10.0
100/20 = 5.0
Hey how we can divide with zero..just skipping
100/5 = 20.0
Hey how we can divide with zero..just skipping
100/30 = 3.3333333333333335
Inside loop execution,if break statement not executed ,then only else part will
be executed.
Eg:
cart=[10,20,30,40,50]
for item in cart:
if item>=500:
print("We cannot process this order")
break
print(item)
else:
print("Congrats ...all items processed successfully")
Output
10
20
30
40
50
Congrats ...all items processed successfully
Eg:
cart=[10,20,600,30,40,50]
for item in cart:
if item>=500:
print("We cannot process this order")
break
print(item)
else:
print("Congrats ...all items processed successfully")
13 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
9)
Output
D:\Python_classes>py test.py
10
20
We cannot process this order
Q. What is the difference between for loop and while loop in Python?
pass statement:
pass is a keyword in Python.
pass
|- It is an empty statement
|- It is null statement
|- It won't do anything
Eg:
if True:
SyntaxError: unexpected EOF while parsing
if True: pass
==>valid
def m1():
SyntaxError: unexpected EOF while parsing
14 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
def m1(): pass
Sometimes in the parent class we have to declare a function with empty body and child
class responsible to provide proper implementation. Such type of empty body we can
define by using pass keyword. (It is something like abstract method in java)
Eg:
def m1(): pass
Eg:
for i in range(100):
if i%9==0:
print(i)
else:pass
5)
D:\Python_classes>py test.py
0
9
18
27
36
45
54
63
72
81
90
99
del statement:
Eg:
x=10
print(x)
del x
15 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
After deleting a variable we cannot access that variable otherwise we will get NameError.
Eg:
x=10
del x
print(x)
Note:
We can delete variables which are pointing to immutable objects.But we cannot delete
the elements present inside immutable object.
Eg:
s="durga"
print(s)
del s==>valid
del s[0] ==>TypeError: 'str' object doesn't support item deletion
In the case del, the variable will be removed and we cannot access that
variable(unbind operation)
s="durga"
del s
print(s) ==>NameError: name 's' is not defined.
But in the case of None assignment the variable won't be removed but the
corresponding object is eligible for Garbage Collection(re bind operation). Hence after
assigning with None value,we can access that variable.
s="durga"
s=None
3) print(s) # None
16 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
String Data Type
The most commonly used object in any project and in any programming language is String only.
Hence we should aware complete information about String data type.
What is String?
Any sequence of characters within either single quotes or double quotes is considered as a String.
Syntax:
s='durga'
s="durga"
Note: In most of other languges like C, C++,Java, a single character with in single quotes is
treated as char data type value. But in Python we are not having char data type.Hence it is
treated as String only.
Eg:
ch='a'
type(ch)
<class 'str'>
Eg:
s='''durga
software
solutions'''
We can also use triple quotes to use single quotes or double quotes as symbol inside String literal.
Eg:
s='This is ' single quote symbol' ==>invalid
s='This is \' single quote symbol' ==>valid
s="This is ' single quote symbol"====>valid
s='This is " double quotes symbol' ==>valid
s='The "Python Notes" by 'durga' is very helpful' ==>invalid
s="The "Python Notes" by 'durga' is very helpful"==>invalid
s='The \"Python Notes\" by \'durga\' is very helpful'
==>valid s='''The "Python Notes" by 'durga' is very helpful'''
==>valid
1 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
How to access characters of a String:
By using index
By using slice operator
1. By using index:
Eg:
s='durga'
diagram
Eg:
s='durga'
s[0]
'd'
s[4]
'a'
s[-1]
'a'
s[10]
IndexError: string index out of range
Note: If we are trying to access characters of a string with out of range index then we will get
error saying : IndexError
Q. Write a program to accept some string from the keyboard and display its characters
by index wise(both positive and nEgative index)
test.py:
Output:
D:\python_classes>py test.py
Enter Some String:durga
2 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
The character present at positive index 0 and at nEgative index -5 is d
The character present at positive index 1 and at nEgative index -4 is u
The character present at positive index 2 and at nEgative index -3 is r
The character present at positive index 3 and at nEgative index -2 is g
The character present at positive index 4 and at nEgative index -1 is a
Syntax: s[bEginindex:endindex:step]
Note: If we are not specifying bEgin index then it will consider from bEginning of the string.
If we are not specifying end index then it will consider up to end of the string
The default value for step is 1
Eg:
if +ve then it should be forward direction(left to right) and we have to consider bEgin to end-1
if -ve then it should be backward direction(right to left) and we have to consider bEgin to end+1
3 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
***Note:
In the backward direction if end value is -1 then result is always empty.
In the forward direction if end value is 0 then result is always empty.
In forward direction:
default value for bEgin: 0
default value for end: length of string
default value for step: +1
In backward direction:
default value for bEgin: -1
default value for end: -(length of string+1)
Note: Either forward or backward direction, we can take both +ve and -ve values for bEgin and
end index.
print("durga"+"soft") #durgasoft
print("durga"*2) #durgadurga
Note:
To use + operator for Strings, compulsory both arguments should be str type
To use * operator for Strings, compulsory one argument should be str and other argument
should be int
Eg:
s='durga'
print(len(s)) #5
4 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Q. Write a program to access each character of string in forward and backward
direction by using while loop?
Alternative ways:
Checking Membership:
We can check whether the character or string is the member of another string or not by using in
and not in operators
s='durga'
print('d' in s) #True
print('z' in s) #False
Program:
Output:
D:\python_classes>py test.py
Enter main string:durgasoftwaresolutions
Enter sub string:durga
durga is found in main string
D:\python_classes>py test.py
Enter main string:durgasoftwaresolutions
Enter sub string:python
python is not found in main string
Comparison of Strings:
We can use comparison operators (<,<=,>,>=) and equality operators(==,!=) for strings.
Eg:
Output:
D:\python_classes>py test.py
Enter first string:durga
Enter Second string:durga
Both strings are equal
D:\python_classes>py test.py
emove spaces both sides
Eg:
1. find():
s.find(substring)
Returns index of first occurrence of the given substring. If it is not available then we will get -1
Eg:
Note: By default find() method can search total string. We can also specify the boundaries to
search.
s.find(substring,bEgin,end)
Eg:
s="durgaravipavanshiva"
print(s.find('a'))#4
print(s.find('a',7,15))#10
print(s.find('z',7,15))#-1
index() method:
index() method is exactly same as find() method except that if the specified substring is
not available then we will get ValueError.
Eg:
Output:
D:\python_classes>py test.py
Enter main string:learning python is very easy
Enter sub string:python
substring found
D:\python_classes>py test.py
Enter main string:learning python is very easy
Enter sub string:java
substring not found
8 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Q. Program to display all positions of substring in a given main string
Output:
D:\python_classes>py test.py
Enter main string:abbababababacdefg
Enter sub string:a
Found at position 0
Found at position 3
Found at position 5
Found at position 7
Found at position 9
Found at position 11
D:\python_classes>py test.py
Enter main string:abbababababacdefg
Enter sub string:bb
Found at position 1
Eg:
s="abcabcabcabcadda"
print(s.count('a'))
print(s.count('ab'))
print(s.count('a',3,7))
9 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Output:
6
4
2
Eg1:
s="Learning Python is very difficult"
s1=s.replace("difficult","easy")
print(s1)
Output:
Learning Python is very easy
s="ababababababab"
s1=s.replace("a","b")
print(s1)
Output: bbbbbbbbbbbbbb
Q. String objects are immutable then how we can change the content
by using replace() method.
Once we creates string object, we cannot change the content.This non changeable behaviour is
nothing but immutability. If we are trying to change the content by using any method, then with
those changes a new object will be created and changes won't be happend in existing object.
Hence with replace() method also a new object got created but existing object won't be changed.
Eg:
s="abab"
s1=s.replace("a","b")
print(s,"is available at :",id(s))
print(s1,"is available at :",id(s1))
Output:
abab is available at : 4568672
bbbb is available at : 4568704
10 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
In the above example, original object is available and we can see new object which was created
because of replace() method.
Splitting of Strings:
We can split the given string according to specified seperator by using split() method.
l=s.split(seperator)
The default seperator is space. The return type of split() method is List
Eg1:
Output:
durga
software
solutions
Eg2:
s="22-02-2018"
l=s.split('-')
for x in l:
print(x)
Output:
22
02
2018
Joining of Strings:
We can join a group of strings(list or tuple) wrt the given seperator.
s=seperator.join(group of strings)
Eg:
t=('sunny','bunny','chinny')
s='-'.join(t)
print(s)
Output: sunny-bunny-chinny
11 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Eg2:
l=['hyderabad','singapore','london','dubai']
s=':'.join(l)
print(s)
hyderabad:singapore:london:dubai
Eg:
s='learning Python is very Easy'
print(s.upper())
print(s.lower())
print(s.swapcase())
print(s.title())
print(s.capitalize())
Output:
LEARNING PYTHON IS VERY EASY
learning python is very easy
LEARNING pYTHON IS VERY eASY
Learning Python Is Very Easy
Learning python is very easy
s.startswith(substring)
s.endswith(substring)
Eg:
s='learning Python is very easy'
print(s.startswith('learning'))
print(s.endswith('learning'))
print(s.endswith('easy'))
12 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Output:
True
False
True
Eg:
print('Durga786'.isalnum()) #True
print('durga786'.isalpha()) #False
print('durga'.isalpha()) #True
print('durga'.isdigit()) #False
print('786786'.isdigit()) #True
print('abc'.islower()) #True
print('Abc'.islower()) #False
print('abc123'.islower()) #True
print('ABC'.isupper()) #True
print('Learning python is Easy'.istitle()) #False
print('Learning Python Is Easy'.istitle()) #True
print(' '.isspace()) #True
Demo Program:
13 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
print("Non Space Special Character")
D:\python_classes>py test.py
Enter any character:7
Alpha Numeric Character
it is a digit
D:\python_classes>py test.py
Enter any character:a
Alpha Numeric Character
Alphabet character
Lower case alphabet character
D:\python_classes>py test.py
Enter any character:$
Non Space Special Character
D:\python_classes>py test.py
Enter any character:A
Alpha Numeric Character
Alphabet character
Upper case alphabet character
Eg:
name='durga'
salary=10000
age=48
print("{} 's salary is {} and his age is {}".format(name,salary,age))
print("{0} 's salary is {1} and his age is {2}".format(name,salary,age))
print("{x} 's salary is {y} and his age is {z}".format(z=age,y=salary,x=name))
Output:
durga 's salary is 10000 and his age is 48
durga 's salary is 10000 and his age is 48
durga 's salary is 10000 and his age is 48
14 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Important Programs rEgarding String Concept
Q1. Write a program to reverse the given String
input: durga
output:agrud
st
1 Way:
nd
2 Way:
rd
3 Way:
Output:
Enter Some String:Learning Python is very easy!!
easy!!! very is Python Learning
15 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Q3. Program to reverse internal content of each word.
Q4. Write a program to print characters at odd position and even position for the
given String?
st
1 Way:
nd
2 Way:
Q5. Program to merge characters of 2 strings into a single string by taking characters
alternatively.
s1="ravi"
s2="reja"
output: rtaevjia
16 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
s1=input("Enter First String:")
s2=input("Enter Second String:")
output=''
i,j=0,0
while i<len(s1) or j<len(s2):
if i<len(s1):
output=output+s1[i]
i+=1
if j<len(s2):
output=output+s2[j]
j+=1
print(output)
Output:
Enter First String:durga
Enter Second String:ravisoft
druarvgiasoft
Q6. Write a program to sort the characters of the string and first alphabet
symbols followed by numeric values
input: B4A1D3
Output: ABD134
input: a4b3c2
output: aaaabbbcc
17 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
else:
output=output+previous*(int(x)-1)
print(output)
input: a4k3b2
output:aeknbd
Q9. Write a program to remove duplicate characters from the given input string?
input: ABCDABBCDABBBCCCDDEEEF
output: ABCDEF
Q10. Write a program to find the number of occurrences of each character present in
the given String?
input: ABCABCABBCDE
output: A-3,B-4,C-3,D-1,E-1
18 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
for k,v in d.items():
print("{} = {} Times".format(k,v))
The main objective of format() method to format string into meaningful output form.
name='durga'
salary=10000
age=48
print("{} 's salary is {} and his age is {}".format(name,salary,age))
print("{0} 's salary is {1} and his age is {2}".format(name,salary,age))
print("{x} 's salary is {y} and his age is {z}".format(z=age,y=salary,x=name))
Output:
durga 's salary is 10000 and his age is 48
durga 's salary is 10000 and his age is 48
durga 's salary is 10000 and his age is 48
d--->Decimal IntEger
f----->Fixed point number(float).The default precision is 6
b-->Binary format
o--->Octal Format
x-->Hexa Decimal Format(Lower case)
X-->Hexa Decimal Format(Upper case)
Eg-1:
print("The intEger number is: {}".format(123))
print("The intEger number is: {:d}".format(123))
print("The intEger number is: {:5d}".format(123))
print("The intEger number is: {:05d}".format(123))
Output:
The intEger number is: 123
The intEger number is: 123
The intEger number is: 123
The intEger number is: 00123
Eg-2:
print("The float number is: {}".format(123.4567))
print("The float number is: {:f}".format(123.4567))
19 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
print("The float number is: {:8.3f}".format(123.4567))
print("The float number is: {:08.3f}".format(123.4567))
print("The float number is: {:08.3f}".format(123.45))
print("The float number is: {:08.3f}".format(786786123.45))
Output:
The float number is: 123.4567
The float number is: 123.456700
The float number is: 123.457
The float number is: 0123.457
The float number is: 0123.450
The float number is: 786786123.450
Note:
{:08.3f}
print("Binary Form:{0:b}".format(153))
print("Octal Form:{0:o}".format(153))
print("Hexa decimal Form:{0:x}".format(154))
print("Hexa decimal Form:{0:X}".format(154))
Output:
Binary Form:10011001
Octal Form:231
Hexa decimal Form:9a
Hexa decimal Form:9A
Note: We can represent only int values in binary, octal and hexadecimal and it is not possible for
float values.
Note:
{:5d} It takes an intEger argument and assigns a minimum width of 5.
{:8.3f} It takes a float argument and assigns a minimum width of 8 including "." and after decimal
point excatly 3 digits are allowed with round operation if required {:05d} The blank places can be
filled with 0. In this place only 0 allowed.
20 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Case-3: Number formatting for signed numbers
Using plus for -ve numbers there is no use and for -ve numbers - sign will come automatically.
Output:
int value with sign:+123
int value with sign:-123
float value with sign:+123.456000
float value with sign:-123.456000
Ex:
print("{:5d}".format(12))
print("{:<5d}".format(12))
print("{:<05d}".format(12))
print("{:>5d}".format(12))
print("{:>05d}".format(12))
print("{:^5d}".format(12))
print("{:=5d}".format(-12))
print("{:^10.3f}".format(12.23456))
print("{:=8.3f}".format(-12.23456))
Output:
12
12
12000
12
00012
12
-12
21 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
12.235
- 12.235
Similar to numbers, we can format String values also with format() method.
s.format(string)
Eg:
print("{:5d}".format(12))
print("{:5}".format("rat"))
print("{:>5}".format("rat"))
print("{:<5}".format("rat"))
print("{:^5}".format("rat"))
print("{:*^5}".format("rat")) #Instead of * we can use any character(like +,$,a etc)
Output:
12
rat
rat
rat
rat
*rat*
Note: For numbers default alignment is right where as for strings default alignment is left
print("{:.3}".format("durgasoftware"))
print("{:5.3}".format("durgasoftware"))
print("{:>5.3}".format("durgasoftware"))
print("{:^5.3}".format("durgasoftware"))
print("{:*^5.3}".format("durgasoftware"))
Output:
dur
dur
dur
dur
*dur*
person={'age':48,'name':'durga'}
print("{p[name]}'s age is: {p[age]}".format(p=person))
22 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Output:
durga's age is: 48
Note: p is alias name of dictionary
person dictionary we are passing as keyword argument
Eg:
person={'age':48,'name':'durga'}
print("{name}'s age is: {age}".format(**person))
Output:
durga's age is: 48
Eg:
class Person:
age=48
name="durga"
print("{p.name}'s age is :{p.age}".format(p=Person()))
Output:
durga's age is :48
Eg:
class Person:
def __init__(self,name,age):
self.name=name
self.age=age
print("{p.name}'s age is :{p.age}".format(p=Person('durga',48)))
print("{p.name}'s age is :{p.age}".format(p=Person('Ravi',50)))
Note: Here Person object is passed as keyword argument. We can access by using its
reference variable in the template string
string="{:{fill}{align}{width}}"
print(string.format('cat',fill='*',align='^',width=5))
print(string.format('cat',fill='*',align='^',width=6))
print(string.format('cat',fill='*',align='<',width=6))
print(string.format('cat',fill='*',align='>',width=6))
23 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Output:
*cat*
*cat**
cat***
***cat
num="{:{align}{width}.{precision}f}"
print(num.format(123.236,align='<',width=8,precision=2))
print(num.format(123.236,align='>',width=8,precision=2))
Output:
123.24
123.24
import datetime
#datetime formatting
date=datetime.datetime.now()
print("It's now:{:%d/%m/%Y %H:%M:%S}".format(date))
complexNumber=1+2j
print("Real Part:{0.real} and Imaginary Part:{0.imag}".format(complexNumber))
24 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
List Data Structure
If we want to represent a group of individual objects as a single entity where
insertion order preserved and duplicates are allowed, then we should go for List.
-6 -5 -4 -3 -2 -1
10 A B 20 30 10
0 1 2 3 4 5
list=[]
print(list)
print(type(list))
4)
[]
<class 'list'>
1 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
With dynamic input:
list=eval(input("Enter List:"))
print(list)
print(type(list))
4)
D:\Python_classes>py test.py
Enter List:[10,20,30,40]
[10, 20, 30, 40]
<class 'list'>
l=list(range(0,10,2))
print(l)
print(type(l))
4)
D:\Python_classes>py test.py
[0, 2, 4, 6, 8]
<class 'list'>
Eg:
s="durga"
l=list(s)
print(l)
4)
D:\Python_classes>py test.py
['d', 'u', 'r', 'g', 'a']
Note:
Sometimes we can take list inside another list,such type of lists are called nested
lists. [10,20,[30,40]]
2 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Accessing elements of List:
We can access elements of the list either by using index or by using slice operator(:)
1. By using index:
list=[10,20,30,40]
-4 -3 -2 -1
list 10 20 30 40
0 1 2 3
print(list[0]) ==>10
print(list[-1]) ==>40
print(list[10]) ==>IndexError: list index out of range
Syntax:
list2= list1[start:stop:step]
Eg:
n=[1,2,3,4,5,6,7,8,9,10]
print(n[2:7:2])
print(n[4::2])
print(n[3:7])
print(n[8:2:-2])
print(n[4:100])
3 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
7)
Output
D:\Python_classes>py test.py
[3, 5, 7]
[5, 7, 9]
[4, 5, 6, 7]
[9, 7, 5]
[5, 6, 7, 8, 9, 10]
List vs mutability:
Once we creates a List object,we can modify its content. Hence List objects are mutable.
Eg:
n=[10,20,30,40]
print(n)
n[1]=777
print(n)
5)
D:\Python_classes>py test.py
[10, 20, 30, 40]
[10, 777, 30, 40]
n=[0,1,2,3,4,5,6,7,8,9,10]
i=0
while i<len(n):
print(n[i])
i=i+1
6)
D:\Python_classes>py test.py
0
1
2
3
4
5
6
7
8
9
4 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
10
n=[0,1,2,3,4,5,6,7,8,9,10]
for n1 in n:
print(n1)
4)
D:\Python_classes>py test.py
0
1
2
3
4
5
6
7
8
9
10
n=[0,1,2,3,4,5,6,7,8,9,10]
for n1 in n:
if n1%2==0:
print(n1)
5)
D:\Python_classes>py test.py
0
2
4
6
8
10
l=["A","B","C"]
x=len(l)
for i in range(x):
print(l[i],"is available at positive index: ",i,"and at negative index: ",i-x)
Output
D:\Python_classes>py test.py
A is available at positive index: 0 and at negative index: -3
B is available at positive index: 1 and at negative index: -2
C is available at positive index: 2 and at negative index: -1
5 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Important functions of List:
I. To get information about list:
1. len():
returns the number of elements present in the list
Eg: n=[10,20,30,40]
print(len(n))==>4
2. count():
It returns the number of occurrences of specified item in the list
n=[1,2,2,2,2,3,3]
print(n.count(1))
print(n.count(2))
print(n.count(3))
print(n.count(4))
Output
D:\Python_classes>py test.py
1
4
2
0
3. index() function:
Eg:
n=[1,2,2,2,2,3,3]
print(n.index(1)) ==>0
print(n.index(2)) ==>1
print(n.index(3)) ==>5
5) print(n.index(4)) ==>ValueError: 4 is not in list
Note: If the specified element not present in the list then we will get ValueError.Hence
before index() method we have to check whether item present in the list or not by using
in operator.
print( 4 in n)==>False
6 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
II. Manipulating elements of List:
1. append() function:
We can use append() function to add item at the end of the list.
Eg:
list=[]
list.append("A")
list.append("B")
list.append("C")
print(list)
6)
D:\Python_classes>py test.py
['A', 'B', 'C']
Eg: To add all elements to list upto 100 which are divisible by 10
list=[]
for i in range(101):
if i%10==0:
list.append(i)
print(list)
6)
7)
D:\Python_classes>py test.py
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
insert() function:
n=[1,2,3,4,5]
n.insert(1,888)
print(n)
4)
D:\Python_classes>py test.py
[1, 888, 2, 3, 4, 5]
Eg:
n=[1,2,3,4,5]
n.insert(10,777)
n.insert(-10,999)
print(n)
5)
7 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
D:\Python_classes>py test.py
[999, 1, 2, 3, 4, 5, 777]
Note: If the specified index is greater than max index then element will be inserted at
last position. If the specified index is smaller than min index then element will be inserted
at first position.
3. extend() function:
l1.extend(l2)
all items present in l2 will be added to l1
Eg:
order1=["Chicken","Mutton","Fish"]
order2=["RC","KF","FO"]
order1.extend(order2)
print(order1)
5)
D:\Python_classes>py test.py
['Chicken', 'Mutton', 'Fish', 'RC', 'KF', 'FO']
Eg:
order=["Chicken","Mutton","Fish"]
order.extend("Mushroom")
print(order)
4)
D:\Python_classes>py test.py
['Chicken', 'Mutton', 'Fish', 'M', 'u', 's', 'h', 'r', 'o', 'o', 'm']
remove() function:
We can use this function to remove specified item from the list.If the item
present multiple times then only first occurrence will be removed.
8 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
n=[10,20,10,30]
n.remove(10)
print(n)
4)
D:\Python_classes>py test.py
[20, 10, 30]
If the specified item not present in list then we will get ValueError
n=[10,20,10,30]
n.remove(40)
print(n)
4)
ValueError: list.remove(x): x not in list
Note: Hence before using remove() method first we have to check specified
element present in the list or not by using in operator.
5. pop() function:
Eg:
n=[10,20,30,40]
print(n.pop())
print(n.pop())
print(n)
5)
D:\Python_classes>py test.py
40
30
[10, 20]
Eg:
n=[]
2) print(n.pop()) ==> IndexError: pop from empty list
9 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Note:
pop() is the only function which manipulates the list and returns some value
In general we can use append() and pop() functions to implement stack datastructure
by using list,which follows LIFO(Last In First Out) order.
In general we can use pop() function to remove last element of the list. But we can use
to remove elements based on index.
n=[10,20,30,40,50,60]
print(n.pop()) #60
print(n.pop(1)) #20
print(n.pop(10)) ==>IndexError: pop index out of range
remove() pop()
1) We can use to remove special element 1) We can use to remove last element
from the List. from the List.
2) It can’t return any value. 2) It returned removed element.
3) If special element not available then we 3) If List is empty then we get Error.
get VALUE ERROR.
Note:
List objects are dynamic. i.e based on our requirement we can increase and decrease
the size.
10 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
III. Ordering elements of List:
1. reverse():
n=[10,20,30,40]
n.reverse()
print(n)
4)
D:\Python_classes>py test.py
[40, 30, 20, 10]
sort() function:
In list by default insertion order is preserved. If want to sort the elements of list
according to default natural sorting order then we should go for sort() method.
n=[20,5,15,10,0]
n.sort()
print(n) #[0,5,10,15,20]
s=["Dog","Banana","Cat","Apple"]
s.sort()
print(s) #['Apple','Banana','Cat','Dog']
Note: To use sort() function, compulsory list should contain only homogeneous
elements. otherwise we will get TypeError
Eg:
n=[20,10,"A","B"]
n.sort()
print(n)
4)
TypeError: '<' not supported between instances of 'str' and 'int'
Note: In Python 2 if List contains both numbers and Strings then sort() function first
sort numbers followed by strings
n=[20,"B",10,"A"]
n.sort()
11 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
print(n)# [10,20,'A','B']
We can sort according to reverse of default natural sorting order by using reverse=True
argument.
Eg:
n=[40,10,30,20]
n.sort()
print(n) ==>[10,20,30,40]
n.sort(reverse=True)
print(n) ===>[40,30,20,10]
n.sort(reverse=False)
print(n) ==>[10,20,30,40]
Eg:
x=[10,20,30,40]
2) y=x 10 20 30 40
3) print(id(x)) x
4) print(id(y)) y
The problem in this approach is by using one reference variable if we are changing
content,then those changes will be reflected to the other reference variable.
1) x=[10,20,30,40]
2) y=x 10 20 30 40
3) y[1]=777 x 777
4) print(x) ==>[10,777,30,40] y
12 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
By using slice operator:
x=[10,20,30,40]
y=x[:]
y[1]=777
print(x) ==>[10,20,30,40]
print(y) ==>[10,777,30,40]
10 20 30 40
x
10 20 30 40
777
y
x=[10,20,30,40]
y=x.copy()
y[1]=777
print(x) ==>[10,20,30,40]
print(y) ==>[10,777,30,40]
10 20 30 40
x
10 20 30 40
777
y
13 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Using Mathematical operators for List Objects:
We can use + and * operators for List objects.
1. Concatenation operator(+):
a=[10,20,30]
b=[40,50,60]
c=a+b
print(c) ==>[10,20,30,40,50,60]
Eg:
2. Repetition Operator(*):
We can use repetition operator * to repeat elements of list specified number of times
Eg:
x=[10,20,30]
y=x*3
print(y)==>[10,20,30,10,20,30,10,20,30]
Eg:
x=["Dog","Cat","Rat"]
y=["Dog","Cat","Rat"]
z=["DOG","CAT","RAT"]
print(x==y) True
print(x==z) False
6. print(x != z) True
14 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Note:
Whenever we are using comparison operators(==,!=) for List objects then the following
should be considered
The number of elements
The order of elements
The content of elements (case sensitive)
Eg:
x=[50,20,30]
y=[40,50,60,100,200]
print(x>y) True
print(x>=y) True
print(x<y) False
print(x<=y) False
Eg:
x=["Dog","Cat","Rat"]
y=["Rat","Cat","Dog"]
print(x>y) False
print(x>=y) False
print(x<y) True
print(x<=y) True
Membership operators:
We can check whether element is a member of the list or not by using
memebership operators.
in operator
not in operator
Eg:
n=[10,20,30,40]
print (10 in n)
print (10 not in n)
print (50 in n)
print (50 not in n)
Output
15 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
True
False
False
True
clear() function:
Eg:
n=[10,20,30,40]
print(n)
n.clear()
print(n)
5.
Output
D:\Python_classes>py test.py
[10, 20, 30, 40]
[]
Nested Lists:
Sometimes we can take one list inside another list. Such type of lists are called
nested lists.
Eg:
n=[10,20,[30,40]]
print(n)
print(n[0])
print(n[2])
print(n[2][0])
print(n[2][1])
7.
Output
D:\Python_classes>py test.py
[10, 20, [30, 40]]
10
[30, 40]
30
40
Note: We can access nested list elements by using index just like accessing
multi dimensional array elements.
16 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Nested List as Matrix:
In Python we can represent matrix by using nested lists.
n=[[10,20,30],[40,50,60],[70,80,90]]
print(n)
print("Elements by Row wise:")
for r in n:
print(r)
print("Elements by Matrix style:")
for i in range(len(n)):
for j in range(len(n[i])):
print(n[i][j],end=' ')
print()
11)
Output
D:\Python_classes>py test.py
[[10, 20, 30], [40, 50, 60], [70, 80, 90]]
Elements by Row wise:
[10, 20, 30]
[40, 50, 60]
[70, 80, 90]
Elements by Matrix style:
10 20 30
40 50 60
70 80 90
List Comprehensions:
It is very easy and compact way of creating list objects from any iterable
objects(like list,tuple,dictionary,range etc) based on some condition.
Syntax:
list=[expression for item in list if condition]
Eg:
17 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
[2, 4, 8, 16, 32]
[4, 16, 36, 64, 100]
Eg:
words=["Balaiah","Nag","Venkatesh","Chiranjeevi"]
l=[w[0] for w in words]
print(l)
4)
Output['B', 'N', 'V', 'C']
Eg:
num1=[10,20,30,40]
num2=[30,40,50,60]
num3=[ i for i in num1 if i not in num2]
print(num3) [10,20]
5)
common elements present in num1 and num2
num4=[i for i in num1 if i in num2]
print(num4) [30, 40]
Eg:
Output
['the', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog']
[['THE', 3], ['QUICK', 5], ['BROWN', 5], ['FOX', 3], ['JUMPS', 5], ['OVER', 4],
['THE', 3], ['LAZY', 4], ['DOG', 3]]
vowels=['a','e','i','o','u']
word=input("Enter the word to search for vowels: ")
found=[]
for letter in word:
if letter in vowels:
if letter not in found:
found.append(letter)
print(found)
print("The number of different vowels present in",word,"is",len(found))
D:\Python_classes>py test.py
18 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Enter the word to search for vowels: durgasoftwaresolutions
['u', 'a', 'o', 'e', 'i']
The number of different vowels present in durgasoftwaresolutions is 5
list out all functions of list and write a program to use these functions
19 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Tuple Data Structure
Tuple is exactly same as List except that it is immutable. i.e once we creates Tuple
object,we cannot perform any changes in that object.
Hence Tuple is Read Only version of List.
If our data is fixed and never changes then we should go for Tuple.
Insertion Order is preserved
Duplicates are allowed
Heterogeneous objects are allowed.
We can preserve insertion order and we can differentiate duplicate objects by using
index. Hence index will play very important role in Tuple also.
Tuple support both +ve and -ve index. +ve index means forward direction(from left
to right) and -ve index means backward direction(from right to left)
We can represent Tuple elements within Parenthesis and with comma seperator.
Parenethesis are optional but recommended to use.
Eg:
t=10,20,30,40
print(t)
print(type(t))
Output
(10, 20, 30, 40)
<class 'tuple'>
t=()
print(type(t)) # tuple
Note: We have to take special care about single valued tuple.compulsary the
value should ends with comma,otherwise it is not treated as tuple.
Eg:
t=(10)
print(t)
print(type(t))
Output
10
<class 'int'>
DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 040 –
64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Eg:
t=(10,)
print(t)
print(type(t))
0 Output
1 (10,)
2 <class 'tuple'>
t=()
t=10,20,30,40
t=10
t=10,
t=(10)
t=(10,)
7.t=(10,20,30,40)
Tuple creation:
1. t=()
creation of empty tuple
2. t=(10,)
t=10,
creation of single valued tuple ,parenthesis are optional,should ends with comma
3. t=10,20,30
t=(10,20,30)
creation of multi values tuples & parenthesis are optional
list=[10,20,30]
t=tuple(list)
print(t)
4.
t=tuple(range(10,20,2))
print(t)
2 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Accessing elements of tuple:
We can access either by index or by slice operator
By using index:
t=(10,20,30,40,50,60)
print(t[0]) #10
print(t[-1]) #60
print(t[100]) IndexError: tuple index out of range
t=(10,20,30,40,50,60)
print(t[2:5])
print(t[2:100])
print(t[::2])
5.
Output
(30, 40, 50)
(30, 40, 50, 60)
(10, 30, 50)
Tuple vs immutability:
Once we creates tuple,we cannot change its content.
Hence tuple objects are immutable.
Eg:
t=(10,20,30,40)
t[1]=70 TypeError: 'tuple' object does not support item assignment
Concatenation Operator(+):
t1=(10,20,30)
t2=(40,50,60)
t3=t1+t2
print(t3) # (10,20,30,40,50,60)
3 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Multiplication operator or repetition operator(*)
t1=(10,20,30)
t2=t1*3
print(t2) #(10,20,30,10,20,30,10,20,30)
1. len()
To return number of elements present in the tuple
Eg:
t=(10,20,30,40)
print(len(t)) #4
2. count()
To return number of occurrences of given element in the tuple
Eg:
t=(10,20,10,10,20)
print(t.count(10)) #3
3. index()
returns index of first occurrence of the given element.
If the specified element is not available then we will get ValueError.
Eg:
t=(10,20,10,10,20)
print(t.index(10)) #0
print(t.index(30)) ValueError: tuple.index(x): x not in tuple
4. sorted()
To sort elements based on default natural sorting order
t=(40,10,30,20)
t1=sorted(t)
print(t1)
print(t)
5.
Output
[10, 20, 30, 40]
(40, 10, 30, 20)
4 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
t1=sorted(t,reverse=True)
print(t1) [40, 30, 20, 10]
These functions return min and max values according to default natural sorting order.
Eg:
t=(40,10,30,20)
print(min(t)) #10
print(max(t)) #40
cmp():
Eg:
t1=(10,20,30)
t2=(40,50,60)
t3=(10,20,30)
print(cmp(t1,t2)) # -1
print(cmp(t1,t3)) # 0
print(cmp(t2,t3)) # +1
Eg:
a=10
b=20
c=30
d=40
t=a,b,c,d
print(t) #(10, 20, 30, 40)
Here a,b,c,d are packed into a tuple t. This is nothing but tuple packing.
5 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Tuple unpacking is the reverse process of tuple packing
We can unpack a tuple and assign its values to different variables
Eg:
t=(10,20,30,40)
a,b,c,d=t
print("a=",a,"b=",b,"c=",c,"d=",d)
Output
a= 10 b= 20 c= 30 d= 40
Note: At the time of tuple unpacking the number of variables and number of values
should be same. ,otherwise we will get ValueError.
Eg:
t=(10,20,30,40)
a,b,c=t #ValueError: too many values to unpack (expected 3)
Tuple Comprehension:
Tuple Comprehension is not supported by Python.
Here we are not getting tuple object and we are getting generator object.
6 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Write a program to take a tuple of numbers from the keyboard and print its sum and
average?
List Tuple
1) List is a Group of Comma separeated 1) Tuple is a Group of Comma separeated
Values within Square Brackets and Square Values within Parenthesis and Parenthesis
Brackets are mandatory. are optional.
Eg: i = [10, 20, 30, 40] Eg: t = (10, 20, 30, 40)
t = 10, 20, 30, 40
2) List Objects are Mutable i.e. once we 2) Tuple Objeccts are Immutable i.e. once
creates List Object we can perform any we creates Tuple Object we cannot change
changes in that Object. its content.
Eg: i[1] = 70 t[1] = 70 ValueError: tuple object does
not support item assignment.
3) If the Content is not fixed and keep on 3) If the content is fixed and never changes
changing then we should go for List. then we should go for Tuple.
4) List Objects can not used as Keys for 4) Tuple Objects can be used as Keys for
Dictionries because Keys should be Dictionries because Keys should be
Hashable and Immutable. Hashable and Immutable.
7 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
8 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Set Data Structure
If we want to represent a group of unique values as a single entity then we should go for set.
Duplicates are not allowed.
Insertion order is not preserved.But we can sort the elements.
Indexing and slicing not allowed for the set.
Heterogeneous elements are allowed.
Set objects are mutable i.e once we creates set object we can perform any changes in that object
based on our requirement.
We can represent set elements within curly braces and with comma seperation
We can apply mathematical operations like union,intersection,difference etc on set objects.
s={10,20,30,40}
print(s)
print(type(s))
Output
{40, 10, 20, 30}
<class 'set'>
s=set(any sequence)
Eg 1:
l = [10,20,30,40,10,20,10]
s=set(l)
print(s) # {40, 10, 20, 30}
Eg 2:
s=set(range(5))
print(s) #{0, 1, 2, 3, 4}
1 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
s={} ==>It is treated as dictionary but not empty set.
Eg:
s={}
print(s)
print(type(s))
Output
{}
<class 'dict'>
Eg:
s=set()
print(s)
print(type(s))
Output
set()
<class 'set'>
Eg:
s={10,20,30}
s.add(40);
print(s) #{40, 10, 20, 30}
update(x,y,z):
Eg:
s={10,20,30}
l=[40,50,60,10]
s.update(l,range(5))
print(s)
2 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
5.
Output
{0, 1, 2, 3, 4, 40, 10, 50, 20, 60, 30}
We can use add() to add individual item to the Set,where as we can use update()
function to add multiple items to Set.
add() function can take only one argument where as update() function can take any
number of arguments but all arguments should be iterable objects.
1. s.add(10)
2. s.add(10,20,30) TypeError: add() takes exactly one argument (3 given)
3. s.update(10) TypeError: 'int' object is not iterable
s.update(range(1,10,2),range(0,10,2))
copy():
s={10,20,30}
s1=s.copy()
print(s1)
4. pop():
Eg:
s={40,10,30,20}
print(s)
print(s.pop())
print(s)
5.
Output
{40, 10, 20, 30}
40
{10, 20, 30}
3 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
5. remove(x):
s={40,10,30,20}
s.remove(30)
print(s) # {40, 10, 20}
s.remove(50) ==>KeyError: 50
6. discard(x):
s={10,20,30}
s.discard(10)
print(s) ===>{20, 30}
s.discard(50)
print(s) ==>{20, 30}
7.clear():
s={10,20,30}
print(s)
s.clear()
print(s)
5.
Output
{10, 20, 30}
set()
4 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Mathematical operations on the Set:
1.union():
x.union(y) ==>We can use this function to return all elements present in both sets
x.union(y) or x|y
Eg:
x={10,20,30,40}
y={30,40,50,60}
print(x.union(y)) #{10, 20, 30, 40, 50, 60}
print(x|y) #{10, 20, 30, 40, 50, 60}
2. intersection():
x.intersection(y) or x&y
Eg:
x={10,20,30,40}
y={30,40,50,60}
print(x.intersection(y)) #{40, 30}
print(x&y) #{40, 30}
3. difference():
x.difference(y) or x-y
returns the elements present in x but not in y
Eg:
x={10,20,30,40}
y={30,40,50,60}
print(x.difference(y)) #{10, 20}
print(x-y) #{10, 20}
print(y-x) #{50, 60}
5 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
4.symmetric_difference():
x.symmetric_difference(y) or x^y
Eg:
x={10,20,30,40}
y={30,40,50,60}
print(x.symmetric_difference(y)) #{10, 50, 20, 60}
print(x^y) #{10, 50, 20, 60}
s=set("durga")
print(s)
print('d' in s)
print('z' in s)
Output
{'u', 'g', 'r', 'd', 'a'}
True
False
Set Comprehension:
Set comprehension is possible.
6 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Q.Write a program to eliminate duplicates present in the list?
Approach-1:
Approach-2:
7 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Dictionary Data Structure
We can use List,Tuple and Set to represent a group of individual objects as a single entity.
Eg:
rollno----name
phone number--address
ipaddress---domain name
Note: In C++ and Java Dictionaries are known as "Map" where as in Perl and Ruby it
is known as "Hash"
d[100]="durga"
d[200]="ravi"
d[300]="shiva"
print(d) #{100: 'durga', 200: 'ravi', 300: 'shiva'}
d={key:value, key:value}
1 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
How to access data from the dictionary?
We can access data by using keys.
if 400 in d:
print(d[400])
rec={}
n=int(input("Enter number of students: "))
i=1
while i <=n:
name=input("Enter Student Name: ")
marks=input("Enter % of Marks of Student: ")
rec[name]=marks
i=i+1
print("Name of Student","\t","% of marks")
for x in rec:
print("\t",x,"\t\t",rec[x])
12)
Output
D:\Python_classes>py test.py
Enter number of students: 3
Enter Student Name: durga
Enter % of Marks of Student: 60%
Enter Student Name: ravi
Enter % of Marks of Student: 70%
Enter Student Name: shiva
2 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Enter % of Marks of Student: 80%
22) Name of Student % of marks
23) durga 60%
24) ravi 70 %
25) shiva 80%
If the key is not available then a new entry will be added to the dictionary with
the specified key-value pair
If the key is already available then old value will be replaced with new value.
Eg:
d={100:"durga",200:"ravi",300:"shiva"}
print(d)
d[400]="pavan"
print(d)
d[100]="sunny"
print(d)
7.
Output
{100: 'durga', 200: 'ravi', 300: 'shiva'}
{100: 'durga', 200: 'ravi', 300: 'shiva', 400: 'pavan'}
{100: 'sunny', 200: 'ravi', 300: 'shiva', 400: 'pavan'}
Eg:
d={100:"durga",200:"ravi",300:"shiva"}
print(d)
del d[100]
print(d)
del d[400]
6.
Output
{100: 'durga', 200: 'ravi', 300: 'shiva'}
3 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
{200: 'ravi', 300: 'shiva'}
KeyError: 400
d.clear()
Eg:
d={100:"durga",200:"ravi",300:"shiva"}
print(d)
d.clear()
print(d)
5.
Output
{100: 'durga', 200: 'ravi', 300: 'shiva'}
{}
del d
Eg:
d={100:"durga",200:"ravi",300:"shiva"}
print(d)
del d
print(d)
5.
Output
{100: 'durga', 200: 'ravi', 300: 'shiva'}
NameError: name 'd' is not defined
To create a dictionary
4 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
2. len()
3. clear():
4. get():
d.get(key)
If the key is available then returns the corresponding value otherwise returns
None.It wont raise any error.
d.get(key,defaultvalue)
If the key is available then returns the corresponding value otherwise returns
default value.
Eg:
d={100:"durga",200:"ravi",300:"shiva"}
print(d[100]) ==>durga
print(d[400]) ==>KeyError:400
print(d.get(100)) ==durga
print(d.get(400)) ==>None
print(d.get(100,"Guest")) ==durga
print(d.get(400,"Guest")) ==>Guest
3. pop():
d.pop(key)
It removes the entry associated with the specified key and returns the
corresponding value
If the specified key is not available then we will get KeyError
Eg:
d={100:"durga",200:"ravi",300:"shiva"}
print(d.pop(100))
print(d)
print(d.pop(400))
5)
Output
5 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
durga
{200: 'ravi', 300: 'shiva'}
KeyError: 400
popitem():
Eg:
d={100:"durga",200:"ravi",300:"shiva"}
print(d)
print(d.popitem())
print(d)
5)
Output
{100: 'durga', 200: 'ravi', 300: 'shiva'}
(300, 'shiva')
{100: 'durga', 200: 'ravi'}
5. keys():
Eg:
d={100:"durga",200:"ravi",300:"shiva"}
print(d.keys())
for k in d.keys():
print(k)
5)
Output
dict_keys([100, 200, 300])
100
200
300
6. values():
6 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Eg:
d={100:"durga",200:"ravi",300:"shiva"}
print(d.values())
for v in d.values():
print(v)
5.
Output
dict_values(['durga', 'ravi', 'shiva'])
durga
ravi
shiva
7. items():
[(k,v),(k,v),(k,v)]
Eg:
d={100:"durga",200:"ravi",300:"shiva"}
for k,v in d.items():
print(k,"--",v)
4.
Output
100 -- durga
200 -- ravi
300 -- shiva
copy():
d1=d.copy();
9. setdefault():
d.setdefault(k,v)
If the key is already available then this function returns the corresponding value.
If the key is not available then the specified key-value will be added as new item to
the dictionary.
7 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Eg:
d={100:"durga",200:"ravi",300:"shiva"}
print(d.setdefault(400,"pavan"))
print(d)
print(d.setdefault(100,"sachin"))
print(d)
6.
Output
pavan
{100: 'durga', 200: 'ravi', 300: 'shiva', 400: 'pavan'}
durga
{100: 'durga', 200: 'ravi', 300: 'shiva', 400: 'pavan'}
10. update():
d.update(x)
All items present in the dictionary x will be added to dictionary d
Q. Write a program to take dictionary from the keyboard and print the sum
of values?
d=eval(input("Enter dictionary:"))
s=sum(d.values())
print("Sum= ",s)
4.
Output
D:\Python_classes>py test.py
Enter dictionary:{'A':100,'B':200,'C':300}
Sum= 600
8 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
p occurred 2 times
Write a program to accept student name and marks from the keyboard and
creates a dictionary. Also display student marks by taking student name as
input?
Dictionary Comprehension:
Comprehension concept applicable for dictionaries also.
10 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
FUNCTIONS
If a group of statements is repeatedly required then it is not recommended to write
these statements everytime seperately.We have to define these statements as a single
unit and we can call that unit any number of times based on our requirement without
rewriting. This unit is nothing but function.
Built in Functions
User Defined Functions
1. Built in Functions:
The functions which are coming along with Python software automatically,are called built
in functions or pre defined functions
Eg:
id()
type()
input()
eval()
etc..
def function_name(parameters) :
doc string"""
----
-----
return value
DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 040 –
64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Note: While creating functions we can use 2 keywords
def (mandatory)
return (optional)
test.py:
def wish():
print("Hello Good Morning")
wish()
wish()
wish()
Parameters
Parameters are inputs to the function. If a function contains parameters,then at the time of
calling,compulsory we should provide values otherwise,otherwise we will get error.
Eg: Write a function to take name of the student as input and print wish message
by name.
def wish(name):
print("Hello",name," Good Morning")
wish("Durga")
wish("Ravi")
5.
6.
D:\Python_classes>py test.py
Hello Durga Good Morning
Hello Ravi Good Morning
Eg: Write a function to take number as input and print its square value
def squareIt(number):
print("The Square of",number,"is", number*number)
squareIt(4)
squareIt(5)
5.
D:\Python_classes>py test.py
The Square of 4 is 16
The Square of 5 is 25
2 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Return Statement:
Function can take input values as parameters and executes business logic, and returns
output to the caller with return statement.
def add(x,y):
return x+y
result=add(10,20)
print("The sum is",result)
print("The sum is",add(100,200))
D:\Python_classes>py test.py
The sum is 30
The sum is 300
If we are not writing return statement then default return value is None
Eg:
def f1():
print("Hello")
f1()
print(f1())
5.
Output
Hello
Hello
None
def even_odd(num):
if num%2==0:
print(num,"is Even Number")
else:
print(num,"is Odd Number")
even_odd(10)
even_odd(15)
8.
Output
D:\Python_classes>py test.py
10 is Even Number
15 is Odd Number
3 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Q. Write a function to find factorial of given number?
def fact(num):
result=1
while num>=1:
result=result*num
num=num-1
return result
for i in range(1,5):
print("The Factorial of",i,"is :",fact(i))
Output
D:\Python_classes>py test.py
The Factorial of 1 is : 1
The Factorial of 2 is : 2
The Factorial of 3 is : 6
The Factorial of 4 is : 24
Eg 1:
def sum_sub(a,b):
sum=a+b
sub=a-b
return sum,sub
x,y=sum_sub(100,50)
print("The Sum is :",x)
print("The Subtraction is :",y)
Output
The Sum is : 150
The Subtraction is : 50
Eg 2:
def calc(a,b):
sum=a+b
sub=a-b
mul=a*b
div=a/b
return sum,sub,mul,div
t=calc(100,50)
print("The Results are")
4 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
for i in t:
print(i)
Output
The Results are
150
50
5000
2.0
Types of arguments
def f1(a,b):
------
------
------
f1(10,20)
positional arguments
keyword arguments
default arguments
Variable length arguments
1. positional arguments:
def sub(a,b):
print(a-b)
sub(100,200)
sub(200,100)
The number of arguments and position of arguments must be matched. If we change the
order then result may be changed.
5 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
2. keyword arguments:
Eg:
def wish(name,msg):
print("Hello",name,msg)
wish(name="Durga",msg="Good Morning")
wish(msg="Good Morning",name="Durga")
Output
Hello Durga Good Morning
Hello Durga Good Morning
Here the order of arguments is not important but number of arguments must be matched.
Note:
We can use both positional and keyword arguments simultaneously. But first we have to
take positional arguments and then keyword arguments,otherwise we will get
syntaxerror.
def wish(name,msg):
print("Hello",name,msg)
wish("Durga","GoodMorning") ==>valid
wish("Durga",msg="GoodMorning") ==>valid
wish(name="Durga","GoodMorning") ==>invalid SyntaxError:
positional argument follows keyword argument
3. Default Arguments:
Eg:
def wish(name="Guest"):
print("Hello",name,"Good Morning")
wish("Durga")
wish()
6)
Output
Hello Durga Good Morning
Hello Guest Good Morning
6 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
If we are not passing any name then only default value will be considered.
***Note:
def f1(*n):
We can call this function by passing any number of arguments including zero number.
Internally all these values represented in the form of tuple.
Eg:
def sum(*n):
total=0
for n1 in n:
total=total+n1
print("The Sum=",total)
sum()
sum(10)
sum(10,20)
sum(10,20,30,40)
Output
The Sum= 0
The Sum= 10
The Sum= 30
The Sum= 100
Note:
We can mix variable length arguments with positional arguments.
7 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Eg:
def f1(n1,*s):
print(n1)
for s1 in s:
print(s1)
f1(10)
f1(10,20,30,40)
f1(10,"A",30,"B")
Output
10
10
20
30
40
10
A
30
B
Note: After variable length argument,if we are taking any other arguments then
we should provide values as keyword arguments.
Eg:
def f1(*s,n1):
for s1 in s:
print(s1)
print(n1)
f1("A","B",n1=10)
Output
A
B
10
f1("A","B",10) ==>Invalid
TypeError: f1() missing 1 required keyword-only argument: 'n1'
def f1(**n):
8 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
We can call this function by passing any number of keyword arguments. Internally
these keyword arguments will be stored inside a dictionary.
Eg:
def display(**kwargs):
for k,v in kwargs.items():
print(k,"=",v)
display(n1=10,n2=20,n3=30)
display(rno=100,name="Durga",marks=70,subject="Java")
Output
n1 = 10
n2 = 20
n3 = 30
rno = 100
name = Durga
marks = 70
subject = Java
Case Study:
def f(arg1,arg2,arg3=4,arg4=8):
print(arg1,arg2,arg3,arg4)
1. f(3,2) ==> 3 2 4 8
f(10,20,30,40) ===>10 20 30 40
f(arg4=2,arg1=3,arg2=4)===>3 4 4 2
f()===>Invalid
TypeError: f() missing 2 required positional arguments: 'arg1' and 'arg2'
6. f(arg3=10,arg4=20,30,40) ==>Invalid
SyntaxError: positional argument follows keyword argument
[After keyword arguments we should not take positional arguments]
7. f(4,5,arg2=6)==>Invalid
TypeError: f() got multiple values for argument 'arg2'
8. f(4,5,arg3=5,arg5=6)==>Invalid
TypeError: f() got an unexpected keyword argument 'arg5'
9 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Note: Function vs Module vs Library:
Library Function
Types of Variables
Python supports 2 types of variables.
Global Variables
Local Variables
1. Global Variables
The variables which are declared outside of function are called global variables.
These variables can be accessed in all functions of that module.
Eg:
f1()
f2()
Output
10
10
10 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
2. Local Variables:
The variables which are declared inside a function are called local variables.
Local variables are available only for the function in which we declared it.i.e from
outside of function we cannot access.
Eg:
def f1():
a=10
print(a) # valid
def f2():
print(a) #invalid
f1()
f2()
global keyword:
We can use global keyword for the following 2 purposes:
Eg 1:
a=10
def f1():
a=777
print(a)
def f2():
print(a)
f1()
f2()
Output
777
10
11 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Eg 2:
a=10
def f1():
global a
a=777
print(a)
def f2():
print(a)
f1()
f2()
Output
777
777
Eg 3:
def f1():
a=10
print(a)
def f2():
print(a)
f1()
f2()
Eg 4:
def f1():
global a
a=10
print(a)
def f2():
print(a)
f1()
f2()
Output
The Sum of 10,20 is: 30
The Sum of 100,200 is: 300
Note:
Lambda Function internally returns expression value and we are not required to
write return statement explicitly.
We can use lambda functions very commonly with filter(),map() and reduce()
functions,b'z these functions expect function as argument.
filter() function:
We can use filter() function to filter values from the given sequence based on
some condition.
filter(function,sequence)
15 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
return False
l=[0,5,10,15,20,25,30]
l1=list(filter(isEven,l))
print(l1) #[0,10,20,30]
map() function:
For every element present in the given sequence,apply some functionality and
generate new element with the required modification. For this requirement we should
go for map() function.
Eg: For every element present in the list perform double and generate new list of doubles.
Syntax:
map(function,sequence)
The function can be applied on each element of sequence and generates new sequence.
l=[1,2,3,4,5]
def doubleIt(x):
return 2*x
l1=list(map(doubleIt,l))
print(l1) #[2, 4, 6, 8, 10]
with lambda
l=[1,2,3,4,5]
l1=list(map(lambda x:2*x,l))
print(l1) #[2, 4, 6, 8, 10]
-------------------------------------------------------------
16 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Eg 2: To find square of given numbers
l=[1,2,3,4,5]
l1=list(map(lambda x:x*x,l))
print(l1) #[1, 4, 9, 16, 25]
We can apply map() function on multiple lists also.But make sure all list should have
same length.
l1=[1,2,3,4]
l2=[2,3,4,5]
l3=list(map(lambda x,y:x*y,l1,l2))
print(l3) #[2, 6, 12, 20]
reduce() function:
reduce() function reduces sequence of elements into a single element by applying
the specified function.
reduce(function,sequence)
Eg:
Eg:
result=reduce(lambda x,y:x*y,l)
print(result) #12000000
Eg:
17 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Note:
In Python every thing is treated as object.
Even functions also internally treated as objects only.
Eg:
def f1():
print("Hello")
print(f1)
print(id(f1))
Output
<function f1 at 0x00419618>
4298264
Function Aliasing:
For the existing function we can give another name, which is nothing but function aliasing.
Eg:
def wish(name):
print("Good Morning:",name)
greeting=wish
print(id(wish))
print(id(greeting))
greeting('Durga')
wish('Durga')
Output
4429336
4429336
Good Morning: Durga
Good Morning: Durga
Note: In the above example only one function is available but we can call that function by
using either wish name or greeting name.
If we delete one name still we can access that function by using alias name
Eg:
def wish(name):
print("Good Morning:",name)
18 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
3)
greeting=wish
greeting('Durga')
wish('Durga')
8)
del wish
#wish('Durga') ==>NameError: name 'wish' is not defined
greeting('Pavan')
Output
Good Morning: Durga
Good Morning: Durga
Good Morning: Pavan
Nested Functions:
We can declare a function inside another function, such type of functions are called Nested
functions.
Eg:
def outer():
print("outer function started")
def inner():
print("inner function execution")
print("outer function calling inner function")
inner()
outer()
8) #inner() ==>NameError: name 'inner' is not defined
Output
outer function started
outer function calling inner function
inner function execution
In the above example inner() function is local to outer() function and hence it is not possible to call
directly from outside of outer() function.
Eg:
def outer():
print("outer function started")
def inner():
print("inner function execution")
19 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
print("outer function returning inner function")
return inner
f1=outer()
f1()
f1()
f1()
Output
outer function started
outer function returning inner function
inner function execution
inner function execution
inner function execution
In the first case for the outer() function we are providing another name f1(function aliasing).
But in the second case we calling outer() function,which returns inner function.For that inner
function() we are providing another name f1
Eg: filter(function,sequence)
map(function,sequence)
reduce(function,sequence)
20 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Function Decorators:
Decorator is a function which can take a function as argument and extend its
functionality and returns modified function with extended functionality.
The main objective of decorator functions is we can extend the functionality of existing
functions without modifies that function.
def wish(name):
print("Hello",name,"Good Morning")
This function can always print same output for any name
But we want to modify this function to provide different message if name is Sunny.
We can do this without touching wish() function by using decorator.
Eg:
def decor(func):
def inner(name):
if name=="Sunny":
print("Hello Sunny Bad Morning")
else:
func(name)
return inner
8)
@decor
def wish(name):
print("Hello",name,"Good Morning")
wish("Durga")
wish("Ravi")
wish("Sunny")
21 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Output
Hello Durga Good Morning
Hello Ravi Good Morning
Hello Sunny Bad Morning
In the above program whenever we call wish() function automatically decor function will
be executed.
def decor(func):
def inner(name):
if name=="Sunny":
print("Hello Sunny Bad Morning")
else:
func(name)
return inner
8)
9)
def wish(name):
print("Hello",name,"Good Morning")
decorfunction=decor(wish)
Output
Hello Durga Good Morning
Hello Sunny Good Morning
Hello Durga Good Morning
Hello Sunny Bad Morning
Eg 2:
def smart_division(func):
def inner(a,b):
print("We are dividing",a,"with",b)
if b==0:
print("OOPS...cannot divide")
return
else:
return func(a,b)
22 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
return inner
@smart_division
def division(a,b):
return a/b
print(division(20,2))
print(division(20,0))
10.0
Traceback (most recent call last):
File "test.py", line 16, in <module>
print(division(20,0))
File "test.py", line 13, in division
return a/b
ZeroDivisionError: division by zero
with decorator we won't get any error. In this case output is:
Decorator Chaining
We can define multiple decorators for the same function and all these decorators will
form Decorator Chaining.
Eg:
@decor1
@decor
def num():
For num() function we are applying 2 decorator functions. First inner decorator will
work and then outer decorator.
Eg:
def decor1(func):
def inner():
x=func()
return x*x
23 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
return inner
def decor(func):
def inner():
x=func()
return 2*x
return inner
@decor1
@decor
def num():
return 10
print(num())
wish("Durga")
D:\durgaclasses>py decaratordemo1.py
Second Decor(decor1) Execution
First Decor(decor) Function Execution
Hello Durga Good Morning
24 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Generators
Generator is a function which is responsible to generate a sequence of values.
We can write generator functions just like ordinary functions, but it uses yield keyword
to return values.
yield
Eg 1:
def mygen():
yield 'A'
yield 'B'
yield 'C'
g=mygen()
print(type(g))
print(next(g))
print(next(g))
print(next(g))
print(next(g))
Output
<class 'generator'>
A
B
C
Traceback (most recent call last):
File "test.py", line 12, in <module>
print(next(g))
StopIteration
Eg 2:
def countdown(num):
print("Start Countdown")
while(num>0):
yield num
num=num-1
6)
values=countdown(5)
for x in values:
25 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
print(x)
Output
Start Countdown
5
4
3
2
1
def firstn(num):
n=1
while n<=num:
yield n
n=n+1
6)
values=firstn(5)
for x in values:
print(x)
10)
Output
1
2
3
4
5
Eg: 0,1,1,2,3,5,8,13,21,...
def fib():
a,b=0,1
while True:
yield a
a,b=b,a+b
for f in fib():
if f>100:
break
print(f)
26 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
10)
Output
0
1
1
2
3
5
8
13
21
34
55
89
27 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
}
yield person
'''''t1 = time.clock()
people = people_list(10000000)
t2 = time.clock()'''
t1 = time.clock()
people = people_generator(10000000)
t2 = time.clock()
print('Took {}'.format(t2-t1))
Note: In the above program observe the differnce wrt execution time by using list and generators
We will get MemoryError in this case because all these values are required to store in the memory.
Generators:
g=(x*x for x in range(10000000000000000))
print(next(g))
Output: 0
We won't get any MemoryError because the values won't be stored at the beginning
28 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Modules
A group of functions, variables and classes saved to a file, which is nothing but module.
Eg: durgamath.py
x=888
def add(a,b):
print("The Sum:",a+b)
def product(a,b):
print("The Product:",a*b)
If we want to use members of module in our program then we should import that
test.py:
import durgamath
print(durgamath.x)
durgamath.add(10,20)
durgamath.product(10,20)
Output
888
The Sum: 30
The Product: 200
DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 040 –
64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Note:
whenever we are using a module in our program, for that module compiled file will be
generated and stored in the hard disk permanently.
test.py:
import durgamath as m
print(m.x)
m.add(10,20)
m.product(10,20)
Eg:
from durgamath import x,add
print(x)
add(10,20)
product(10,20)==> NameError: name 'product' is not defined
test.py:
2 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Various possibilties of import:
import modulename
import module1,module2,module3
import module1 as m
import module1 as m1,module2 as m2,module3
from module import member
from module import
member1,member2,memebr3 from module
import memeber1 as x from module import *
member aliasing:
from durgamath import x as y,add as sum
print(y)
sum(10,20)
Once we defined as alias name,we should use alias name only and we should not use
original name
Eg:
from durgamath import x as y
print(x)==>NameError: name 'x' is not defined
Reloading a Module:
By default module will be loaded only once eventhough we are importing
multiple multiple times.
import time
from imp import reload
import module1
time.sleep(30)
reload(module1)
time.sleep(30)
reload(module1)
print("This is test file")
Note: In the above program, everytime updated version of module1 will be available
to our program
3 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
module1.py:
test.py
import module1
import module1
import module1
import module1
print("This is test module")
Output
This is from module1
This is test module
In the above program test module will be loaded only once eventhough we are
importing multiple times.
We can solve this problem by reloading module explicitly based on our requirement.
We can reload by using reload() function of imp module.
import imp
imp.reload(module1)
test.py:
import module1
import module1
from imp import reload
reload(module1)
reload(module1)
reload(module1)
print("This is test module")
In the above program module1 will be loaded 4 times in that 1 time by default and 3
times explicitly. In this case output is
4 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
The main advantage of explicit module reloading is we can ensure that updated version
is always available to our program.
Python provides inbuilt function dir() to list out all members of current module or
a specified module.
Eg 1: test.py
x=10
y=20
def f1():
print("Hello")
5) print(dir()) # To print all members of current module
6)
Output
['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__nam
e__', '__package__', '__spec__', 'f1', 'x', 'y']
durgamath.py:
x=888
def add(a,b):
print("The Sum:",a+b)
def product(a,b):
print("The Product:",a*b)
test.py:
import durgamath
print(dir(durgamath))
Output
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__',
'__package__', '__spec__', 'add', 'product', 'x']
Note: For every module at the time of execution Python interpreter will add some
special properties automatically for internal use.
5 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Eg: __builtins__,__cached__,'__doc__,__file__, __loader__,
__name__,__package__, __spec__
Based on our requirement we can access these properties also in our program.
Eg: test.py:
print(__builtins__ )
print(__cached__ )
print(__doc__)
print(__file__)
print(__loader__)
print(__name__)
print(__package__)
print(__spec__)
9)
Output
<module 'builtins' (built-in)>
None
None
test.py
For every Python program , a special variable __name__ will be added internally.
This variable stores information regarding whether the program is executed as
an individual program or as a module.
If the program executed as an individual program then the value of this variable
is __main__
If the program executed as a module from some other program then the value of
this variable is the name of module where it is defined.
Hence by using this __name__ variable we can identify whether the program
executed directly or as a module.
6 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Demo program:
module1.py:
def f1():
if __name__=='__main__':
print("The code executed as a program")
else:
print("The code executed as a module from some other program")
f1()
test.py:
import module1
module1.f1()
3)
D:\Python_classes>py module1.py
The code executed as a program
D:\Python_classes>py test.py
The code executed as a module from some other program
The code executed as a module from some other program
sqrt(x)
ceil(x)
floor(x)
fabs(x)
log(x)
sin(x)
tan(x)
....
Eg:
7 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
7)
Output
2.0
11
10
10.6
10.6
Note:
We can find help for any module by using help() function
Eg:
import math
help(math)
1. random() function:
This function always generate some float value between 0 and 1 ( not
inclusive) 0<x<1
Eg:
8 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
2. randint() function:
Eg:
Output
51
44
39
70
49
74
52
10
40
8
3. uniform():
Eg:
Output
9.787695398230332
6.81102218793548
8.068672144377329
8.567976357239834
6.363511674803802
2.176137584071641
4.822867939432386
6.0801725149678445
7.508457735544763
1.9982221862917555
9 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
4. randrange([start],stop,[step])
Eg 1:
Output
9
4
0
2
9
4
8
9
5
9
Eg 2:
Output
2
2
8
10
3
5
9
1
6
3
10 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Eg 3:
Output
1
3
9
5
7
1
1
1
7
3
5. choice() function:
Eg:
Output
Bunny
pinny
Bunny
Sunny
Bunny
pinny
pinny
Vinny
Bunny
Sunny
11 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Packages
It is an encapsulation mechanism to group related modules into a single unit.
package is nothing but folder or directory which represents collection of Python modules.
__init__.py
File 1
File 1 File 1
__init__.py __init__.py
Loan
1 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
__init__.py
File 1
File 1 File 1
__init__.py
__init__.py
Module 1 Module 1
Module 1 Module 1
Loan
Eg 1:
D:\Python_classes>
|-test.py
|-pack1
|-module1.py
|-__init__.py
__init__.py:
empty file
module1.py:
def f1():
print("Hello this is from module1 present in pack1")
test.py (version-1):
import pack1.module1
pack1.module1.f1()
2 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
test.py (version-2):
Eg 2:
D:\Python_classes>
|-test.py
|-com
|-module1.py
|-__init__.py
|-durgasoft
|-module2.py
|-__init__.py
__init__.py:
empty file
module1.py:
def f1():
print("Hello this is from module1 present in com")
module2.py:
def f2():
print("Hello this is from module2 present in com.durgasoft")
test.py:
3 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Library
Files are very common permanent storage areas to store our data.
Types of Files:
There are 2 types of files
1. Text Files:
2. Binary Files:
Usually we can use binary files to store binary data like images,video files, audio files etc...
Opening a File:
Before performing any operation (like read or write) on the file,first we have to open that
file.For this we should use Python's inbuilt function open()
But at the time of open, we have to specify mode,which represents the purpose of
opening file.
f = open(filename, mode)
r open an existing file for read operation. The file pointer is positioned at the
beginning of the file.If the specified file does not exist then we will get
FileNotFoundError.This is default mode.
DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 040 –
64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
w open an existing file for write operation. If the file already contains some data then it
will be overridden. If the specified file is not already avaialble then this mode will create
that file.
a open an existing file for append operation. It won't override existing data.If the specified file
is not already avaialble then this mode will create a new file.
r+ To read and write data into the file. The previous data in the file will not be deleted.The
file pointer is placed at the beginning of the file.
w+ To write and read data. It will override existing data.
a+ To append and read data from the file.It wont override existing data.
x To open a file in exclusive creation mode for write operation. If the file already exists then
we will get FileExistsError.
Note: All the above modes are applicable for text files. If the above modes suffixed
with 'b' then these represents for binary files.
Eg: rb,wb,ab,r+b,w+b,a+b,xb
f = open("abc.txt","w")
Closing a File:
After completing our operations on the file,it is highly recommended to close the file.
For this we have to use close() function.
f.close()
2 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Eg:
f=open("abc.txt",'w')
print("File Name: ",f.name)
print("File Mode: ",f.mode)
print("Is File Readable: ",f.readable())
print("Is File Writable: ",f.writable())
print("Is File Closed : ",f.closed)
f.close()
print("Is File Closed : ",f.closed)
9)
10)
Output
D:\Python_classes>py test.py
File Name: abc.txt
File Mode: w
Is File Readable: False
Is File Writable: True
Is File Closed : False
Is File Closed : True
write(str)
writelines(list of lines)
Eg:
f=open("abcd.txt",'w')
f.write("Durga\n")
f.write("Software\n")
f.write("Solutions\n")
print("Data written to the file successfully")
f.close()
abcd.txt:
Durga
Software
Solutions
Note: In the above program, data present in the file will be overridden everytime if we
run the program. Instead of overriding if we want append operation then we should
open the file as follows.
f = open("abcd.txt","a")
3 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Eg 2:
f=open("abcd.txt",'w')
list=["sunny\n","bunny\n","vinny\n","chinny"]
f.writelines(list)
print("List of lines written to the file successfully")
f.close()
abcd.txt:
sunny
bunny
vinny
chinny
Note: while writing data by using write() methods, compulsory we have to provide line
seperator(\n),otherwise total data should be written to a single line.
f=open("abc.txt",'r')
data=f.read()
print(data)
f.close()
5)
Output
sunny
bunny
chinny
vinny
f=open("abc.txt",'r')
data=f.read(10)
print(data)
f.close()
5)
4 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Output
sunny
bunn
f=open("abc.txt",'r')
line1=f.readline()
print(line1,end='')
line2=f.readline()
print(line2,end='')
line3=f.readline()
print(line3,end='')
f.close()
9)
Output
sunny
bunny
chinny
f=open("abc.txt",'r')
lines=f.readlines()
for line in lines:
print(line,end='')
f.close()
6)
Output
sunny
bunny
chinny
vinny
Eg 5:
f=open("abc.txt","r")
print(f.read(3))
print(f.readline())
print(f.read(4))
print("Remaining data")
print(f.read())
7)
Output
sun
ny
11)
bunn
Remaining data
5 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
y
chinny
vinny
with open("abc.txt","w") as f:
f.write("Durga\n")
f.write("Software\n")
f.write("Solutions\n")
print("Is File Closed: ",f.closed)
print("Is File Closed: ",f.closed)
Output
Is File Closed: False
Is File Closed: True
tell():
==>We can use tell() method to return current position of the cursor(file pointer)
from beginning of the file. [ can you plese telll current cursor position]
The position(index) of first character in files is zero just like string index.
Eg:
f=open("abc.txt","r")
print(f.tell())
print(f.read(2))
print(f.tell())
print(f.read(3))
print(f.tell())
abc.txt:
sunny
bunny
chinny
vinny
6 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Output:
0
su
2
nny
5
seek():
f.seek(offset, fromwhere)
Note: Python 2 supports all 3 values but Python 3 supports only zero.
Eg:
7 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
All Students are GEMS!!!
import os,sys
fname=input("Enter File Name: ")
if os.path.isfile(fname):
print("File exists:",fname)
f=open(fname,"r")
else:
print("File does not exist:",fname)
sys.exit(0)
print("The content of file is:")
data=f.read()
print(data)
12)
Output
D:\Python_classes>py test.py
Enter File Name: durga.txt
File does not exist: durga.txt
D:\Python_classes>py test.py
Enter File Name: abc.txt
File exists: abc.txt
The content of file is:
All Students are GEMS!!!
All Students are GEMS!!!
All Students are GEMS!!!
All Students are GEMS!!!
All Students are GEMS!!!
All Students are GEMS!!!
Note:
sys.exit(0) ===>To exit system without executing rest of the program.
argument represents status code . 0 means normal termination and it is the default value.
8 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Q. Program to print the number of lines,words and characters present in
the given file?
import os,sys
fname=input("Enter File Name: ")
if os.path.isfile(fname):
print("File exists:",fname)
f=open(fname,"r")
else:
print("File does not exist:",fname)
sys.exit(0)
lcount=wcount=ccount=0
for line in f:
lcount=lcount+1
ccount=ccount+len(line)
words=line.split()
wcount=wcount+len(words)
print("The number of Lines:",lcount)
print("The number of Words:",wcount)
print("The number of Characters:",ccount)
Output
D:\Python_classes>py test.py
Enter File Name: durga.txt
File does not exist: durga.txt
23)
D:\Python_classes>py test.py
Enter File Name: abc.txt
File exists: abc.txt
The number of Lines: 6
The number of Words: 24
The number of Characters: 149
abc.txt:
9 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Handling Binary Data:
It is very common requirement to read or write binary data like images,video
files,audio files etc.
f1=open("rossum.jpg","rb")
f2=open("newpic.jpg","wb")
bytes=f1.read()
f2.write(bytes)
print("New Image is available with the name: newpic.jpg")
As the part of programming,it is very common requirement to write and read data wrt
csv files. Python provides csv module to handle csv files.
import csv
with open("emp.csv","w",newline='') as f:
w=csv.writer(f) # returns csv writer object
w.writerow(["ENO","ENAME","ESAL","EADDR"])
n=int(input("Enter Number of Employees:"))
for i in range(n):
eno=input("Enter Employee No:")
ename=input("Enter Employee Name:")
esal=input("Enter Employee Salary:")
eaddr=input("Enter Employee Address:")
w.writerow([eno,ename,esal,eaddr])
print("Total Employees data written to csv file successfully")
with open("emp.csv","w",newline='') as f:
with open("emp.csv","w") as f:
Note: If we are not using newline attribute then in the csv file blank lines will be
included between data. To prevent these blank lines, newline attribute is required in
Python-3,but in Python-2 just we can specify mode as 'wb' and we are not required to use
newline attribute.
10 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Reading Data from csv file:
import csv
f=open("emp.csv",'r')
r=csv.reader(f) #returns csv reader object
data=list(r)
#print(data)
for line in data:
for word in line:
print(word,"\t",end='')
print()
10)
Output
D:\Python_classes>py test.py
ENO ENAME ESAL EADDR
100 Durga 1000 Hyd
200 Sachin 2000 Mumbai
300 Dhoni 3000 Ranchi
To perform zip and unzip operations, Python contains one in-bulit module zip file.
This module contains a class : ZipFile
We have to create ZipFile class object with name of the zip file,mode and
constant ZIP_DEFLATED. This constant represents we are creating zip file.
f = ZipFile("files.zip","w","ZIP_DEFLATED")
Once we create ZipFile object,we can add files by using write() method.
f.write(filename)
11 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Eg:
f = ZipFile("files.zip","r",ZIP_STORED)
ZIP_STORED represents unzip operation. This is default value and hence we are
not required to specify.
Once we created ZipFile object for unzip operation,we can get all file names present
in that zip file by using namelist() method.
names = f.namelist()
Eg:
12 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
To perform these operations,Python provides inbuilt module os,which contains
several functions to perform directory related operations.
import os
cwd=os.getcwd()
print("Current Working Directory:",cwd)
import os
os.mkdir("mysub")
print("mysub directory created in cwd")
cwd
|-mysub
|-mysub2
import os
os.mkdir("mysub/mysub2")
print("mysub2 created inside mysub")
Q4. To create multiple directories like sub1 in that sub2 in that sub3:
import os
os.makedirs("sub1/sub2/sub3")
print("sub1 and in that sub2 and in that sub3 directories created")
import os
os.rmdir("mysub/mysub2")
print("mysub2 directory deleted")
import os
os.removedirs("sub1/sub2/sub3")
print("All 3 directories sub1,sub2 and sub3 removed")
13 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Q7. To rename a directory:
import os
os.rename("mysub","newdir")
print("mysub directory renamed to newdir")
os module provides listdir() to list out the contents of the specified directory. It
won't display the contents of sub directory.
Eg:
import os
print(os.listdir("."))
Output
D:\Python_classes>py test.py
['abc.py', 'abc.txt', 'abcd.txt', 'com', 'demo.py', 'durgamath.py', 'emp.csv', '
file1.txt', 'file2.txt', 'file3.txt', 'files.zip', 'log.txt', 'module1.py', 'myl
og.txt', 'newdir', 'newpic.jpg', 'pack1', 'rossum.jpg', 'test.py', '__pycache__'
]
The above program display contents of current working directory but not contents of
sub directories.
os.walk(path,topdown=True,onerror=None,followlinks=False)
It returns an Iterator object whose contents can be displayed by using for loop
14 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Eg: To display all contents of Current working directory including sub directories:
import os
for dirpath,dirnames,filenames in os.walk('.'):
print("Current Directory Path:",dirpath)
print("Directories:",dirnames)
print("Files:",filenames)
print()
7)
8)
Output
Current Directory Path: .
Directories: ['com', 'newdir', 'pack1', '__pycache__']
Files: ['abc.txt', 'abcd.txt', 'demo.py', 'durgamath.py', 'emp.csv', 'file1.txt'
, 'file2.txt', 'file3.txt', 'files.zip', 'log.txt', 'module1.py', 'mylog.txt', '
newpic.jpg', 'rossum.jpg', 'test.py']
15)
Current Directory Path: .\com
Directories: ['durgasoft', '__pycache__']
Files: ['module1.py', '__init__.py']
19)
...
os.walk("directoryname")
In the case of listdir(), we will get contents of specified directory but not sub directory
contents. But in the case of walk() function we will get contents of specified directory
and its sub directories also.
os.system("commad string")
The argument is any command which is executing from DOS.
Eg:
import os
os.system("dir *.py")
os.system("py abc.py")
15 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
How to get information about a File:
We can get statistics of a file like size, last accessed time,last modified time etc by using
stat() function of os module.
stats = os.stat("abc.txt")
st_mode==>Protection Bits
st_ino==>Inode number
st_dev===>device
st_nlink===>no of hard links
st_uid===>userid of owner
st_gid==>group id of owner
st_size===>size of file in bytes
st_atime==>Time of most recent access
st_mtime==>Time of Most recent modification
st_ctime==> Time of Most recent meta data change
Note:
st_atime, st_mtime and st_ctime returns the time as number of milli seconds since Jan 1st
1970 ,12:00AM. By using datetime module fromtimestamp() function,we can get exact
date and time.
import os
stats=os.stat("abc.txt")
print(stats)
4)
Output
os.stat_result(st_mode=33206, st_ino=844424930132788, st_dev=2657980798, st_nlin
k=1, st_uid=0, st_gid=0, st_size=22410, st_atime=1505451446, st_mtime=1505538999
, st_ctime=1505451446)
import os
from datetime import *
stats=os.stat("abc.txt")
print("File Size in Bytes:",stats.st_size)
print("File Last Accessed Time:",datetime.fromtimestamp(stats.st_atime))
print("File Last Modified Time:",datetime.fromtimestamp(stats.st_mtime))
7)
16 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Output
File Size in Bytes: 22410
File Last Accessed Time: 2017-09-15 10:27:26.599490
File Last Modified Time: 2017-09-16 10:46:39.245394
The process of writing state of object to the file is called pickling and the process
of reading state of an object from the file is called unpickling.
pickle.dump(object,file)
obj=pickle.load(file)
pickling
pickle.dump
eno: 100 (e1, f)
ename: Durga
esal: 10000
eaddr: HYD
e1 eno: 100
ename: Durga
esal: 10000
eaddr: HYD
t1=Test()
t2=Test(10)
t3=Test(10,20)
t4=Test(10,20,30)
Output:
Constructor with 0|1|2|3 number of arguments
Constructor with 0|1|2|3 number of arguments
Constructor with 0|1|2|3 number of arguments
Constructor with 0|1|2|3 number of arguments
class Test:
def __init__(self,*a):
print('Constructor with variable number of arguments')
t1=Test()
t2=Test(10)
t3=Test(10,20)
t4=Test(10,20,30)
t5=Test(10,20,30,40,50,60)
Output:
Constructor with variable number of arguments
Constructor with variable number of arguments
Constructor with variable number of arguments
Constructor with variable number of arguments
Constructor with variable number of arguments
9 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Method overriding:
What ever members available in the parent class are bydefault available to the child class
through inheritance. If the child class not satisfied with parent class implementation then child
class is allowed to redefine that method in the child class based on its requirement. This concept
is called overriding.
Overriding concept applicable for both methods and constructors.
class P:
def property(self):
print('Gold+Land+Cash+Power')
def marry(self):
print('Appalamma')
class C(P):
def marry(self):
print('Katrina Kaif')
9)
c=C()
c.property()
c.marry()
Output:
Gold+Land+Cash+Power
Katrina Kaif
From Overriding method of child class,we can call parent class method also by using
super() method.
class P:
def property(self):
print('Gold+Land+Cash+Power')
def marry(self):
print('Appalamma')
class C(P):
def marry(self):
super().marry()
print('Katrina Kaif')
10)
c=C()
c.property()
c.marry()
Output:
Gold+Land+Cash+Power
Appalamma
Katrina Kaif
10 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com