Python PDF
Python PDF
REDDY
PYTHON
An Introduction to PYTHON
Features of PYTHON
2. Expressive Language
Python language is more expressive means that it is more understandable and
readable.
3. Interpreted Language
Python is an interpreted language i.e. interpreter executes the code line by line at a
time. This makes debugging easy and its suitable for beginners.
MOHAN S.REDDY
4. Cross-platform Language
Python can run equally on different platforms such as Windows, Linux, Unix and
Macintosh etc. So, we can say that Python is a portable language.
6. Object-Oriented Language
Python supports object oriented language and concepts of classes and objects come
into existence.
7. Extensible
It implies that other languages such as C/C++ can be used to compile the code and
thus it can be used further in our python code.
10. Integrated
It can be easily integrated with languages like C, C++, JAVA etc.
MOHAN S.REDDY
Versions of PYTHON
History of PYTHON
o In 1994, Python 1.0 was released with new features like: lambda, map, filter,
and reduce.
o Python 2.0 added new features like: list comprehensions, garbage collection
system.
o On December 3, 2008, Python 3.0 (also called "Py3K") was released. It was
designed to rectify fundamental flaw of the language.
o ABC language.
o Modula-3
❖ Web Applications
❖ Network Programming
❖ Gaming Applications
❖ Business Applications
Go to Google
Click on Python.org
Click on Next
Click on Install
MOHAN S.REDDY
4. Using Pycharm(IDE)
Interpreter vs Compiler:
Interpreter Compiler
1. It will check line by line and 1. It will check Whole program at a
executes time
Python Indentation:
• A code block (body of a function, loop etc.) starts with indentation and ends
with the first un indented line. The amount of indentation is up to you, but it
must be consistent throughout that block.
• Generally four whitespaces are used for indentation and is preferred over
tabs. Here is an example.
MOHAN S.REDDY
a=10
if a==10:
print("welcome to durgasoft")
• The indentation in Python makes the code look neat and clean.
• Indentation can be ignored in line continuation.
• But it makes the code more readable.
Python Comments:
• Comments are very important while writing a program.
• In case user wants to specify a single line comment, then comment must start
with (#)
• If we have comments that extend multiple lines, one way of doing it is to use
hash (#) in the beginning of each line.
Identifiers:
• Digits(0 to 9)
• Underscore symbol(_)
Python Variables:
Multiple Assignment:
a=b=c=10
print (a)
print (b)
print (c)
a,b,c=10,20,30
print (a)
print (b)
print (c)
Python Keywords:
• Python Keywords are special reserved words which convey a special meaning
to the interpreter.
1. None
MOHAN S.REDDY
2. Numeric
3. List
4. Tuple
5. Set
6. String
7. Range
8. Dictionary or Mapping
➢ None: When we have a variable which is not assigned any value is called None.
➢ Normally in any language the keyword can be use null , but in python we use None.
1. Int
2. Float
3. Complex
4. Bool
Ex:
>>> num=3.4
>>> type(num)
<class 'float'>
>>> num=5
>>> type(num)
<class 'int'>
>>> num=3+4j
>>> type(num)
<class 'complex'>
MOHAN S.REDDY
>>> a=5.8
>>> b=int(a)
>>> type(b)
<class 'int'>
>>> b
>>>
>>> a=6
>>> b=float(a)
>>> type(b)
<class 'float'>
>>> b
6.0
>>>
>>> a=3
>>> b=5
>>> c=complex(a,b)
>>> c
(3+5j)
>>>
Bool:
MOHAN S.REDDY
>>> a=10;
>>> b=20;
>>> a<b
True
>>> bool=a<b
>>> bool
True
>>>
>>> int(True)
>>> int(False)
>>>
It is one of the most used datatype in Python and is very flexible. All
the items in a list do not need to be of the same type.
>>> lst=[34,56,78,99]
>>> type(lst)
<class 'list'>
>>> lst
Tuple:
The only difference is that tuples are immutable. Tuples once created cannot be
modified.
Tuples are used to write-protect data and are usually faster than list as it cannot
change dynamically.
>>> t=(23,45,23,55)
>>> type(t)
<class 'tuple'>
>>> t
SET:
Set is an unordered collection of unique items. Set is defined by values separated by comma
inside braces { }. Items in a set are not ordered.
>>> s={1,2,3,4,5}
>>> type(s)
<class 'set'>
>>> s
{1, 2, 3, 4, 5}
String:
String is sequence of Unicode characters. We can use single quotes or double quotes to
represent strings. Multi-line strings can be denoted using triple quotes, ''' or """
>>> str="durga"
MOHAN S.REDDY
>>> type(str)
<class 'str'>
>>> str
'durga'
String Slicing:
-5 -4 -3 -2 -1
M O H A N
0 1 2 3 4
Ex:
>>> s="mohan"
>>> s[0]
'm'
>>> s[1]
'o'
>>> s[-3]
'h'
>>> s[5]
MOHAN S.REDDY
s[5]
>>> s[0:3]
'moh'
>>> s[:3]
'moh'
>>> s*4
'mohanmohanmohanmohan'
>>> len(s)
>>>
Range:
The elements are present in Range data type is not modify, i.e Range data type is
immutable.
>>> range(0,20)
range(0, 20)
>>> list(range(20))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
>>>
Dictionary or Maping:
It is generally used when we have a huge amount of data. Dictionaries are optimized
for retrieving data. We must know the key to retrieve the value.
In Python, dictionaries are defined within braces {} with each item being a pair in
the form key:value. Key and value can be of any type.
MOHAN S.REDDY
>>> d={'mihan':'nokia','manoj':'samsung','kiran':'oneplusone'}
>>> type(d)
<class 'dict'>
>>> d
>>> d.keys()
>>> d.values()
>>> d['mihan']
'nokia'
>>> d.get('kiran')
'oneplusone'
>>>
Python Operators:
1. Arithmetic Operators.
2. Relational Operators.
3. Assignment Operators.
4. Logical Operators.
5. Membership Operators.
6. Identity Operators.
MOHAN S.REDDY
7. Bitwise Operators.
Arithmetic Operators:
Operator Description
+ It perform Addition
- It Perform subtraction
* It Perform Multiplication
/ It Perform Division
EX:
>>> 10+2
12
>>> 10-2
>>> 10*2
20
>>> 10/2
5.0
>>> 10%2
MOHAN S.REDDY
>>> 10**2
100
>>> 10//2
>>>
Relational Operators:
Operator Description
== Equal to
!= Not Equal to
Ex:
>>> a=10
>>> b=20
>>> a<b
True
MOHAN S.REDDY
>>> a>b
False
>>> a<=b
True
>>> a>=b
False
>>> a!=b
True
>>> a=10
>>> b=10
>>> a<=b
True
>>> a>=b
True
>>> a=b
>>> a==b
True
>>>
MOHAN S.REDDY
Assignment Operators:
assignment operators that are used to assign values to the variables.
Operator Description
= Assignment
Ex:
>>> a=10
>>> a+=5
>>> a
15
>>> a-=5
>>> a
10
>>> a*=5
>>> a
MOHAN S.REDDY
50
>>> a/=2
>>> a
25.0
>>> a%=2
>>> a
1.0
>>> a//=2
>>> a
0.0
>>> a=5
>>> a
>>> a**=2
>>> a
25
>>> a//=2
>>> a
12
>>>
Logical Operators:
Operator Description
EX:
>>> a=6>3 and 5<3
>>> print(a)
False
>>> a=6>3 or 5<3
>>> print(a)
True
>>> a=not(6>4)
>>> print(a)
False
>>>
Membership Operators:
Operator Description
Ex:
a=10
b=20
MOHAN S.REDDY
list=[10,20,30,40,50];
if (a in list):
print("a is available in list" )
else:
print ("a is not available in list" )
if(b not in list):
print ("b is not available in list" )
else:
print ("b is available in list" )
Identity Operators:
Operator Description
Ex:
1. a=20
2. b=20
3. if( a is b):
4. print(“a,b have same identity”)
5. else:
6. print(“a, b are different “)
7. b=10
8. if( a is not b):
9. print (“ a,b have different identity”)
10. else:
11. print(“a,b have same identity”)
MOHAN S.REDDY
a=int(x)
b=int(y)
z=a+b
print(z)
////////
z=x+y
print(z)
////
import sys
x=int(sys.argv[1])
y=int(sys.argv[2])
z=x+y
print(z)
////4
print(result)
Id():
>>> a=2
>>> id(a)
1361656080
>>> b=3
>>> id(b)
1361656096
>>> id(a)==id(b)
False
>>> id(a)!=id(b)
True
>>> c=2
>>> c
>>> id(c)
1361656080
>>> id(a)==id(c)
True
MOHAN S.REDDY
>>> d="mohan"
>>> d
'mohan'
>>> id(d)
55031680
>>> e="Mohan"
>>> e
'Mohan'
>>> id(e)
55032064
>>> id(d)==id(e)
False
>>>
Control Statements:
The if statement executes only when specified condition is true. We can pass any
valid expression into the if parentheses.
o if statement
o if-else statement
o nested if statement
Syntax:
if(condition):
statements
Ex:
a=10
MOHAN S.REDDY
if a==10:
print "Welcome to Durgasoft"
If Else:
The If statement is used to test specified condition and if the condition is true, if
block executes, otherwise else block executes.
if(condition):
statements
else:
statements
Ex:
year=2000
if year%4==0:
print "Year is Leap"
else:
print "Year is not Leap"
Nested If :
If (condition):
statements
else :
statements
if(condition):
else:
statements..
EX:
a=10
if a>=20:
print "Condition is True"
else:
if a>=15:
print "Checking second value"
else:
print "All Conditions are false"
Loops in python:
For Loop:
Python for loop is used to iterate the elements of a collection in the order that they
appear. This collection can be a sequence(list or string).
x=["mohan",20,34.5]
for i in x:
print(i)
sum=0
for n in range(1,11):
sum+=n
print (sum)
num=2
for a in range (1,6):
print num * a
When an outer loop contains an inner loop in its body it is called Nested Looping.
num_list = [1, 2, 3]
MOHAN S.REDDY
for n in num_list:
print(n)
for l in char_list:
print(l)
Ex:
print(item)
Syntax:
while <expression>:
Body
i=1
while i<=5:
print("Hello")
i=i+1
i = 1
while i < 6:
MOHAN S.REDDY
print(i)
i += 1
i = 1
while i < 6:
print(i)
if i == 3:
break
i += 1
i = 0
while i < 6:
i += 1
if i == 3:
continue
print(i)
String DataStructure:
MOHAN S.REDDY
What is string?
A string is a sequence of characters.
Ex:
str = 'Hello'
print(str)
str = "Hello"
print(str)
str = '''Hello'''
print(str)
durgasoft"""
print(str)
print(str)
#first character
print(str[0])
#last character
print(str[-1])
MOHAN S.REDDY
print(str[1:5])
print(str[5:-2])
The * operator can be used to repeat the string for a given number of times.
EX:
str1 = 'Durga'
str2 ='Soft'
# using +
print(str1 + str2)
# using *
print(str1 * 3)
String Split():
the split() method takes maximum of 2 parameters:
syntax:
str.split([separator [,maxsplit]])
EX:
MOHAN S.REDDY
print (temp)
print (temp)
String Capitalise():
The capitalize() function doesn't take any parameter.
The capitalize() function returns a string with first letter capitalized. It doesn't modify the
old string.
EX:
string = "durgasoft"
cap = string.capitalize()
String Title():
Title function in python is used to convert the first character in each word to
Uppercase and remaining characters to Lowercase in string and returns new string.
str5 = 'a6568'.title()
print('Output after Title()
method is = ', str5)
String Count():
count() method returns the number of occurrences of the substring in the given string.
substring = "is"
count = string.count(substring)
String Replace():
print(newstring)
Upper():
string="python at durgasoft"
print(string.upper())
MOHAN S.REDDY
Lower():
string="PYTHON AT DURGASOFT"
print(string.lower())
For example, if you want to add a colon (:) after every character in the string
"Python" you can use the following code.
Ex:
print(":".join("Python"))
Reversing String
By using the reverse function, you can reverse the string. For example, if we
have string "12345" and then if you apply the code for the reverse function as
shown below.
#string="12345"
string="SAI"
print(''.join(reversed(string)))
x = "Durga"
x.replace("Durga","Mohan")
print(x)
MOHAN S.REDDY
String Sort():
words = str.split()
words.sort()
print(word)
String Swapcase():
The swapcase() method returns the string where all uppercase characters are converted
to lowercase, and lowercase characters are converted to uppercase.
List DataStructure:
What is List:
Nested List:
A List can have another list within it as Item is called Nested List.
Creating a List:
list is created by placing all the items (elements) inside a square bracket [ ], separated
by commas.
Ex:
#Nested List
nlst=["mohan",[3,4,5],['A','B',
'C']]
print(nlst)
Access elements from a List:
Index starts from 0. So, a list having 4 elements will have index from 0 to 3.
We can't use float or other types, this will result into TypeError.
Ex:
lst = ['D','u','r','g','a']
print(lst[0])
print(lst[2])
print(lst[4])
# Nested List
nlst = ["Mohan", [2,0,1,5]]
# Nested indexing
print(nlst[0][1])
print(nlst[1][3])
MOHAN S.REDDY
#negative index
print(lst[-2])
List Slicing:
lst =
['d','u','r','g','a','s','o','f
','t']
# elements 3rd to 5th
print(lst[2:5])
# elements beginning to 4th
print(lst[:-5])
# elements 6th to end
print(lst[5:])
# elements beginning to end
print(lst[:])
Ex:
We can add one item to a list using append() method or add several items
using extend()method.
Ex:
lst = [1, 2, 3]
lst.append(4)
print(lst)
lst.extend([5, 6, 7])
print(lst)
List Concatenation and List Multiplication :
We can use + operator to combine two lists. This is also called concatenation.
lst = [1, 2, 3]
print(lst + [7, 8, 9])
print(["AB"] * 4)
print(lst*3)
Insert Method in List:
we can insert one item at a desired location by using the method insert()
EX:
lst = [1, 9]
lst.insert(1,3)
print(lst)
lst[2:2] = [5, 7]
print(lst)
We can delete one or more items from a list using the keyword del. It can even
delete the list entirely.
lst =
['d','u','r','g','a','s','o','f
','t']
# delete one item
del lst[2]
print(lst)
# delete multiple items
del lst[1:5]
print(lst)
# delete entire list
del lst
MOHAN S.REDDY
The pop() method removes and returns the last item if index is not provided. This
helps us implement lists as stacks (first in, last out data structure).
lst =
['d','u','r','g','a','s','o','f
','t']
lst.remove('d')
print(lst)
print(lst.pop(1))
print(lst)
print(lst.pop())
print(lst)
lst.clear()
print(lst)
List Sort():
The sort() method sorts the elements of a given list in a specific order - Ascending or Descending.
Ex:
MOHAN S.REDDY
# vowels list
vowels = ['e', 'a', 'u', 'o',
'i']
# sort the vowels
vowels.sort()
# print vowels
print('Sorted list:', vowels)
sort() method accepts a reverse parameter as an optional argument.
list.sort(reverse=True)
sorted(list, reverse=True)
# vowels list
vowels = ['e', 'a', 'u', 'o',
'i']
# print vowels
MOHAN S.REDDY
List Copy():
old_list = [1, 2, 3]
new_list = old_list
List Count():
# vowels list
vowels = ['a', 'e', 'i', 'o',
'i', 'u']
# print count
MOHAN S.REDDY
# print count
print('The count of p is:',
count)
List Index():
# vowels list
vowels = ['a', 'e', 'i', 'o',
'i', 'u']
# index is printed
print('The index of e:', index)
first_num = int(input('Enter
first number: '))
second_num = int(input('Enter
second number: '))
third_num = int(input('Enter
third number: '))
our_list.append(first_num)
our_list.append(second_num)
our_list.append(third_num)
print(our_list)
MOHAN S.REDDY
# empty range
print(list(range(0)))
# using range(stop)
print(list(range(10)))
What is tuple?
In Python programming, a tuple is similar to a list. The difference between the
two is that we cannot change the elements of a tuple once it is assigned whereas
in a list, elements can be changed.
Creating a Tuple
A tuple is created by placing all the items (elements) inside a parentheses (),
separated by comma. The parentheses are optional but is a good practice to
write it.
A tuple can have any number of items and they may be of different types
(integer, float, list, string etc.).
Ex:
# empty tuple
tpl = ()
print(tpl)
# tuple with integers
tpl = (1, 2, 3)
print(tpl)
# tuple with different
datatypes
tpl = (9, "mohan", 3.4)
print(tpl)
# nested tuple
tpl = ("mohan", (8, 4, 60), (1,
MOHAN S.REDDY
2, 3))
print(tpl)
# tuple creating without
brakets is called tuple packing
tpl = 5, 7.8, "hai"
print(tpl)
Creating a tuple with one element is a bit tricky.
Having one element within parentheses is not enough. We will need a trailing
comma to indicate that it is in fact a tuple.
1. Indexing
We can use the index operator [] to access an item in a tuple where the index
starts from 0.
tpl =
('d','u','r','g','a','s','o','f
','t')
print(tpl)
print(tpl[2])
print(tpl[5])
# nested tuple
ntpl = ("durga", (7, 8, 6), (1,
2, 3))
print(ntpl[0][3])
print(ntpl[1][1])
print(ntpl[2][1])
#negative indexing
print(tpl[-4])
print(tpl[-5])
Tuple Slicing:
MOHAN S.REDDY
tpl =
('d','u','r','g','a','s','o','f
','t')
print(tpl)
print(tpl[1:2])
print(tpl[:4])
print(tpl[2:])
print(tpl[:])
Tuple Immutable:
Unlike lists, tuples are immutable
This means that elements of a tuple cannot be changed once it has been
assigned
tpl=(10,20,30)
print(tpl)
tpl[1]=33
print(tpl)
We can also repeat the elements in a tuple for a given number of times using the
* operator.
MOHAN S.REDDY
# Concatenation
print((1, 2, 3) + (4, 5, 6))
# Multiplication
print(("durga",) * 5)
Deleting a Tuple
As discussed above, we cannot change the elements in a tuple. That also means
we cannot delete or remove items from a tuple.
tpl=('d','u','r','g','a')
print(tpl)
del tpl
print(tpl)
Tuple Methods():
Methods that add items or remove items are not available with tuple. Only the
following two methods are available.
tpl = ('b','a','n','a','n','a')
print(tpl.count('n'))
MOHAN S.REDDY
print(tpl.index('a'))
Tuple Membership Test
We can test if an item exists in a tuple or not, using the keyword in.
tpl = ('b','a','n','a','n','a')
print('b' in tpl)
print('i' in tpl)
print('i' not in tpl)
Max():
print('Maximum is:', max(1, 3,
2, 5, 4))
tpl = (1, 3, 2, 8, 5, 10, 6)
print('Maximum is:', max(tpl))
Min():
MOHAN S.REDDY
Sum():
tpl=tuple(str)
MOHAN S.REDDY
print(tpl)
print(type(tpl))
tpl=tuple(lst)
print(tpl)
print(type(tpl))
string=str(tpl)
print(string)
print(type(string))
MOHAN S.REDDY
What is set:
A set is an unordered collection of items. Every element is unique (no duplicates) and
must be immutable (which cannot be changed).
Sets can be used to perform mathematical set operations like union, intersection,
symmetric difference etc
Creating set:
A set is created by placing all the items (elements) inside curly braces {},
separated by comma or by using the built-in function set().
It can have any number of items and they may be of different types (integer, float,
tuple, string etc.).
EX:
# set of integers
myset = {1, 2, 3}
print(myset)
# different datatypes
myset = {1.0, "Hello", (1, 2,
3)}
print(myset)
#no duplicates in set
myset = {1,2,3,4,3,2}
print(myset)
MOHAN S.REDDY
Empty curly braces {} will make an empty dictionary in Python. To make a set
without any elements we use the set() function without any argument.
a = {}
print(type(a))
a = set()
print(type(a))
We can add single element using the add() method and multiple elements using
the update() method. The update() method can take tuples, lists, strings or other
sets as its argument. In all cases, duplicates are avoided.
myset = {1,3}
print(myset)
# add an element
myset.add(2)
print(myset)
print(myset)
The only difference between the two is that, while using discard() if the item
does not exist in the set, it remains unchanged. But remove() will raise an error in
such condition.
# initialize my_set
myset = {1, 3, 4, 5, 6}
print(myset)
# discard an element
myset.discard(4)
print(myset)
# remove an element
myset.remove(6)
print(myset)
# discard an element
MOHAN S.REDDY
Let us consider the following two sets for the following operations.
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
Set Union
# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
MOHAN S.REDDY
# use | operator
print(A | B)
#use union function
print(A.union(B))
Set Intersection
Intersection is performed using & operator. Same can be accomplished using the
method intersection().
# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
Set Difference
Difference of A and B (A - B) is a set of elements that are only in A but not in B.
Similarly, B - A is a set of element in B but not in A.
MOHAN S.REDDY
# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
# use - operator on A
# Output: {1, 2, 3}
#print(A - B)
#use difference()
print(A.difference(B))
# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
# use ^ operator
#print(A ^ B)
#use symanticdifference
print(A.symmetric_difference(B)
)
MOHAN S.REDDY
ADD():
It will add an element to set
The add() method doesn't add an element to the set if it's already
present in it.
# set of vowels
vowels = {'a', 'e', 'i', 'u'}
# adding 'o'
vowels.add('o')
print('Vowels are:', vowels)
# adding 'a' again
vowels.add('a')
print('Vowels are:', vowels)
Set membership test:
# initialize my_set
myset = set("apple")
print('a' in myset)
print('p' not in myset)
Len():
myset={10,20,30,40,50,60}
print(len(myset))
# using max(iterable)
myset = {1, 3, 2, 8, 5, 10, 6}
print('Maximum is:',
max(myset))
# using min(iterable)
myset = {1, 3, 2, 8, 5, 10, 6}
print('Maximum is:',
min(myset))
Sum():
# start = 7
Total = sum(myset, 7)
print(Total)
What is Dictionary:
MOHAN S.REDDY
Creating Dictionary:
An item has a key and the corresponding value expressed as a pair, key: value.
While values can be of any data type and can repeat, keys must be of immutable
type (string, number or tuple with immutable elements) and must be unique.
EX:
# empty dictionary
mydict = {}
print(mydict)
# dictionary with integer keys
mydict = {1: 'mohan', 2:
'durga'}
print(mydict)
# dictionary with mixed keys
mydict = {'name': 'sai', 1: [3,
4, 5]}
print(mydict)
# using dict()
mydict = dict({1:'mohan',
2:'sai'})
MOHAN S.REDDY
print(mydict)
# from sequence having each
item as a pair
mydict = dict([(1,'raj'),
(2,'ram')])
print(mydict)
While indexing is used with other container types to access values, dictionary
uses keys. Key can be used either inside square brackets or with
the get() method.
The difference while using get() is that it returns None instead of KeyError, if the
key is not found.
mydict = {'name':'manoj',
'age': 45}
print(mydict['name'])
print(mydict.get('age'))
Dictionary are mutable. We can add new items or change the value of existing
items using assignment operator.
If the key is already present, value gets updated, else a new key: value pair is
added to the dictionary.
Ex:
We can remove a particular item in a dictionary by using the method pop(). This
method removes as item with the provided key and returns the value.
The method, popitem() can be used to remove and return an arbitrary item (key,
value) form the dictionary. All the items can be removed at once using
the clear() method.
We can also use the del keyword to remove individual items or the entire
dictionary itself.
# create a dictionary
mydict = {1:1, 2:4, 3:9, 4:16,
5:25}
MOHAN S.REDDY
Copy():
Values:
What is Function:
.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.
Functions help break our program into smaller and modular chunks.
As our program grows larger and larger, functions make it more organized and
manageable.
MOHAN S.REDDY
1. Built in Functions
1. Built in Functions:
Eg: id()
type()
input()
eval()
Len()
etc..
def function_name(parameters) :
Statements…
return value
1. def (mandatory)
2. return (optional)
def fun():
print("Hello")
fun()
fun()
fun()
Parameters:
MOHAN S.REDDY
Eg: Write a function to take name of the student as input and print wish
message by name.
def fun(name):
print("Hello",name,"good morning")
fun("mohan")
fun("sai")
Eg: Write a function to take number as input and print its square value
def square(num):
print("Square value of ",num, "is",
num*num)
square(4)
square(3)
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("sum is:",result)
MOHAN S.REDDY
def add(x,y):
return x+y
print(add(30,20))
If we are not writing return statement then default return value is None
def myfunction(course =
"Python"):
print("My course is:" +
course)
myfunction("Dotnet")
myfunction("java")
myfunction()
myfunction("Php")
def even_odd(num):
if num%2==0:
print(num,"is Even")
else:
MOHAN S.REDDY
print(num,"is Odd")
even_odd(10)
even_odd(9)
Lifetime of a variable is the period throughout which the variable exits in the
memory. The lifetime of variables inside a function is as long as the function
executes.
They are destroyed once we return from the function. Hence, a function does not
remember the value of a variable from its previous calls.
def myfunc():
x = 10
print("Value inside
function:",x)
x = 20
myfunc()
print("Value outside
function:",x)
MOHAN S.REDDY
print(num1,"+",num2,"=",
add(num1,num2))
elif choice == '2':
print(num1,"-",num2,"=",
subtract(num1,num2))
elif choice == '3':
print(num1,"*",num2,"=",
multiply(num1,num2))
elif choice == '4':
print(num1,"/",num2,"=",
divide(num1,num2))
else:
print("Invalid input")
Types of arguments :
def f1(a,b):
------
------
------
f1(10,20)
1. positional arguments
2. keyword arguments
3. default arguments
4. Variable length arguments
1. positional arguments:
def sub(a,b):
print(a-b)
MOHAN S.REDDY
sub(100,200)
sub(200,100)
EX:
def sub(x,y):
print("sum is:",x-y)
sub(10,20)
2. keyword arguments:
def fun(name,msg):
print("Hello",name,msg)
fun(name="Durga",msg="Good
Morning")
fun(msg="Good
Morning",name="Durga")
MOHAN S.REDDY
Note:
def fun(name,msg):
print("Hello",name,msg)
fun("Durga","GoodMorning") ==>valid
fun("Durga",msg="GoodMorning") ==>valid
fun(name="Durga","GoodMorning") ==>invalid
SyntaxError: positional argument follows keyword
argument
3. Default Arguments:
def fun(name="Guest"):
print("Hello",name,"Good
Morning")
MOHAN S.REDDY
fun("Durga")
fun()
If we are not passing any name then only default value will
be considered.
***Note:
def f1(*n):
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)
1. Global Variables
2. Local Variables
1. Global Variables
print(a)
def f2():
print(a)
f1()
f2()
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.
def f1():
a=10
print(a) #valid
def f2():
print(a) #invalid
f1()
f2()
Error: name a is not defined
global keyword:
a=10
def f1():
a=777
print(a)
def f2():
print(a)
f1()
f2()
Ex:
a=10
def f1():
global a
a=777
print(a)
def f2():
print(a)
f1()
f2()
MOHAN S.REDDY
def f1():
a=10
print(a)
def f2():
print(a)
f1()
f2()
Error: a is not defined:
Ex:
def f1():
global a
a=10
print(a)
def f2():
print(a)
f1()
f2()
Note: If global variable and local variable having the same name then we
can access global variable inside a function as follows
MOHAN S.REDDY
Recursive Functions :
A function that calls itself is known as Recursive Function.
Eg: factorial(3)
=3*factorial(2)
=3*2*factorial(1)
=3*2*1*factorial(0)
=3*2*1*1 =6
factorial(n)= n*factorial(n-1)
Ex:
def factorial(n):
if n==0:
MOHAN S.REDDY
result=1
else:
result=n*factorial(n-
1)
return result
print("Factorial of 4
is:",factorial(4))
print("Factorial of 5
is:",factorial(5))
Anonymous Functions:
Normal Function:
def square(n):
return n*n
lambda Function:
We can define by using lambda keyword
lambda n:n*n
EX:
s=lambda n:n*n
print("Square of 4 is:",s(4))
print("Square of 5 is:",s(5))
s=lambda a,b:a+b
print("Sumof 10,20
is",s(10,20))
print("Sumof 100,200
is",s(100,200))
filter() function:
filter(function,sequence)
def isEven(x):
if x%2==0:
return True
else:
return False
L=[2,6,3,5,8,12,13]
L1=list(filter(isEven,L))
print(L1)
L=[2,3,4,8,9,12,10,15,13]
L1=list(filter(lambda
x:x%2==0,L))
print(L1)
L2=list(filter(lambda
x:x%2!=0,L))
print(L2)
map() function:
Syntax: map(function,sequence)
Without lambda:
MOHAN S.REDDY
L=[1,2,3,4,5]
def double(x):
return 2*x
L1=list(map(double,L))
print(L1)
with lambda:
L=[2,4,6,8]
L1=list(map(lambda x:2*x,L))
print(L1)
L1=[1,2,3,4]
L2=[2,3,4,5]
L3=list(map(lambda
x,y:x*y,L1,L2))
print(L3)
MOHAN S.REDDY
reduce() function:
reduce(function,sequence)
Note:
def f1():
print("Hello")
print(f1)
print(id(f1))
Function Aliasing:
def wish(name):
print("Good Morning",name)
greeting=wish
print(id(wish))
print(id(greeting))
greeting("Mohan")
wish("mohan")
def wish(name):
print("Good Morning",name)
MOHAN S.REDDY
greeting=wish
greeting("Mohan")
wish("mohan")
del wish
#wish("sai")
greeting("sai")
Nested Function:
def multi(a):
def mul(b):
def mu(c):
return a*b*c
return mu
return mul
y=multi(10)(20)(2)
print(y)
MOHAN S.REDDY
dir():
The dir() function returns all properties and methods of the specified
object, without the values.
This function will return all the properties and methods, even built-in
properties which are default for all object.
Syntax: dir(object)
Ex:
l1=[1,2,3,4]
print(dir(l1))
Ex:
number = [1, 2, 3]
print(dir(number))
print(dir())
Format():
Syntax: format(value,format)
EX:
x = format(0.5, '%')
print(x)
MOHAN S.REDDY
x = format(10000, '_')
print(x)
x = format(10000, 'e')
print(x)
enumerate():
The enumerate() method adds counter to an iterable and returns it. The returned object is a
enumerate object.
A lot of times when dealing with iterators, we also get a need to keep a count of
iterations. Python eases the programmers’ task by providing a built-in function
enumerate() for this task.
Enumerate() method adds a counter to an iterable and returns it in a form of
enumerate object.
Syntax: enumerate(iterable,start)
x = ('apple', 'banana',
'cherry')
y = enumerate(x)
print(x)
print(y)
Converting enumerate into List:
L1 = ['Pepsi', 'Sprite',
'Thumsup']
L2 = enumerate(L1)
print(type(L2))
MOHAN S.REDDY
# converting to list
print(list(L2))
# changing the default counter
L2 = enumerate(L1, 10)
print(list(L2))
Modules:
Sample.py:
x=123
def add(a,b):
print("sum is:",a+b)
def mul(a,b):
print("Product is:",a*b)
import modulename
modulename.variable
modulename.function()
test.py:
import sample
print(sample.x)
sample.add(10,20)
sample.mul(30,20)
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
import sample as s
print(s.x)
s.add(10,20)
s.mul(30,20)
MOHAN S.REDDY
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 *
MOHAN S.REDDY
member aliasing:
print(y)
sum(10,20)
Once we defined as alias name, we should use alias name only and we
should not use original name
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.
Module1.py:
MOHAN S.REDDY
def f1():
if __name__=='__main__':
print("The Code
Executed as program")
else:
print("The Code
Executed as module from some
other program")
f1()
test1.py:
import module1
module1.f1()
1. sqrt(x)
2. ceil(x)
3. floor(x)
4. fabs(x)
MOHAN S.REDDY
5.log(x)
6. sin(x)
7. tan(x) ....
Ex:
from math import*
print(sqrt(4))
print(ceil(10.1))
print(floor(10.1))
print(fabs(-10.6))
print(fabs(10.6))
Note: We can find help for any module by using help() function
import math
help(math)
Working with random module:
1. random() function:
EX:
from random import *
for i in range(10):
print(randint(1,100))
3. uniform():
for i in range(10):
print(uniform(1,10))
random() ===>in between 0 and 1 (not inclusive)
randint(x,y) ==>in between x and y ( inclusive)
MOHAN S.REDDY
4. randrange([start],stop,[step])
Ex:
for i in range(10):
print(randrange(10))
5. choice() function:
Ex:
from random import *
list=["mohan","rohan","pavan","
bhuvan"]
MOHAN S.REDDY
for i in range(10):
print(choice(list))
DateTime Module:
EX:
import datetime
x=datetime.datetime.now()
print(x)
The date contains year, month, day, hour, minute, second, and
microsecond.
The datetime module has many methods to return information about the
date object.
EX:
import datetime
x=datetime.datetime.now()
print(x.year)
print(x.day)
print(x.month)
Ex:
import datetime
x=datetime.datetime(2010,3,23)
#x=datetime.datetime(2010,12,32
) day is out of of range for
month
print(x)
Strrftime() Method:
The datetime object has a method for formatting date objects into
readable strings.
Ex:
import datetime
x=datetime.datetime(2018,9,3)
print(x.strftime('%A'))
print(x.strftime('%B'))
print(x.strftime('%a'))
print(x.strftime('%b'))
MOHAN S.REDDY
print(x.strftime('%y'))
print(x.strftime('%Y'))
%a ----weekday,short version
%A-----weekday, full version
%b-----month, short version
%B-----month, full version
%y---- year,short version
%Y-----year. Full version
Calendar:
we import the calendar module. The built-in function month() inside the module takes in
the year and the month and displays the calendar for that month of the year.
import calendar
yy=2016
mm=10
print(calendar.month(yy,mm))
Array :
MOHAN S.REDDY
However, in Python, there is no native array data structure. So, we use Python
lists instead of an array.
Note: If you want to create real arrays in Python, you need to use NumPy's
array data structure. For mathematical problems, NumPy Array is more efficient.
Unlike arrays, a single list can store elements of any data type and does
everything an array does. We can store an integer, a float and a string inside the
same list. So, it is more flexible to work with.
[10, 20, 30, 40, 50 ] is an example of what an array would look like in Python,
but it is actually a list.
import array
A=array.array('i',[4,3,2,5])
print(A)
print(type(A))
MOHAN S.REDDY
print(A[i])
for i in range(len(A)):
print(A[i])
#copying Array
from array import *
A=array('i',[2,3,4,5])
print(A)
B=array(A.typecode,(i*i for i
in A))
print(B)
#character array
from array import *
A=array('u',['m','o','h','a','n
'])
print(A)
Array"))
for i in range(n):
x=int(input("Enter the next
value:"))
arr.append(x)
print(arr)
s=int(input("Enter the value
for search:"))
#searchinng element in Array
print(arr.index(s))
What is NumPy?
NumPy is a general-purpose array-processing package.
It provides a high-performance multidimensional array object, and tools for
working with these arrays.
It is the fundamental package for scientific computing with Python.
▪ In NumPy dimensions are called axes. The number of axes is rank.
Click on File
MOHAN S.REDDY
Click on settings
Expand Project
Choose numpy
Array()
Linespace()
Logspace()
Arange()
Zeros()
Ones()
EX:
Array():
MOHAN S.REDDY
Linespace()
Logspace()
MOHAN S.REDDY
Arange()
Zeros()
Ones()
import numpy as np
#creating array
arr=np.array([[1,2,3],
[4,5,6]])
#printing type of array
print("Array type
is:",type(arr))
# Printing array dimensions
(axes)
print("No. of dimensions: ",
arr.ndim)
# Printing shape of array
print("Shape of array: ",
arr.shape)
# Printing size (total number
of elements) of array
print("Size of array: ",
arr.size)
# Printing type of elements in
array
print("Array stores elements of
type: ", arr.dtype)
We can use flatten method to get a copy of array collapsed into one dimension. It
accepts order argument.
MOHAN S.REDDY
import numpy as np
#creating array
arr=np.array([[1,2,3],
[4,5,6]])
flat = arr.flatten()
print(flat)
print("Column-wise minimum
elements:",
arr.min(axis=0))
# sum of array elements
print("Sum of all array
elements:",
arr.sum())
What is Class:
1. print(classname.__doc__)
2. help(classname)
class student:
"""this is student calss
with required data"""
print(student.__doc__)
help(student)
1. Instance Methods
2. Class Methods
3. Static Methods
def details(self):
print("My EmpId:",self.id)
print("My Name:",self.name)
print("My Age:",self.age)
What is Object:
referencevariable = classname()
MOHAN S.REDDY
Example: s = Student()
The variable which can be used to refer object is called reference variable.
By using reference variable, we can access properties and methods of
object.
EX:
class Student:
self.name = name
self.rollno = rollno
self.marks = marks
def talk(self):
Self variable:
self is the default variable which is always pointing to current object (like
this keyword in Java..Net)
MOHAN S.REDDY
Note:
1. self should be first parameter inside constructor def __init__(self):
Constructor Concept:
Ex:
def __init__(self,name,rollno,marks):
self.name=name
self.rollno=rollno
self.marks=marks
class test:
def __init__(self):
print("Constructor Execution")
MOHAN S.REDDY
def m1(self):
print("Method Execution")
t1=test()
t2=test()
t3=test()
t1.m1()
EX:
class Student:
def __init__(self,x,y,z):
self.name=x
self.rollno=y
self.marks=z
def display(self):
print("Student Name:{}\nRollno:{}
\nMarks:{}".format(self.name,self.rollno,self.marks
) )
s1=Student("Durga",101,80)
s1.display()
s2=Student("Sunny",102,100)
s2.display()
MOHAN S.REDDY
Types of Variables:
1. Instance Variables:
If the value of a variable is varied from object to object, then such type of
variables are called instance variables.
EX:
#inside constructor by using self variable
class Employee:
def __init__(self):
self.eno=101
self.ename='durga'
self.esal=23000
e=Employee()
print(e.__dict__)
Ex:
#inside instance method by using self variable
class test:
def __init__(self):
self.a=10
self.b=20
def m1(self):
self.c=30
t=test()
t.m1()
print(t.__dict__)
MOHAN S.REDDY
Ex:
#outside of the class by using object reference
variable
class test:
def __init__(self):
self.a=10
self.b=20
def m1(self):
self.c=30
t=test()
t.m1()
t.d=40
print(t.__dict__)
We can access instance variables with in the class by using self variable
and outside of the class by using object reference.
Ex:
#how to access instance variables
class test:
MOHAN S.REDDY
def __init__(self):
self.a=10
self.b=20
def display(self):
print(self.a)
print(self.b)
t=test()
t.display()
print(t.a,t.b)
del self.variableName
del objectreference.variableName
EX:
class test:
def __init__(self):
self.a=10
self.b=20
self.c=30
self.d=40
def m1(self):
del self.d
t=test()
MOHAN S.REDDY
print(t.__dict__)
t.m1()
print(t.__dict__)
del t.c
print(t.__dict__)
Note: The instance variables which are deleted from one object, will not
be deleted from other objects
EX:
class test:
def __init__(self):
self.a=10
self.b=20
self.c=30
self.d=40
t1=test()
t2=test()
del t1.a
print(t1.__dict__)
print(t2.__dict__)
Ex:
MOHAN S.REDDY
class test:
def __init__(self):
self.a=10
self.b=20
t1=test()
t1.a=123
t1.b=345
t2=test()
print("t1:",t1.a,t1.b)
print("t2:",t2.a,t2.b)
1. Static variables:
If the value of a variable is not varied from object to object, such type of
variables we have to declare with in the class directly but outside of
methods. Such type of variables are called Static variables.
For total class only one copy of static variable will be created and shared
by all objects of that class.
Note: In the case of instance variables for every object a seperate copy
will be created,but in the case of static variables for total class only one
copy will be created and shared by every object of that class
MOHAN S.REDDY
EX:
#static variables
class test:
x=10
def __init__(self):
self.y=20
t1=test()
t2=test()
print("t1:",t1.x,t1.y)
print("t2:",t2.x,t2.y)
test.x=777
t1.y=999
print("t1:",t1.x,t1.y)
print("t2:",t2.x,t2.y)
1. In general we can declare within the class directly but from out side of
any method
2. Inside constructor by using class name
3. Inside instance method by using class name
4. Inside class method by using either class name or class variable
5. Inside static method by using class name
test.c=30
@classmethod
def m2(cls):
cls.d1=40
test.d2=400
@staticmethod
def m3():
test.e=50
print(test.__dict__)
t=test()
print(test.__dict__)
t.m1()
print(test.__dict__)
test.m2()
print(test.__dict__)
test.m3()
print(test.__dict__)
test.f=60
print(test.__dict__)
Local variables:
EX:
class test:
def m1(self):
a=1000
print(a)
MOHAN S.REDDY
def m2(self):
b=2000
print(a) #a is not defined
print(b)
t=test()
t.m1()
t.m2()
Types of Methods:
1. Instance Methods
2. Class Methods
3. Static Methods
1. Instance Methods:
def m1(self):
Within the class we can call instance method by using self variable and
from outside of the class we can call by using object reference.
MOHAN S.REDDY
Ex:
class student:
def __init__(self,name,marks):
self.name=name
self.marks=marks
def display(self):
print("Hi",self.name)
print("Your marks are:",self.marks)
def grade(self):
if self.marks>60:
print("You Got First Grade")
elif self.marks>50:
print("You got Second Grade")
elif self.marks>=35:
print("You got third Grade")
else:
print("You Failed")
for i in range(1):
name=input("Enter Name:")
marks=int(input("Enter Marks"))
s=student(name,marks)
s.display()
s.grade()
print()
We can set and get the values of instance variables by using getter and
setter methods.
Setter Method:
MOHAN S.REDDY
syntax:
def setVariable(self,variable):
self.variable=variable
Example:
def setName(self,name):
self.name=name
Getter Method:
Getter methods can be used to get values of the instance variables. Getter
methods also known as accessor methods.
syntax:
def getVariable(self):
return self.variable
Example:
def getName(self):
MOHAN S.REDDY
return self.name
Ex:
class Student:
def setName(self,name):
self.name=name
def getName(self):
return self.name
def setMarks(self,marks):
self.marks=marks
def getMarks(self):
return self.marks
for i in range(1):
s=Student()
name=input('Enter Name:')
s.setName(name)
marks=int(input('Enter Marks:'))
s.setMarks(marks)
print('Hi',s.getName())
print('Your Marks are:',s.getMarks())
print()
2. Class Methods:
Ex:
class Animal:
legs=4
@classmethod
def walk(cls,name):
print('{} walks with {}
legs...'.format(name,cls.legs))
Animal.walk('Dog')
Animal.walk('Cat')
3. Static Methods:
EX:
class DurgaMath:
@staticmethod
def add(x, y):
print('The Sum:', x + y)
@staticmethod
def product(x, y):
print('The Product:', x * y)
@staticmethod
MOHAN S.REDDY
Note: In general we can use only instance and static methods.Inside static
method we can access class level variables by using class name.
Ex:
class Employee:
def __init__(self,eno,ename,esal):
self.eno=eno
self.ename=ename
self.esal=esal
def display(self):
print('Employee Number:',self.eno)
print('Employee Name:',self.ename)
print('Employee Salary:',self.esal)
class Test:
def modify(emp):
emp.esal=emp.esal+10000
emp.display()
MOHAN S.REDDY
e=Employee(100,'Durga',10000)
Test.modify(e)
Inner classes:
class Car:
.....
class Engine:
......
class University:
.....
class Department:
......
MOHAN S.REDDY
class Human:
class Head:
EX:
class Outer:
def __init__(self):
print("outer class object creation")
class Inner:
def __init__(self):
print("inner class object creation")
def m1(self):
print("inner class method")
o=Outer()
i=o.Inner()
i.m1()
MOHAN S.REDDY
Note: The following are various possible syntaxes for calling inner class
method
1. o=Outer()
i=o.Inner()
i.m1()
2. i=Outer().Inner()
i.m1()
3. Outer().Inner().m1()
Ex:
class Human:
def __init__(self):
self.name = 'Sunny'
self.head = self.Head()
self.brain = self.Brain()
def display(self):
print("Hello..", self.name)
class Head:
def talk(self):
print('Talking...')
class Brain:
def think(self):
print('Thinking...')
h = Human()
h.display()
h.head.talk()
h.brain.think()
MOHAN S.REDDY
Garbage Collection:
If an object does not have any reference variable then that object eligible
for Garbage Collection.
1. gc.isenabled()
2. gc.disable()
To disable GC explicitly
3. gc.enable()
To enable GC explicitly
EX:
import gc
print(gc.isenabled())
gc.disable()
print(gc.isenabled())
gc.enable()
print(gc.isenabled())
Destructors:
sys.getrefcount(objectreference)
Example:
import sys
class Test:
pass
t1=Test()
t2=t1
t3=t1
t4=t1
print(sys.getrefcount(t1))
Encapsulation:
In object oriented programming we can restrict the access to the
variables and methods , this process is called Encapsulation.
1.private
2.public
Ex:
class car:
def __init__(self):
self.__updatesoftware()
def drive(self):
print("driving")
def __updatesoftware(self):
print("updating software")
c=car()
c.drive()
Ex:
class car:
#def __init__(self):
# self.__updatesoftware()
MOHAN S.REDDY
def drive(self):
print("driving")
def __updatesoftware(self):
print("updating software")
c=car()
c.drive()
c.__updatesoftware()
Private Variables:
EX:
class car:
__maxspeed=0
__name=""
def __init__(self):
self.__maxspeed=200
self.__name="FordFigo"
def drive(self):
print("driving")
MOHAN S.REDDY
print(self.__maxspeed)
def setspeed(self,speed):
self.__maxspeed=speed
print(self.__maxspeed)
c=car()
c.drive()
c.setspeed(100)
Ex2:
class car:
__maxspeed=0
__name=""
def __init__(self):
self.__maxspeed=200
self.__name="FordFigo"
def drive(self):
print("driving")
print(self.__maxspeed)
c=car()
c.drive()
c.__maxspeed=100
c.drive()
MOHAN S.REDDY
Polymorphism:
Poly means many. Morphs means forms.
2. Overloading
MOHAN S.REDDY
1. Operator Overloading
2. Method Overloading
3. Constructor Overloading
3. Overriding
1. Method overriding
2. constructor overriding
def f1(obj):
obj.talk()
Overloading:
Eg1:
print(10+20)#30
print('durga'+'soft')#durgasoft
print(10*20)#200
print('durga'*3)#durgadurgadurga
deposit(cash)
deposit(cheque)
deposit(dd)
1. Operator Overloading
MOHAN S.REDDY
2. Method Overloading
3. Constructor Overloading
1. Operator Overloading:
print(10+20)#30
print('durga'+'soft')#durgasoft
print(10*20)#200
print('durga'*3)#durgadurgadurga
Ex:
class Book:
b1 = Book(100)
b2 = Book(200)
print(b1 + b2)
We can overload + operator to work with Book objects also. i.e Python
supports Operator Overloading.
EX:
class Book:
def __init__(self,pages):
self.pages=pages
def __add__(self,other):
return self.pages+other.pages
b1=Book(100)
b2=Book(200)
print('The Total Number of Pages:',b1+b2)
EX:
class Employee:
def __init__(self,name,salary):
MOHAN S.REDDY
self.name=name
self.salary=salary
def __mul__(self,other):
return self.salary*other.days
class TimeSheet:
def __init__(self,name,days):
self.name=name
self.days=days
e=Employee('Durga',500)
t=TimeSheet('Durga',25)
print('This Month Salary:',e*t)
2. Method Overloading:
Eg:
m1(int a)
m1(double d)
EX:
class Test:
def m1(self):
print('no-arg method')
t = Test()
# t.m1()
# #t.m1(10)
# t.m1(10,20)
t.m1(10,20)
3. Constructor Overloading:
EX:
class Test:
def __init__(self):
print('No-Arg Constructor')
def __init__(self,a):
print('One-Arg constructor')
def __init__(self,a,b):
print('Two-Arg constructor')
#t1=Test()
# #t1=Test(10)
t1=Test(10,20)
Method overriding:
MOHAN S.REDDY
What ever members available in the parent class are by default 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.
EX:
class P:
def property(self):
print('Gold+Land+Cash+Power')
def marry(self):
print('Appalamma')
class C(P):
def marry(self):
print('Katrina Kaif')
c=C()
c.property()
c.marry()
From Overriding method of child class,we can call parent class method
also by using super() method.
EX:
class P:
def property(self):
print('Gold+Land+Cash+Power')
def marry(self):
print('Appalamma')
MOHAN S.REDDY
class C(P):
def marry(self):
super().marry()
print('Katrina Kaif')
c=C()
c.property()
c.marry()
Inheritance :
The new class is called derived (or child) class and the one from which it
inherits is called the base (or parent) class.
Syntax:
Class Baseclass:
Body of baseclass
Class Derivedclass(Baseclass):
Body of Derivedclass
Derived class inherits features from the base class, adding new features to it. This
results into re-usability of code.
Ex:
MOHAN S.REDDY
class Vehicle:
def general_usage(self):
print("general use: Transportation")
class car(Vehicle):
def __init__(self):
print("I am a car")
self.wheels=4
self.hasroof=True
def specific_usage(self):
print("Specific use:vacation with family")
class Motorcycle(Vehicle):
def __init__(self):
print("I am a Motor Cycle")
self.wheels = 2
self.hasroof = False
def specific_usage(self):
print("Specific use:road trip,racing")
c=car()
c.general_usage()
c.specific_usage()
m=Motorcycle()
m.general_usage()
m.specific_usage()
Benefits of Inheritance:
1.Code Reuse
2.Extensibility
3.Readability
MOHAN S.REDDY
print(isinstance(c,car))
print(isinstance(c,Motorcycle))
print(issubclass(car,Vehicle))
print(issubclass(car,Motorcycle))
Exception Handling:
In any programming language there are 2 types of errors are possible.
1. Syntax Errors:
The errors which occurs because of invalid syntax are called syntax
errors.
EX:
x=10
if x==10
print("hello")
MOHAN S.REDDY
Ex:
print "Hello"
2. Runtime Errors:
x=int(input("Enter Number:"))
print(x)
Enter Number :ten ValueError: invalid literal for int() with base 10:
'ten'
Note: Exception Handling concept applicable for Runtime Errors but not
for syntax errors
MOHAN S.REDDY
What is Exception:
Eg:
ZeroDivisionError
TypeError
ValueError
FileNotFoundError
EOFError
SleepingError
TyrePuncturedError
Eg:
EX:
print("Hello")
print(10/0)
print("hai")
Every Exception in Python is a class. All exception classes are child classes
of BaseException.i.e every exception class extends BaseException either
directly or indirectly. Hence BaseException acts as root for Python
Exception Hierarchy.
try:
Risky Code
except XXXXX:
MOHAN S.REDDY
EX:
without try-except
print("Hello")
print(10/0)
print("hai")
OUTPUT:
Hello
Division by zero
with try-except:
Ex:
print("Hello")
try:
print(10/0)
except ZeroDivisionError:
print(10/2)
print("hai")
Normal termination/Graceful Termination
try:
stmt-1
stmt-2
stmt-3
except XXX:
stmt-4
stmt-5
1, Abnormal Termination
Conclusions:
1. within the try block if anywhere exception raised then rest of the
try block wont be executed even though we handled that
exception.
Hence we have to take only risky code inside try block and length of
the try block should be as less as possible.
MOHAN S.REDDY
3. If any statement which is not part of try block raises an exception then
it is always abnormal termination.
EX:
try:
print(10/0)
except ZeroDivisionError as msg:
print("exception raised and its
description is:", msg)
i.e try with multiple except blocks is possible and recommended to use.
Eg:
try:
-------
-------
-------
MOHAN S.REDDY
except ZeroDivisionError:
perform alternative
arithmetic operations
except FileNotFoundError:
If try with multiple except blocks available then based on raised exception
the corresponding except block will be executed.
EX:
try:
x=int(input("Enter First Number:
"))
y=int(input("Enter Second Number:
"))
print(x/y)
except ZeroDivisionError :
print("Can't Divide with Zero")
except ValueError:
print("please provide int value
only")
If try with multiple except blocks available then the order of these except
blocks is important .
Python interpreter will always consider from top to bottom until matched
except block identified.
MOHAN S.REDDY
EX:
try:
x=int(input("Enter First Number:
"))
y=int(input("Enter Second Number:
"))
print(x/y)
except ArithmeticError :
print("ArithmeticError")
except ZeroDivisionError:
print("ZeroDivisionError")
We can write a single except block that can handle multiple different
types of exceptions.
except (Exception1,Exception2,exception3,..):
or
EX:
try:
x=int(input("Enter First Number: "))
y=int(input("Enter Second Number: "))
print(x/y)
MOHAN S.REDDY
Syntax:
except:
statements
EX:
try:
x=int(input("Enter First Number: "))
y=int(input("Enter Second Number: "))
print(x/y)
except ZeroDivisionError:
print("ZeroDivisionError:Can't divide with
zero")
except:
print("Default Except:Plz provide valid input
only")
***Note: If try with multiple except blocks available then default except
block should be last,otherwise we will get SyntaxError.
EX:
MOHAN S.REDDY
try:
print(10/0)
except:
print("Default Except")
except ZeroDivisionError:
print("ZeroDivisionError")
Note:
1. except ZeroDivisionError:
3. except (ZeroDivisionError,ValueError) :
5. except :
finally block:
Syntax:
try:
Risky Code
except:
Handling Code
finally:
Cleanup code
Ex:
try:
print("try")
except:
print("except")
finally:
print("finally")
EX:
try:
print("try")
print(10/0)
except ZeroDivisionError:
print("except")
finally:
print("finally")
EX:
try:
print("try")
print(10/0)
except NameError:
print("except")
finally:
print("finally")
*** Note: There is only one situation where finally block won't be
executed i.e whenever we are using os._exit(0) function.
EX:
import os
try:
print("try")
os._exit(0)
except NameError:
MOHAN S.REDDY
print("Except")
finally:
print("Finally")
try:
stmt-1
stmt-2
stmt-3
except:
stmt-4
finally:
stmt-5
stmt6
try:
----------
----------
----------
try:
-------------
--------------
--------------
except:
--------------
--------------
--------------
MOHAN S.REDDY
------------
except:
-----------
-----------
-----------
General Risky code we have to take inside outer try block and too much
risky code we have to take inside inner try block. Inside Inner try block if
an exception raised then inner except block is responsible to handle. If it
is unable to handle then outer except block is responsible to handle.
EX:
try:
print("outer try block")
try:
print("Inner try block")
print(10/0)
except ZeroDivisionError:
print("Inner except block")
finally:
print("Inner finally block")
except:
print("outer except block")
finally:
print("outer finally block")
try:
stmt-1
MOHAN S.REDDY
stmt-2
stmt-3
try:
stmt-4
stmt-5
stmt-6
except X:
stmt-7
finally:
stmt-8
stmt-9
except Y:
stmt-10
finally:
stmt-11
stmt-12
1,2,3,4,8,10,11,12,Normal Termination
case-6:If an exception raised at stmt-5 and both inner and outer except
blocks are not matched
1,2,3,4,8,11,Abnormal Termination
Note: If the control entered into try block then compulsory finally block
will be executed. If the control not entered into try block then finally
block won't be executed.
else block will be executed if and only if there are no exceptions inside
try block.
try:
Risky Code
except:
else:
finally:
Eg:
try:
print("try")
print(10/0)--->1
except:
print("except")
else:
print("else")
finally:
print("finally")
try
else
finally
If we are not commenting line-1 then else block won't be executed b'z
there is exception inside try block. In this case output is:
try
MOHAN S.REDDY
except
finally
4. We can write multiple except blocks for the same try,but we cannot
write multiple finally blocks for the same try
Types of Exceptions:
In Python there are 2 types of exceptions are possible.
1. Predefined Exceptions
2. User Definded Exceptions
1. Predefined Exceptions:
x=int("ten")===>ValueError
Eg:
InSufficientFundsException
InvalidInputException
TooYoungException
TooOldException
Syntax:
def __init__(self,arg):
self.msg=arg
EX:
class TooYoungException(Exception):
def __init__(self, arg):
self.msg = arg
raise TooYoungException("message")
EX:
class TooYoungException(Exception):
def __init__(self, arg):
self.msg = arg
class TooOldException(Exception):
def __init__(self, arg):
self.msg = arg
age = int(input("Enter Age:"))
if age > 60:
raise TooYoungException("Plz wait
some more time you will get best
match soon!!!")
elif age < 18:
raise TooOldException(
"Your age already crossed
marriage age...no chance of getting
ma rriage")
else:
print("You will get match details
soon by email!!!")
Note: raise keyword is best suitable for customized exceptions but not for
pre defined exceptions
MOHAN S.REDDY
Regular Expressions:
pattern = re.compile("ab")
MOHAN S.REDDY
matcher = pattern.finditer("abaababa")
EX:
import re
count=0
pattern=re.compile("ab")
matcher=pattern.finditer("abaababa")
for match in matcher:
count+=1
print(match.start(),"...",match.end(),"...",match.g
roup())
print("The number of occurrences: ",count)
Character classes:
1. [abc]===>Either a or b or c
EX:
import re
matcher=re.finditer("x","a7b@k9z")
for match in matcher:
print(match.start(),"......",match.group())
x = [abc]
0 ...... a
2 ...... b
x = [^abc]
1 ...... 7
3 ...... @
4 ...... k
5 ...... 9
6 ...... z
x = [a-z]
0 ...... a
2 ...... b
4 ...... k
6 ...... z
MOHAN S.REDDY
x = [0-9]
1 ...... 7
5 ...... 9
x = [a-zA-Z0-9]
0 ...... a
1 ...... 7
2 ...... b
4 ...... k
5 ...... 9
6 ...... z
x = [^a-zA-Z0-9]
3 ...... @
\s Space character
EX:
MOHAN S.REDDY
import re
matcher=re.finditer("x","a7b@k9z")
for match in matcher:
print(match.start(),"......",match.group())
x = \s
3 ......
x = \S
0 ...... a
1 ...... 7
2 ...... b
4 ...... k
5 ...... @
6 ...... 9
7 ...... z
x = \d
1 ...... 7
6 ...... 9
x = \D
0 .......a
2 ...... b
MOHAN S.REDDY
3 ......
4 ...... k
5 ...... @
7 ...... z
x = \w
0 ...... a
1 ......7
2 ...... b
4 ...... k
6 ...... 9
7 ...... z
x = \W
3 ......
5 ...... @
x=.
0 ...... a
1 ...... 7
2 ...... b
MOHAN S.REDDY
3 ......
4 ...... k
5 ...... @
6 ...... 9
7 ...... z
Qunatifiers:
Ex:
import re
matcher=re.finditer("x","ababaaab")
for match in matcher:
print(match.start(),"......",match.group())
x=a
0 ...... a
MOHAN S.REDDY
2 ...... a
3 ...... a
5 ...... a
6 ...... a
7 ...... a
x = a+
0 ...... a
2 ...... aa
5 ...... aaa
x = a*
0 ...... a
1 ......
2 ...... aa
4 ......
5 ...... aaa
8 ......
9 ......
x = a?
0 ...... a
MOHAN S.REDDY
1 ......
2 ...... a
3 ...... a
4 ......
5 ...... a
6 ...... a
7 ...... a
8 ......
9 ......
x = a{3}
5 ...... aaa
x = a{2,4}
2 ...... aa
5 ...... aaa
Note: ^x--- It will check whether target string starts with x or not
1. match()
MOHAN S.REDDY
2. fullmatch()
3. search()
4.findall()
5.finditer()
6. sub()
7.subn()
8. split()
9. compile()
1. match():
EX:
import re
s=input("Enter pattern to check: ")
m=re.match(s,"abcabdefg")
if m!= None:
print("Match is available at the beginning of the String")
print("Start Index:",m.start(), "and End Index:",m.end())
else:
print("Match is not available at the beginning of the String")
MOHAN S.REDDY
2. fullmatch():
EX:
import re
s=input("Enter pattern to check: ")
m=re.fullmatch(s,"ababab")
if m!= None:
print("Full String Matched")
else:
print("Full String not Matched")
3. search():
We can use search() function to search the given pattern in the target
string. If the match is available then it returns the Match object which
represents first occurrence of the match. If the match is not available then
it returns None
EX:
import re
s=input("Enter pattern to check: ")
m=re.search(s,"abaaaba")
if m!= None:
print("Match is available")
print("First Occurrence of match with start
MOHAN S.REDDY
4. findall():
EX:
import re
l=re.findall("[0-9]","a7b9c5kz")
print(l)
5. finditer():
Ex:
import re
itr=re.finditer("[a-z]","a7b9c5k8z")
for m in itr:
print(m.start(),"...",m.end(),"...",m.group())
6. sub():
re.sub(regex,replacement,targetstring)
MOHAN S.REDDY
In the target string every matched pattern will be replaced with provided
replacement.
EX:
import re
s=re.sub("[a-z]","#","a7b9c5k8z")
print(s)
7. subn():
EX:
import re
t=re.subn("[a-z]","#","a7b9c5k8z")
print(t)
print("The Result String:",t[0])
print("The number of replacements:",t[1])
8. split():
EX:
import re
l = re.split(",", "sunny,bunny,chinny,vinny,pinny")
print(l)
MOHAN S.REDDY
for t in l:
print(t)
EX:
import re
l = re.split("\.", "www.durgasoft.com")
print(l)
for t in l:
print(t)
^ symbol:
We can use ^ symbol to check whether the given target string starts with
our provided pattern or not.
EX:
import re
s="Learning Python is Very Easy"
res=re.search("^Learn",s)
if res != None:
print("Target String starts with Learn")
else:
print("Target String Not starts with Learn")
$ symbol:
MOHAN S.REDDY
We can use $ symbol to check whether the given target string ends with
our provided pattern or not
Eg: res=re.search("Easy$",s)
If the target string ends with Easy then it will return Match
object,otherwise returns None
EX:
import re
s="Learning Python is Very Easy"
res=re.search("Easy$",s)
if res != None:
print("Target String Ends with Easy")
else:
print("Target String Not Ends with Easy")
Rules:
[7-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]
Or
[7-9][0-9]{9}
Or
[7-9]\d{9}
MOHAN S.REDDY
Ex:
import re
n=input("Enter number:")
m=re.fullmatch("[7-9]\d{9}",n)
if m!= None:
print("Valid Mobile Number")
else:
print("Invalid Mobile Number")
Write a Python Program to check whether the given mail id is valid gmail
id or not?
Ex:
import re
s=input("Enter Mail id:")
m=re.fullmatch("\w[a-zA-Z0-9_.]*@gmail[.]com",s)
if m!=None:
print("Valid Mail Id");
else:
print("Invalid Mail id")
EX:
import re
s=input("Enter Vehicle Registration Number:")
m=re.fullmatch("TS[012][0-9][A-Z]{2}\d{4}",s)
if m!=None:
print("Valid Vehicle Registration Number");
else:
print("Invalid Vehicle Registration Number")
MOHAN S.REDDY
Ex:
import re
s=input("Enter Mobile Number:")
m=re.fullmatch("(0|91)?[7-9][0-9]{9}",s)
if m!=None:
print("Valid Mobile Number");
else:
print("Invalid Mobile Number")
Files are very common permanent storage areas to store our data.
Types of Files:
1. Text Files:
Usually we can use text files to store character data eg: abc.txt
2. Binary Files:
Usually we can use binary files to store binary data like images,video files,
audio files etc...
Opening a File:
MOHAN S.REDDY
f = open(filename, mode)
2. 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.
4. 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.
6. a+ →To append and read data from the file.It wont override
existing data.
MOHAN S.REDDY
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:
f.close()
Once we opend a file and we got file object,we can get various details
related to that file by using its properties.
Ex:
MOHAN S.REDDY
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)
We can write character data to the text files by using the following 2
methods.
write(str)
writelines(list of lines)
EX:
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
MOHAN S.REDDY
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")
Ex:
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()
We can read character data from text file by using the following read
methods
The with statement can be used while opening a file.We can use this to
group file operation statements within a block. The advantage of with
statement is it will take care closing of file,after completing all operations
automatically even in the case of exceptions also, and we are not required
to close explicitly.
EX:
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)
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.
Ex:
f = open("abcd.txt", "r")
print(f.tell())
print(f.read(2))
print(f.tell())
print(f.read(3))
print(f.tell())
seek():
f.seek(offset, fromwhere)
offset represents the number of positions
Note: Python 2 supports all 3 values but Python 3 supports only zero.
Ex:
data = "All Students are Good"
f = open("abc.txt", "w")
f.write(data)
with open("abc.txt", "r+") as f:
text = f.read()
print(text)
print("The Current Cursor Position: ",
f.tell())
f.seek(17)
print("The Current Cursor Position: ",
f.tell())
f.write("GEMS!!!")
f.seek(0)
text = f.read()
print("Data After Modification:")
print(text)
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)
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.
MOHAN S.REDDY
f.write(filename)
f = ZipFile("files.zip", 'w',
ZIP_DEFLATED)
f.write("file1.txt")
f.write("file2.txt")
f.write("file3.txt")
f.close()
print("files.zip file created
successfully")
To perform unzip operation:
f = ZipFile("files.zip","r",ZIP_STORED)
names = f.namelist()
logging levels:
logging.basicConfig(filename='log.txt',level=logging.WARNING)
The above line will create a file log.txt and we can store either WARNING
level or higher level messages to that file.
After creating log file, we can write messages to that file by using the
following methods.
logging.debug(message)
logging.info(message)
logging.warning(message)
logging.error(message)
logging.critical(message)
MOHAN S.REDDY
.Write a Python program to create a log file and write WARNING and
higher level messages?
EX:
import logging
logging.basicConfig(filename='log.txt
', level=logging.WARNING)
print("Logging Module Demo")
logging.debug("This is debug
message")
logging.info("This is info message")
logging.warning("This is warning
message")
logging.error("This is error
message")
logging.critical("This is critical
message")
Note: In the above program only WARNING and higher level messages will
be written to log file. If we set level as DEBUG then all messages will be
written to log file.
Ex:
import logging
logging.basicConfig(filename='log.txt
MOHAN S.REDDY
',level=logging.DEBUG)
print("Logging Module Demo")
logging.debug("This is debug
message")
logging.info("This is info message")
logging.warning("This is warning
message")
logging.error("This is error
message")
logging.critical("This is critical
message")
Note: We can format log messages to include date and time, ip address of
the client etc at advanced level.
logging.exception(msg)
Ex:
EX:
import logging
logging.basicConfig(filename='mylog.t
xt',level=logging.INFO)
logging.info("A New request Came:")
try:
MOHAN S.REDDY
x=int(input("Enter First
Number: "))
y=int(input("Enter Second
Number: "))
print(x/y)
except ZeroDivisionError as msg:
print("cannot divide with
zero")
logging.exception(msg)
except ValueError as msg:
print("Enter only int
values")
logging.exception(msg)
logging.info("Request Processing
Completed")
Storage Areas As the Part of our Applications, we required to store our Data like Customers
Information, Billing Information, Calls Information etc..
These are the Memory Areas where Data will be stored temporarily. Eg: Python objects like List,
Tuple, Dictionary.
MOHAN S.REDDY
Once Python program completes its execution then these objects will be destroyed
automatically and data will be lost.
Also known as Persistent Storage Areas. Here we can store Data permanently. Eg: File Systems,
Databases, Data warehouses, Big Data Technologies etc
Databases:
2) Query Language Support is available for every Database and hence we can perform Database
Operations very easily.
3) To access Data present in the Database, compulsory username and pwd must be required.
Hence Data is secured.
4) Inside Database Data will be stored in the form of Tables. While developing Database Table
Schemas, Database Admin follow various Normalization Techniques and can implement various
Constraints like Unique Key Constrains, Primary Key Constraints etc which prevent Data
Duplication. Hence there is no chance of Data Inconsistency Problems.
Limitations of Databases:
1) Database cannot hold very Huge Amount of Information like Terabytes of Data.
2) Database can provide support only for Structured Data (Tabular Data OR Relational Data) and
cannot provide support for Semi Structured Data (like XML Files) and Unstructured Data (like
Video Files, Audio Files, Images etc) To overcome these Problems we should go for more
Advanced Storage Areas like Big Data Technologies, Data warehouses etc.
We can use SQL Language to talk to the database and we can use Python to send those SQL
commands to the database.
Python provides inbuilt support for several databases like Oracle, MySql, SqlServer, GadFly,
sqlite, etc. Python has seperate module for each database. Eg: cx_Oralce module for
communicating with Oracle database pymssql module for communicating with Microsoft Sql
Server
MOHAN S.REDDY
import pyodbc
con=pyodbc.connect("Driver={SQL
Server};server=.;database=ASP")
cur=con.cursor()
cur.execute("select name from emp")
for row in cur:
print(row.name)
cur.close()
con.close()
import pyodbc
try:
con=pyodbc.connect("Driver={SQL
Server};server=.;database=ASP")
cursor=con.cursor()
cursor.execute('create table
py(eno int,ename varchar(10),esal
int)')
print("Table created
successfully")
MOHAN S.REDDY
except pyodbc.DatabaseError as e:
if con:
con.rollback()
print("There is a problem
with sql",e)
finally:
if cursor:
cursor.close()
if con:
con.close()
MOHAN S.REDDY