You are on page 1of 88

Programming Language

& A Programming language is a set of rules that


provides a way of telling a computer what operation
to perform.
& A Programming language is a set of rules for
communicating an algorithm.
Types Of Programming Language
& Machine Language & Assemble Language & High Level
Language
Machine Language
All Computer have an internal machine language which
they execute directly.
This language is coded in binary (0's and 1's)
representation and is very tedious to understand and
to write the program in machine language.
& It consists of string of numbers that instructs
computer to perform operations one at a time.
& Machine language programming is very slow.
Assemble Language
Low-Level Language that allows a programmer to use
abbreviations or easily remembered words instead of
numbers.
G*These Observation are called Mnemonics. These
Mnemonic are Opcode and Operands.
& Programmer can write instructions fast but it is
still not an easy language to learn.
& The language is specific to a particular processor
family and environment. (Machine Dependent
Language).
High Level Language
OA High-Level Language is an English-like language.
OIt allowed users to write in familiar notation,
rather than number or abbreviations.
OMost High-Level language are not machine dependent.
OTranslator for High-Level languages is either a
Compiler or an Interpreter.
What is Python
& Python is a general purpose interpreted interactive
object oriented and high-level programming
language.
& It was first introduced in 1991 by Guido Van
Rossum, a Dutch computer programmer.
& The language places strong emphasis on code
reliability and simplicity so that the programmer
can develop applications rapidly.
& Python is multi-paradigm programming language,
which allows user to code in several different
programming styles.
& Python supports cross platform development and is
available through open source.
& Python is widely used for scripting in Game menu
applications effectively.
Why to Learn Python
& There are large number of high-level
programming languages like C, C++, Java etc. But when
compared to all these languages Python has simplest
Syntax, availability of libraries and built-in
modules.
& Python comes with an extensive collection of third-
party resources that extend the capabilities of the
language.
& Python can be used for large variety of tasks like
Desktop applications, Data base applications,
network programming, game programming and even
mobile development also.
& Python is also a cross platform which means that
the code written for one operating system like
windows, will work equally well with Linux or MacOS
without any changes to the python code.
Features of Python
Easy-to-learn: Python has few keywords, simple
structure, and a clearly defined syntax. This allows
a student to pick up the language quickly.
Easy-to-read: Python code is more clearly defined and
visible to the eyes.
Easy-to-maintain: Python's source code is fairly
easy-to-maintain.
A broad standard library: Python's bulk of the
library is very portable and cross platform
compatible on UNIX, windows, and Mac.
Portable: Python can run on a wide variety of
hardware platform and has the same interface on all
platforms.
Database: Python provides interfaces to all major
commercial databases.
Installing Python
C>Open Browser and type
https://www.python.org/downloads/
C>Select Download option and select
window/MAC/Another platform.
OSelect a Python stable version and click on it and
download.
OAfter completion of download.
OGo to your download location of the folder and Right
click on the python software and select RUN Option
and click.
OClick on install now.
OSelect the installation folder and click next, next
.... Finish.
Python Running Program Modes
l.Interactive Mode
click on it:

& Go to start menu and type IDLE and click on it.


E D © Filters NX

Best match

IDLE (Python 3.6 32-bit) I


App i
Recent

0 Variablel

0 First

Command

CUD idle

Search the web

,0 idle - See web results

Store (2)
>

& IDLE stands for Integrated Development


Environment. When you run IDLE, the window shown in
below figure. Notice the >>> prompt appears in the
IDLE window, indicating that the interpreter is
running in interactive mode. You can type Python
statement at this prompt and see them executed in the
IDLE window.
Pyth on 3,6.4 Shell — □ ^
File Edit Shell Debug Options Window Help
Python 3.S.4 (v3.6.4:d48eceb, Dec 19 2017, 06:04:45) [MSC v.1900 32 bit (Intel)] * on Win32
Type "copyright", "credits" or "license()" for more information.
»> | ' ■ '
2.Script Mode
& A Python script can be executed at the command line
by invoking the interpreter on your application, as
show in the following.
i^Open Notepad.
& Type the following Program.
print ('Welcome to Python.')
& And save as any name like Example.py(the extension
.py stands for python program)
*>And select any location and save it.
& After saving the program.
& Open CMD in the location we your program has been
saved.
& And run the python file by using following command
and as shown in figure.
C:\Users\vasu>cd desktop
C:\Users\vasu\Desktop>python Example.py Welcome
to Python.
C:\Users\vasu\Desktop>
Comments
OComments are notes of explanation that document
lines or sections of a program.
Comments are part of the program, but the python
interpreter ignores them.
They are intended for people who may be reading the
source code.
& The Pound (#) symbol or character indicates that
the comments in python.
#My First Python Program.|
print("Welcome to Scripting Language.") print("End
of the Program.")
#File is Ended.
Keywords in Python
& Keywords are words that are reserved they cannot be
used as variable names.
& The instruction is already given to python
interpreter.
^In python we can print all the keyword.
& Python keywords version to version may or may not
be change.
>>> import keyword
>>> keyword.kwlist
['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class' 'continue ' , '
def', 'del', 'elif', 'else', 'except', 'finally', 'fox', ' f r 'global', 'if',
om',
'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass ' 'raise', 'retu
,
rn', 'try', 'while', 'with', 'yield']
»> |
Identifiers
& An identifier is a unique name that enables you to
identify something.
& Identifiers are used to label variables, functions,
classes, objects and modules.
& They begin with either a letter or an underscore and
they can contain letters underscore or digits.
& They cannot contain punctuation marks.
Variable
& A variable is a name that refers to a value.
Syntax
<variable_name> = value
Type Conversion in Python
Sometimes, you may need to perform conversions between
the built-in types.
& To convert between types, you simply use the type-name
as a function.
& There are several built-in functions to perform
conversion from one data type to another.
Function Description
int(x [,base]) Converts x to an integer.

float(x) Converts x to a floating-


point number.
complex(real [,imag]) Creates a complex number.

str(x) Converts object x to a


string representation.
tuple(s) Converts s to a tuple.
list(s) Converts s to a list.
set(s) Converts s to a set.
dict(d) Creates a dictionary. d
must be a sequence of
(key,value) tuples.
Operators in Python
& An operator performs a task on one or two operands.
1. Arithmetic Operators
Operator Name
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
** Exponentiation
// Floor Division
2.Relational Operators
Operator Names
== Equal equals to
< Less than
< = Less than equals to
> Greater than
>= Greater than equals to
! = Not equals to

3.Logical Operators
Operator Description
and (Logical AND) Both operands are true it
is True. Otherwise False.

or (Logical OR) One operand is true it is


True. Otherwise False.
not (Logical NOT) If the result is True it
returns False. If False
it returns True.

4.Bitwise Operators
Operator Name
& Bitwise and
Bitwise or
A Bitwise exclusive or
Bitwise Complement
<< Bitwise Left-Shift
>> Bitwise Right-shift
5.Membership Operators
Operator Description
in It returns True if it
finds a variable in the
specified sequence.
Otherwise False
not in It returns True if it
does not find a variable
in the specified
sequence. Other False.

6.Identity Operators
Operator Description
is It returns True if the
two variables points to
the same memory location.
Otherwise False.
is not It returns False if the
two-variable point to the
same memory location.
Otherwise True.

7.Assignment Operators
Operator Description
= (Assignment Operator) Right side value will be
stored into left side
variable/object.
+= (Addition Assignment Adds right operand to
Operator) the left operand and
stores the result into
left operand.
-= (Subtraction Subtract right operand
Assignment Operator) to the left operand and
stores the result into
left operand.
*= (Multiplication Multiplies right operand
Assignment Operator) to the left operand and
stores the result into
left operand.

/= (Division Assignment Division left operand


Operator) with the right operand
and stores the result
into left operand.
%= (Modulus Assignment Division left operand to
Operator) the right operand and
stores the result into
left operand.
**== (Exponential Performs power value and
Assignment Operator) then stores the result
into left operands.

//= (Floor Division Performs floor division


Assignment) and then stores the
result into left
operands.
Control Flow Statements
l. Decision or Conditional Statement if
syntax:
if (condition/Boolean_Expression): statement-1
statement-2
& When the condition or Boolean_Expression is True it
will execute the statement and when False it will not
execute the statement.
Ex
name = input(’Enter Your Name:’)
if name==’Vasu’:
print(’Good Moring:',name) print(’Good Night:',name)
print(’End of Program..!!’) Output
12 | Page
D:\notes\Python\materi al>python Exanple.py
Enter Your Name:Vasu
Good Moring: Vasu
Good Night: Vasu
End of Program..!!
print ()
& Print Function, which displays output on the screen.
input function (built-in)
& Input function is used to read input form the
keyword.
if-else
syntax
if(condition/Boolean_Expression):
statement-1
statement-2
else:
statement-1
statement-2
& When the condition or Boolean_Expression is True it
execute the statement inside if block. If the
condition is False it executes the statement inside
else block.
Ex
2. n1 = int(input(’Enter First
Number:’))
3. n2 = int(input(’Enter Second
Number:’))
4.
5.if n1>n2:
6. print(n1,’is Big.’)
7. else:
8. print(n2,’is Big.’) output:
D:\notes\Python\materia"l>python Exanple. py
Enter First Number:15 Enter Second Number:2 15 is
Big.
D:\notes\Python\materia"l>python Exanple. py
Enter First Number:56 Enter Second Number:322 322
is Big.
if-elif-else
syntax:
if condition: statement-1 statement-2 elif
condition: statement-1 statement-2 elif condition:
14 | Page SS TECHNOLOGIES Pvt Ltd.
Software Training & Development. www.sstechnologis.com

statement-1
statement-2
else:
statement-1
statement-2
Ex
1. n = input(’Is the Window is Open:’)
2.
3.if n == ’yes’:
4. print(’The Room is Cool.’)
5.
5. elif n == ’no’:
6. print(’The Room is Warm.’)
8.
7. else:
8. print(’The Romm is Cool and Warm.’)
Output:
D:\notes\Python\materi al>python Exanple.py Is
the Window is Open:no The Room is Warm.
D:\notes\Python\materi al>python Exanple.py Is
the Window is Open:yes The Room i s Cool.
D:\notes\Python\materi al>python Exanple.py Is
the Window is Open:middle The Romm is Cool and
Warm.
D:\notes\Python\materi al>
Note:
[Seise block is always optional.
[! Switch statement is not there in python.
Looping or Iterative Statement
& Loops are used to execute a group of statement for
multiple times.
& Until the condition becomes false the loop stops
and control jumps out of the loop.
While
& While loops are known as indefinite or conditional
loops.
& It iterates until certain condition is met.
& There is no guarantee that how many times the loop
will be iterates.
Syntax:
Initialization While condition:
Statement-1
Statement-2
Increment / Decrement
Note:
& Initialization and Increment / Decrement statement
are optional.
Ex:
1.i = 1
2. while i<10:
3. print(’i=’,i)
4.1 = i + 1
output:
D:\notes\Python\material>python Exanple.py i= 1 i=
2 i = 3 i = 4 i= 5 i= 6 i= 7 i = 8 i= 9
Ex
1.# Write a Python program sum of ’n’ natural
number
2. n = int(input(’Enter a number:’))
3. sum = 0
4. i = 1
5. while i<=n:
6. sum +=i
7.1 = i + 1
8.
9. print(’Sum of Natural Number is
:’,sum)
output:
D:\notes\Python\material>python Exanple.py
Enter a number:10
Sum of Natural Number is : 55
D:\notes\Python\material>python Exanple.py
Enter a number:5
Sum of Natural Number is : 15
For
Ofor loop repeats a group of statements a specified
number of times.
Syntax:
for <variable_name> in sequence: statement-1
statement-2
Note
il where sequence can be string/list/tuple .. etc.
Ex:
1. for x in "PYTHON":
2. print(x)
output:
D:\notes\Python\materi al>python Exanpl e.py P
Ex:
1.list1 = [1,2,3,4]
2. for x in list1:
3. print(x)
output:
D:\notes\Python\mate ri al>python Exanple.py 1
4
range () function
& range () function is used to generate sequence of
numbers.
& It is a built-in function available in python.
Syntax:
range (Start, Stop, Step) start:
& It represents the starting point of the list.
& It is optional argument and the default value for
this argument is 0.
Stop:
& It is the end point of the sequence generated.
& It is the only required argument in the function.
& It does not have any default value.
Step:
& This is the 3rd and the last argument in the
function.
& Just like start it is also the optional argument
and its default value is 1.
& Though the user can change this value according to
its requirements.
Note:
IS Since python is 0 indexed.
[I So, by default every list generated by range
function will start from 0 and will end at stop-
1. i.e. 1 less than the value for stop argument.
Hi Though it will include the starting point in the
list.
Ex
1. for x in range(10):
2. print(x)
output:
D:\notes\Python\materi al>python Exanple.py 0
9 Ex
1. # Write a Python Program to print 20 even
2. numbers using range() function
3.
3. for x in range(2,22,2):
4. print(x)
output:
C:\Users\vasu\Desktop>python Demo.py 2
10 12 14 16 18 20
Note:
Hi The 3rd argument (step argument) in range()
function can never be 0.
Hi If it is 0, then it will raise a ValueError
exception.
Nested Loops
for <variable> in <range>: #outer loop [do something]
# Optional for <variable> in <range>:# Nested loop
[do something]
Ex
1. for x in range(1,3):
2. for y in range(1,3):
i. print('x:',x,,and y:’,y)
3. print( ----- ’ ’)
output:
C:\Users\vasu\Desktop>python Demo.py x: 1
and y: 1 x: 1 and y: 2
x: 2 and y: 1 x: 2 and y: 2
Ex:
1. for x in range(1,4):
2. for y in range(1,4):
i. print(’ * ’,end=’’)
3. print()
output:
C:\Users\vasu\Desktop>python Demo.py
A A A

'fc 'A 'A


« « rt
Transfer or Jumping statements: break:
& break is keyword.
& You can use break keyword in if-else, while and for
loops.
& It is used to terminate the loop based on the
condition.
Ex:
1. for x in range(10):
2. print(x)
3. if x==5:
4. break;
Output:
C:\Users\vasu\Desktop>python Demo.py 0
Continue:
^continue is a keyword.
& We can use continue statement to skip current
iteration and continue next iteration.
Ex:
2. for x in range(10):
3. print(x)
4.if x==5:
5.continue;
output:
C:\Users\vasu\Desktop>python Demo.py 0
pass:
i^pass is a keyword.
i^Pass is used to execute nothing.
& Pass means nothing (NONE).
Syntax:
pass
Ex:
1. for x in range(10):
2. print(x)
3.if x==5:
4. print('pass executed.’)
5. pass
output:
C:\Users\vasu\Desktop>python Demo.py 0 5
pass executed.
String
& String is sequence of character.
Ex:
1. str1 = 'PYTHON'
2. print(str1)
output:
C:\Users\vasu\Desktop>python Demo.py
PYTHON
Accessing string by using index:
Ex
1. str1 = ’PYTHON’
2. print(str1[0])
3. print(str1[1])
4. print(str1[2])
Output:
C:\Users\vasu\Desktop>python Demo.py P
Accessing String using for loop
1. str1 = ’PYTHON’
2. for x in str1:
3. print(x)
output:
C:\Users\vasu\Desktop>python Demo.py P
Accessing String using slicing operator Syntax:
Str [beginindex:endindex:step]
1.str1 = "Be yourself; everyone else is already
taken"
2.print(str1[::])
3.print(str1[:])
4.print(str1[0::2])
5.print(str1[::-1])
6.print(str1[:10:])
output:
C:\Users\vasu\Desktop>python Demo.py Be yourself;
everyone else is already taken Be yourself;
everyone else is already taken B oref vroees
saraytkn
nekat ydaerla si esle enoyreve ;flesruoy eB Be
yoursel
String methods in python
Capitalized:
Return a copy of the string with only its first
character capitalized.
Ex
1.str1 = "be yourself; everyone else is already
taken"
2. str2 = str1.capitalize()
3. print(str2)
output:
C:\Users\vasu\Desktop>python Demo.py Be yourself;
everyone else is already taken
Count:
Syntax:
Count(sub[,start[,end]])
G^ Return the number of occurrences of substring sub
in string S[start:end].
& Optional arguments start and end ae interpreted as
in slice notation.
Ex:
1.str1 = "be yourself; everyone else is already
taken"
2.
2. str2 = str1.count(’e’)
3. print(str2) #9
len()
G^ Return the length of the given string.
Ex:
1.str1 = "be yourself; everyone else is already
taken"
2.
2. str2 = len(str1)
3. print(str2) #43
endswithO
syntax:
endswith(suffix[,start[,end]]
O Return True if the string ends with the specified
suffix, otherwise return False, with optional
start, test beginning at that position.
OWith optional end, stop comparing at that position.
Ex:
1.str1 = "Be yourself; everyone else is already
taken"
2.
2. str2 = str1.endswith('n')
3. print(str2) #True
5.
4. print(str1.endswith
('e',0,9)) #True title()
G* Return a title cased version of the string: words
start with uppercase characters, all remaining
cased characters are lowercase.
Ex
1.str1 = "Be yourself; everyone else is already
taken"
2.
2. str2 = str1.title()
3. print(str2) #True
upper():
O Return a copy of the string converted to uppercase.
Ex:
1.str1 = "Be yourself; everyone else is already
taken"
2.
2. str2 = str1.upper()
3. print(str2) #True
split():
syntax:
split([sep[,maxsplit]])
G* Return a list of the words in the string, using
sep as the delimiter string.
& If maxsplit is given, at most maxsplit splits are
done. (thus, the list will have at most maxsplit+1
elements).
& If maxsplit is not specified, then there is no
limit on the number of splits (all possible splits
are made).
Ex:
1.str1 = "Be yourself; everyone else is already
taken"
2.
2. str2 = str1.split()
3. for x in str2:
4. print(x)
output:
C:\Users\vasu\Desktop>python Demo.py Be
yourself; everyone el se
is
already taken
List in python
& A list is an ordered sequence of values.
& It is a data structure in Python.
& The values inside the lists can be of any
type(like integer, float, strings, lists, tuple,
dictionaries etc) and are called as elements or
items.
& The elements of list are enclosed within square
brackets ([]).
Creating a list:
Ex
1. shopping_list = ['Milk',
'Bread',
'Cheese','Bow and Arrow']
2. print(shopping_list)
Access a list using index Ex:
1. shopping_list = ['Milk', 'Bread',
'Cheese','Bow and Arrow']
2. print(shopping_list[2])
Access a list using for loop:
Ex
1.list1 = [’Milk’, ’Bread’, ’Cheese’,’Bow and Arrow’]
2.
3. for x in list1:
4. print(x)
Access a list using slice operator:
Ex

1.list1 = [’Milk’, ’Bread’, ’Cheese’, ’Bow and


Arrow’]
2.
3.print(list1[:])
4.print(list1[::2])
5.print(list1[2::])
list function
len()
syntax:
len(list)
& This function gives the length of the list.
Ex
1.list1 = [’Milk’, ’Bread’, ’Cheese’,’Bow and Arrow’]
2.
3.print(len(list1))
maxO:
syntax:
max(list)
& This function returns the maximum element value
from the list.
Ex:
1.list1 = [10,20,30,40,50,5]
2.print(max(list1))
minO
syntax:
min(list)
& This function returns the minimum value from the
list.
Ex:
1.list1 = [10,20,30,40,50,5]
2.
3. print(min(list1)) #5 python
list methods append():
syntax:
list.append(x)
& This method is used to add a new element at the end
of a list.
Ex:
1.list1 = [10,20,30,40,50,5]
2.
3.print(list1)
4.
5.list1.append(’Abc’)
6.
7.print(list1)
extends():
syntax:
list.extend(x)
& This method is used to add one or more element at
the end of a list.
Ex
1.list1 = [10,20,30,40,50,5]
2.
3.print(list1)
4.
5.list2 = [’abc’,45,123]
6.print(list2)
7.
8.list1.extend(list2)
9.
9. print(list1) output:
C:\Users\vasu\Desktop>python Demo.py [10,
20, 30, 40, 50, 5]
['abc *, 45, 123]
[10, 20, 30, 40, 50, 5, 'abc', 45, 123]
CountO:
Syntax:
list.count(x)
& This method is used to find the occurrence of the
given element in the list.
Ex
1.list1 = [1,2,1,3,4,1]
2.
3.print(list1.count(1))#3
insert()
Syntax:
list.insert(index,element)
& This method is used to insert an element at a given
position.
Ex:
1.list1 = ['A','B','C','D','E','F']
2.
3.list1.insert(0,'V')
4.print(list1)
remove()
Syntax:
list.remove(x)
& Remove the first item from the list.
Ex:
1.list1 = ['A','B','C','D','E','F']
35 | P a g e SS TECHNOLOGIES Pvt Ltd.
Software Training & Development. www.sstechnologis.com
2.
3.list1.remove('B')
4.print(list1)
pop():
Syntax:
list.pop()
& It removes and returns the last element.
Ex:
1.list1 = [,A',,B','C',,D',,E','F']
2.
3.list1.pop()
4.print(list1)
sort()
Syntax:
list.sort()
& Sort the elements of the list.
Ex:
1.list1 = ['V','A','B','C','D','E','F']
2.
3.list1.sort()
4.print(list1)
reverse():
Syntax:
list.reverse()
& Reverse the elements of the list.
Ex:
1.list1 = ['A','B','C','D','E','F']
2.
3.list1.reverse()
4.print(list1)
Tuples in Python
& A tuple is a sequence of items, similar to
lists.
& The values stored in the tuple can be of any
type and they are indexed using integers.
Creating a tuple:
& It is created as a comma separated list of
elements.
Ex
1. tuple1 = (1,2,3,4,5,6)
2. print(tuple1)
Access tuple using index:
Ex
1. tuple1 = (1,2,3,4,5,6)
2. print(tuple1[5]) #6
Access tuple using for loop:
Ex:
1. tuple1 = (1,2,3,4,5,6)
2.
2. for x in tuple1:
3. print(x)
Access Tuple using slice operator:
Ex:
1. tuple1 = (1,2,3,4,5,6)
2. print(tuple1[2:5])
3. print(tuple1[::-1])
C :\l)sers\vasu\Desktop>python Demo. py
Deleting elements in a tuple
& By using del keyword, you can delete all elements in
the tuple.
Ex:
1. tuple1 = ('Hyd','Bang','Guj','Del')
2. print(tuple1)
3.
3. del tuple1
4. #print(tuple1) Error
Tuple Methods:
& There is some built-in function for tuple. len():
Syntax:
len(tuple)
& This function returns the length of the tuple. Ex:
1. tuple1 = ("Python'Y'HTMLV'DJANGO")
2. print(tuple1)
3.
4.print('Length:',len(tuple1)) maxO:
Syntax:
max(tuple)
& It returns the maximum value in the tuple. Ex:
1. tuple1 = ("Python'Y'HTMLV'DJANGO")
2. print(tuple1)
3.
3.print('Maximum:',max(tuple1)) min():
Syntax:
min(tuple)
& It returns the minimum value in the tuple. Ex:
1. tuple1 = ("Python","HTML","DJANGO")
2. print(tuple1)
3.
3. print('Minimum:',min(tuple1))
Operations of Tuples
Addition and Multiplication in tuple
Ex:
1. tuple1 = (100,200,300)
2. tuple2 = (400,500,600)
3.
3. print(tuple1+tuple2)
4. print(tuple1*3)
in Operator in python
1. tuple1 =
('Python','PHP','Django','JAVA')
2.
2. print('python' in tuple1)
3. print('JAVA' in tuple1)
Ex:
1. tuple1 =
('Python','PHP','Django','JAVA')
2.
3.lang = input('Enter any language name:')
4.
5.if lang in tuple1:
print('Yes, you can use:',lang)
5. else:
print("You can't use :",lang)
Set in Python
& A set is any collection of distinct items, and its
members are often referred to as set elements.
& Python captures this essence in its set type
objects.
& A set object is an unordered collection of hash
table values.
Create and Assign Set Types
Ex
1. set1 = set('Technologies')
2. print(set1)
Changing a Set in Python
& Set are mutable. But since they are unordered,
indexing have no meaning.
We cannot access or change an element of set using
indexing.
Set does not support it.
Ex
1. set1 = {1,2}
2. print(set1[0])
output:
r■ - — — v —— i- — j *

TypeError: 'set' object does not support indexing


& We can add single element in set by using add()
method.
Ex
1. set1 = {1,2}
2. print(set1)
3.
3. set1.add(3)
4. print(set1)
Removing Element from a Set
& We can remove element from a set by using discard()
and remove() methods.
Ex
1. set1 = {1,2,3,4,5,6}
2.
2. set1.discard(4)
3. print(set1)
41 | P a g e
5.
4.set1.remove(5)
5.print(set1)
set methods in python Union:
& This method is used to find out all the unique
elements in two sets.
Ex
1.Set1 = {1,2,3}
2.Set2 = {4,5,6,1,2}
3.
3.print(Set1.union(Set2))
output:
{1, 2, 3, 4, 5, 6}
intersection^:
& This method return common element from two sets.
Ex
1.Set1 = {1,2,3}
2.Set2 = {4,5,6,1,2}
3.
3.print(Set1.intersection(Set2))
Output: {1, 2}
difference^)
& It return elements that are only in A but not in B
sets.
Ex
1.Set1 = {1,2,3}
2.Set2 = {4,5,6,1,2}
3.
2.print(Set1.difference(Set2)) output:
{3}
Symmetric difference()
& It returns elements in Both sets except those
common.
Ex
1.Set1 = {1,2,3}
2.Set2 = {4,5,6,1,2}
3.
3.print(Set1.symmetric_difference(Set2)) output:
Python Dictionary
& A python dictionary is written as a sequence of
key/value on item pains separated by commas.
& These pairs are sometimes called entries.
Ex:
o port = {22: "SSH", 23: "Telnet", 53: "DNS", 80:
"HTTP"} o Dict1 = {"AP": "Access Point", "IP":
"Internet Protocol"}
Syntax:
Dictionary_name = {key: value}
& The key and value pair are called item, key and
value is separated by colon (:).
& Each item is separated by comma (,), whole thing is
enclosed in curly braces ({}).
& An empty Python dictionary can be created by just
two curly braces {}.
Accessing the values in dictionary
Ex:
1. port =
{22:"SSH",23:"Telnet",53:"DNS",80:"HTTP"}
2. print(port)
3.
3. print(port[22])
4. print(port[53])
Deleting an element in dictionary Syntax:
del dict[key]
& You can delete single element of dictionary as well
entire dictionary.
Ex:
1. port =
{22:"SSH",23:"Telnet",53:"DNS",80:"HTTP"}
2. print(port)
3.
3. del port[22]# deleting of element
5.
4. print(port)
7.
5. del port # deleting of dictionary
Updating dictionary
Syntax:
Dict[key] = new_value
*>You can update the value of dictionary.
& Just specify its key in square bracket, just
reassign the value to old key.
Ex:
1. port =
{22:"POP",23:"SMTP",53:"DNS",80:"HTTP"}
2. print(port)
3.
3. port[23] = "TCP"
5.
4. print(port)
Adding item in dictionary Syntax:
dict[new_key] = value
Ex
1. port =
{22:"POP",23:"SMTP",53:"DNS",80:"HTTP"}
2. print(port)
3.
3. port[90] = "TCP"
5.
4. print(port)
Dictionary Functions lenO:
syntax:
len(dict)
Ex:
1. subj =
{1:"Telugu",2:"Hindi",3:"English",4:"Maths"}
2. print(subj)
3.print("Length:",len(subj)) str()
syntax:
str(dict)
& The function str() converts a dictionary into a
string.
Ex:
1. subj =
{1:"Telugu",2:"Hindi",3:"English",4:"Maths"}
2. print(subj)
3.
3. print(str(subj))
copy(): syntax:
dict.copy()
& If you want to make a copy dictionary use copy()
method.
Ex:
1. subj =
{1:"Telugu",2:"Hindi",3:"English",4:"Maths"}
2. print(subj)
3.
3. csubj = subj.copy()
4. print(csubj)
get():
syntax:
dict.get(key,default=None)
& Used to get the value of given key.
Ex:
1. subj =
{1:"Telugu",2:"Hindi",3:"English",4:"Maths"}
2. print(subj)
3.
3. print(subj.get(3))
itemsO:
syntax:
dict.items()
& returns the list of dictionary (key, value) tuple
pairs.
Ex:
1. subj =
{1:"Telugu",2:"Hindi",3:"English",4:"Maths"}
2. print(subj)
3.
3.print(subj.items()) keys():
syntax:
dict.keys()
& returns all keys.
Ex:
1. subj =
{1:"Telugu",2:"Hindi",3:"English",4:"Maths"}
2. print(subj)
3.
3. print(subj.keys())
value():
syntax:
dict.value()
& return all values of dictionary.
Ex:
1. subj =
{1:"Telugu",2:"Hindi",3:"English",4:"Maths"}
2. print(subj)
3. print(subj.values())
Functions
& A function in python can perform a particular task,
and support the concept of modular programming
design techniques.
& When your program is too complicated, the function
declaration is divided into smaller steps or logic
to simplify the complexity of program.
& For this reason, the functions are implemented.
What is a function
& A function is a named sequence of statements that
performs a computation.
When you define a function, you specify the name and
the sequence of statements which can be called many
times.
Why Functions
(S Reduces duplication of code.
[! Breaking up of complex problems into simpler
pieces.
(S Improved clarity of the code.
il Hiding information.
DEFINING FUNCTION Syntax:
def <function_name> ([parameters list]): -statement's
-[return <value's>]
Where,
def is a keyword.
function_name must be a user-defined name or an
identifier or variable name.
parameters are optional.
return is a keyword and it is optional.
Ex: function without parameters:
1. # user-define function
2. def fun1():
print(’User-define function called.’) print(’Python
by Vasu.’)
3.
3. # calling a function
4. fun1()
5. fun1()
Output:

User-define function called. User-


define function called.
Ex: function with parameter
1. # user-define function
2. def fun1(name):
3. print('Hi',name)
4. print('Hello',name)
5.
5. # calling a function
6. fun1(’Rama’)
7. fun1('Vasu')
output:
Hi Rama Hel1o Rama Hi Vasu Hello Vasu
Example: write a program to demonstrate simple
function declaration to find the sum of two numbers.
Ex:
1.# A simple function call to find sum of two
numbers.
2. # Declares the function body.
3.
3. def sumNum():
4. a = int(input("Enter First Number:"))
5. b = int(input("Enter Second Number:"))
6. sumT = a + b;
7. print("Sum of %d and %d is %d"%(a,b,sumT))
9.
8. sumNum()
Function Returning values:
& The return keyword is used to return values from a
function.
Ex:
1. def cube(x):# Function with return
2. return x * x * x
3.
3. x = cube(3)
4. print(’The Cube of 3 is:’,x)
Returning more than one value
& We can return more than one value from a function.
& The objects, after the return keyword, are
separated by commas.
Ex:
1.# Program to returing more than one value.
2.
3. def ReturnMore():
4. # Five subject marks for a student
5. Marks = [98, 67, 87, 89, 87]
6. # Individual marks transferred into
7. # independent variable
8. M1 = Marks[0]
9. M2 = Marks[1]
10. M3 = Marks[2]
11. M4 = Marks[3]
12. M5 = Marks[4]
13. # Total marks
14. MarkSum = M1 + M2 + M3 + M4 + M5
15. # Percentage
16. MarkPer = float(MarkSum/5)
17. # Returning more than one value from a
18. function
19. return MarkSum,MarkPer
20.
20. Total, Percentage = ReturnMore()
21. print("Total marks is = %d and percentage
22. is = %.2f"%(Total,Percentage))
Function with argument
© Required Argument © Keyword Argument © Default
Argument © Variable-length Argument
Required Argument
Required argument are those argument that are passed
to a function in correct positional order.
Ex: Write a program to find the area and perimeter of
a rectangle using function required arguments.
1.# Program to find area and perimeter of a
rectangle
2.
2. def rectangle(length, breadth):
3.area = length * breadth # Area of rectangle
4.perimeter = 2 * (length + breadth) #
Perimeter of rectangle
5.print(’Area is:’,area)
6.print(’Perimeter is:’,perimeter)
8.
7.def main():
8.l = int(input(’Enter length of rectangle:’))
9.b = int(input(’Enter breadth of rectangle:’))
10. rectangle(l,b)
13.
11. main()
Note:
Hi Here the number of arguments in the function call
should match exactly with the function definition.
S If the arguments are not match.
H It raises an error.
Keyword Arguments
If you have some functions with many parameters and
you want to specify only some of them, then you can
give values for such parameters by naming them-this
is called keyword argument.
Ex:
1.# Printing persons information
2.
3.def display(name, age, sex):
4.print(’Name is:’,name)
5.print(’Age is:’,age)
6.print('Sex is:',sex)
7.
7.def main():
8.display('AAA',23,'M')
9.display('BBB',25,'F')
10. #OR
11. display(name='CCC',sex='M',age=24)
12. main()
Note:
[! Keyword argument are especially useful when you
want to call a function with a long parameter list
where most of the parameters have default values
and you only wish to change few of them.
Default/Optional Argument Values
G* For some functions, you may want to make some
parameters optional and use default values in case
the user does not want to provide values for them.
& This is done with the help of default argument
values.
Ex:
1.# Program to find sum of two numbers with default
2.# argument
3.
3.def default_sum(x,y=90):
4.sum = x + y
5.print('The Sum of
',x,'and',y,'is',sum)
7.
def main():
8.
9.
10.
default_sum(100,230) default_sum(340) # In this
function
call, default parameter used
11.
12.
default_sum(120,320) default_sum(-99) # In this
function
call, default parameter used
13. main()
Note:
H The default argument values are called implicit
values.
H An implicit value is used if not value is
provided.
H Also, the default argument value should be a
constant.
H More precisely, the default argument value should
be immutable.
Variable-length Arguments
& You may need to process a function for more
argument than you specified while defining the
function.
These arguments are called variable-length argument.
Syntax:
def <function_name> ([formal_args,..]
*var_args_tuple):
-statement's
Where,
-1- The first argument passed to the function will
be assigned into format argument.
-1- The second argument holds an asterisk (*) which
is placed before the variable name that will hold
the values of all non-keyword variable argument.
Ex:
1.# Program to demonstrate variable-length
argument
2.
2. def var_len(arg1, *arg2):
3. print(arg1, arg2)
5.
4. var_len(10)
5. var_len(10,20)
6. var_len(10,20,30)
7. var_len(10,20,40)
Lambdas
& An interesting way of making functions is through
anonymous functions, also known as lambda
expressions.
& Lambdas create a function that is essentially
processed in-line, rather than giving it a name to
be called later (hence, the anonymous part).
Ex:
1. def fun(a, b, c): # Regular Function
2. print(a+b+c)
3.
3. fun(10,20,30)
5.
6.
lam_fun = lambda a, b, c : a + b + c #
lambda
#
7.
function
8.
9.
print(lam_fun(100,200,300))
Variable Scope
& The use of functions introduces the concept of
scope.
& Scope is where in the code a variable is "alive"
and can be accessed.
& Variable in a program may not be accessible at all
the locations in that program.
Global Variable
G^ A variable defined outside a function body has a
global scope.
Local Variable
G^ A variable defined inside a function body has a
local scope.
Ex
1.
2.
3.
4.
5.
6.
7.
8.
x = 123 # Gobal Variable
def fun():
a = 456 # Local Variable print(’a:’,a) print(’x:’,x)
fun()
Files
& Python provides built-in methods to create and
modify files.
& File-related python operations are useful in large
number of programming exercises.
& These methods are provided by standard Python
modules and do not require installation of
additional packages.
open () method
& The open() method is a default method that is
available in Python and it is one of the most
widely used functions to manipulate files.
Ex:
f = open('test.txt', 'w')
& This command will create a test.txt file in the
same folder in which you started the python
interpreter or location from where the code is
being executed.
Mode Description
W This opens or create a
file for writing only.
W+ This opens or creates a
file for writing and
reading.
R This opens a file for
reading only.
R+ This open a file for
reading and writing.
A This opens a file for
appending.
A+ This open a file for
appending and readiing.
write() method

& Once the file is open in one of the writing or


appending modes, you can start writing to the file
object using this method.
Ex:
f.write('Hello World.' )
& You can also use the writelines() method if you
want to write a sequence of strings to the file.
closeO method
& The close() method closes the file and free system
resources that are occupied by the file.
Ex:
f.close()
read() method
& This read() method reads the content of an opened
file from the beginning to the end.
Ex:
f = open('text.txt','r') f.read()
Examples
Ex: Creating and writing into a file
1. f = open(’test.txt’,mode=’x’)
2. f.write(’Welcome to File.’)
3. f.write(’Inside vasu class.’)
Ex: Reading a file
1. with open(’test.txt’,mode=’r’) as f:
2. r = f.read()
3. print(r)
Ex: Reading a file using iterator
1. with open(’test.txt’,mode=’r’) as f:
2. r = f.read()
3. for row in r:
4. print(row)
Ex: Writing into a file using writelines () method
1. with open(’test.txt’,mode=’a’) as f:
2. f.writelines(’hi\nBye’)
Exception Handling in Python
& An exception is an object that indicates an error
or anomalous condition.
& When python detects an error, it raises an
exception, that is, python signals the occurrence
of an anomalous condition by passing an exception
object to the exception-propagation mechanism.
Ex:
1. a = int(input(’Enter First Number:’))
2. b = int(input(’Enter Second Number:’))
3.
3. print(a//b)
5.print(’END’)
C>In the above program if you enter a and b value
like a = 10 and b = 2. The result will be 5.
G^ Suppose if you enter a = 10 and b = 0 then you
program occurs an exception.
OIt is nothing but an abnormal termination of a
program.
C>We can handle the exception by using following.
Using try and except Try:
& try is keyword.
& Inside try logical code you need to write.
& Nothing but a business logical code.
Except:
^except is a keyword.
& It caught the error throw by the try block.
Syntax: try:
G^ Business logical code. except <exceptionname>:
G^ Handling errors
Ex:
1.try:
2. a = int(input(’Enter First Number:’))
3. b = int(input(’Enter Second Number:’))
4.
4. print(a//b)
5. print(’END’)
7.
6. except ZeroDivisionError:
7. print("You are dividing by zero,")
try with multiple except syntax:
try:
Ostatement's except <name>:
OStatement's except <name>:
& Statement's except:
& Statement's
Ex
1. try:
2. a= int(input(’Enter First Number:’))
4.
5.
6.
7.
8.
9.
4. 11. 12.
3. b= int(input(’Enter Second Number:’))
print(a//b)
print(’END’)
except ZeroDivisionError:
print("You are dividing by zero,")
except :
print(’Error’)
Finally clauses
finally is keyword.
& This block executes if exception occurs or not.
Syntax:
try:
OStatement's except:
OStatemnt's finally:
OStatement's
Ex:
1. try:
2. print(10//2)
3. except :
4. print(’Error’)
5. finally:
6. print(’Always executed.’)
output
5 Always executed.
_ I _
Ex
1. try:
2. print(10//0)
3. except :
4. print(’Error’)
5. finally:
6. print(’Always executed.’)
Output:
Always executed.
try with finally: syntax:
try:
G^ Statement's Finally:
G^ Statement's
Ex:
1. try:
2. print(’Try..’)
3. finally:
4. print(’Always executed.’) output:
Try. _ Always executed.
Python types of Exception:
IndexError:
& When you are trying to access an item at an invalid
index.
Ex:
1. >>> listl = [’rama’,’krishna’,’vasu’]
2. >>> list1[3]
Output:
IndexError: list index out of range KeyError:
& When a key is not found.
Ex:
1. dictl =
{1:’vasu’,2:’technologies’,3:’python’}
2. dict1[4]
output:
KeyError: '4'
TypeError:
& When a function's argument is of an inappropriate
type.
Ex:
a = int(input(’Enter a Value:’)) output:
Enter a value: abc
ValueError: invalid literal for int() with base 10:
'abc'
NameError
& When an object/variable could not find.
Ex:
print(a)
66 | Page SS TECHNOLOGIES Pvt Ltd.
Software Training & Development. www.sstechnologis.com

output:
NameError: name 'a' is no defined.
Keybordlnterrupt
& Raised when the user hits the interrupt key
(normally Control-C or Delete).
& During execution, a check for interrupts is made
regularly.
SyntaxError:
& Raised when the parser encounters a syntax
error.
Exception hierarchy

BaseException
+-- SystemExit +-- Keyboardlnterrupt +-- GeneratorExit
+-- Exception
+-- Stoplteration +-- ArithmeticError | +--
FloatingPointError
| +-- OverflowError
| +-- ZeroDivisionError
+-- AssertionError +-- AttributeError +-- BufferError
+-- EOFError
+-- ImportError
+-- LookupError
| +-- IndexError
| +-- KeyError
+-- MemoryError
+-- NameError
| +-- UnboundLocalError
+-- OSError
| +-- BlockinglOError
| +-- ChildProcessError
| +-- ConnectionError
| | +-- BrokenPipeError
| | +-- ConnectionAbortedError
| | +-- ConnectionRefusedError
| | +-- ConnectionResetError
| +-- FileExistsError
| +-- FileNotFoundError
| +-- InterruptedError
| +-- IsADirectoryError
| +-- NotADirectoryError
| +-- PermissionError
| +-- ProcessLookupError
| +-- TimeoutError
68 | P a g e SS TECHNOLOGIES Pvt Ltd
Software Training & Development. www.sstechnologis.com

+-- ReferenceError
+-- RuntimeError
| +-- NotImplementedError
+-- SyntaxError
| +-- IndentationError
| +-- TabError
+-- SystemError
+-- TypeError
+-- ValueError
| +-- UnicodeError
| +-- UnicodeDecodeError
| +-- UnicodeEncodeError
| +-- UnicodeTranslateError
+-- Warning
+-- DeprecationWarning
+-- PendingDeprecationWarning
+-- RuntimeWarning
+-- SyntaxWarning
+-- UserWarning
+-- FutureWarning
+-- ImportWarning
+-- UnicodeWarning
+-- BytesWarning
+-- ResourceWarning
69 | P a g e SS TECHNOLOGIES Pvt Ltd
Software Training & Development. www.sstechnologis.com
Object Oriented Programming
& Python is an Object-Oriented programming language.
& Python doesn't force to use the object-oriented
paradigm exclusively.
& Python also supports procedural programming with
modules and functions, so you can select the most
suitable programming paradigm for each part of your
program.
Note:
H Generally, the object-oriented paradigm is
suitable when you want to group state (data) and
behaviour (code) together in handy packets of
functionality.
Class
& Binds the member variables and into a single unit.
OR
Class is a Blue Print or Template for an object.
Syntax:
class <name>([<name>, <name>, . . .]):
& Statement's
Where,
class is a keyword. name is an identifier.
[] optional
Ex:
1. # Creating a Class
2. class Vasu():
3. print(’Hello’)
Object:
& Object is an instance of a class.
OObject has state and behaviour.
Syntax:
<referenc_name> = <class_name>([parameter list])
Ex:
1. # Creating a Class
2. class Vasu():
3. print(’Hello’)
4.
4. # Creating an object 6.obj1 = Vasu()
Note:
0 For one class you can createone or more object,
il For every object PVMmaintainsdifferent
address.
Method
& A method is a function defined in class.
Types of method
instance method Class method Ecstatic method
Instance method
& Method define inside a class and has a keyword
fselfJ parameter.

& These methods are access by using object only.


Syntax:
class <name>:
def <method_name> (self, [parameter-1, . . .]):
- statement's
Ex
1. class Example:
2. def method1(self):
3. print(’Instance method called.’)
4.
4. e1 = Example()
5. # calling an instance method
6. e1.method1()
Class method
& These methods are decorated with @classmethod. &
This method has a keyword 'cls' parameter.
Syntax:
class <name>:
@classmethod
def <method_name>(self,[parameter-1, . . .]):
- statement's
1. class Example:
2. @classmethod
3. def method1(cls):
4. print(’class method called.’)
5.
5. e1 = Example()
6. # calling an class method
7. e1.method1()
8. # calling with class name
9. Example.method1()
Static method
& A method which is decorated with @staticmethod.
Syntax: class <name>:
@staticmethod
def <method_name>([parameter-1, . . .]):
- statement's
Ex:
1. class Example:
2. @staticmethod
3. def method1():
4. print(’static method
called.’)
5.
5. e1 = Example()
6. # calling an class method
7. e1.method1()
8. # calling with class name
9. Example.method1()
73 | P a g e SS TECHNOLOGIES Pvt Ltd.
Software Training & Development. www.sstechnologis.com
Constructor
& It is a special method executed automatically when
object is created.
& It is define with ____init _().
Syntax:
Class<name>:
def _____ init_ (self, [parameter-1, . . .):
- Statement's
Ex
1. class Example:
2. # constructor
3. def _ init _ (self):
4. print(’Constructor is called.’)
5.
5. e1 = Example()
Ex: parameterized constructor
1. class Example:
2. # constructor
3. def _ init _ (self,name):
4. print(’Hi’,name,’.’)
5.
5. # calling parameterized constructor
6. e1 = Example(’rama’)
7. e2 = Example(’vasu’)
Variables in class
instance variable static variable
instance variable
& A variable which is define inside a constructor
with 'self' keyword.
Ex:
1. class Example:
2. # constructor
3. def init (self,name):
4. self.name = name
5.
5. def display(self):
6. print(’Hello’,self.name)
8.
7. # calling parameterized
constructor
8. e1 = Example(’rama’)
9. # calling display method
10. e1.display()
13.
11. e2 = Example(’vasu’)
12. e2.display()
output:
Hel1o rama Hello vasu
Static variable
& A variable which is define outside the
constructor(method).
Ex
1. class Example:
2. #static variable
name =
3.
4.
5.
6.
7.
8.
9.
3. 11. 12.
13.
14.
15.
16.
# constructor
def __ init _ (self,name):
Example.name = name
def display(self):
print(’Hello’,Example.name)
# calling parameterized constructor e1 =
Example(’rama’)
# calling display method e1.display()
e2 = Example(’vasu’)
17. e2.display()
Inheritance
What is Inheritance (Real Life Example):
& Consider a farmer having a nice farm in the Indian
countryside.
& This man has been working in agriculture for about
50 years.
& Of course, he gained a great experience.
& His son, who worked with his father for years, has
just graduated from faculty of Agriculture.
& Now, the son has his father's great practical
experience, plus scientific knowledge and
education.
& After years, the son who had become a father, has
educated his son (for accuracy a grandson) the
agriculture, transferring the experience he gained
over years from working with his father (who is
now a grandfather), combined with the
76 | P a g e SS TECHNOLOGIES Pvt Ltd.
Software Training & Development. www.sstechnologis.com
scientific knowledge he gained from his education.
& Now, the grandson who has just completed his
masters in Agriculture, has his grandfather's
practical experience, plus his father's practical
and scientific knowledge, plus his advanced
knowledge gained from studying the masters.
Definition of Inheritance
& Inheritance allows a new class to extend an
existing class.
& The new class inherits the members of the class it
extends.
& Inheritance involves a superclass and a subclass.
& The superclass in the general class and the
subclass is the specialized class.
& You can think of the subclass as an extends version
of the superclass.
& The subclass inherits attributes and methods from
the superclass without any of them having to be
rewritten.
& Furthermore, new attributes and methods may be
added to the subclass, and that is what makes it a
specialized version of the superclass.
Note:
H Super classes are also called base classes and sub
classes are also called derived classes.
Syntax:
class <name>[(<name>,<name>,. . . )]:
- Statement's
Types of Inheritance:
& Python supports Five types of inheritance as
following.
1. Single Inheritance.
2. Multi-Level Inheritance.
3. Hierarchical Inheritance.
4. Multiple Inheritance.
5. Hybrid Inheritance.
Single Inheritance
& Having one parent and child class is called single
inheritance.
Parent
Q
Child
Ex:
1. class Species:
2. def breath(self):
3. print(’Species can take breath.’)
4.
4. class Animal(Species):
5. def walk(self):
6. print(’Animals can Walk.’)
8.
7. a = Animal()
8. a.walk()
9. a.breath()
Output
Animals can Walk. Species can take
breath.
Multi-Level Inheritance
& Having more than one class which act as the parent
class.
79 | P a g e SS TECHNOLOGIES Pvt Ltd.
Software Training & Development. www.sstechnologis.com
class Species:
def breath(self):
print(’Species can take breath.’)
class Animal(Species): def eat(self):
print(’Animals can Eat.’)
class Bird(Animal): def fly(self):
print(’Birds can Fly.’)
b = Bird()
b.eat()
b.breath()
16. b.fly()
Ex
Animals can Eat. Species can take
breath.
Hierarchical Inheritance
& More than one child class have one same parent
class.
Ex:
1. class Species:
2. def breath(self):
3. print(’Species can take breath.’)
4.
4. class Animal(Species):
5. def walk(self):
6. print(’Animals can Walk.’)
8.
7. class Bird(Species):
8. def fly(self):
9. print(’Birds can Fly.’)
81 | P a g e SS TECHNOLOGIES Pvt Ltd.
Software Training & Development. www.sstechnologis.com
12.
13. a = Animal()
14. a.breath()
15. a.walk()
16. print(’ ---
17. b = Bird()
18. b.breath()
19. b.fly()
output:
Species can take breath. Animals can
Walk.
Species can take breath. Birds can
Fly.
Multiple Inheritance
& Having two parent class and one child class.
Ex:
1. class Species:
2. def breath(self):
3. print(’Species can take breath.’)
4.
4. class Animal:
5. def eat(self):
6. print(’Animals can Eat.’)
8.
7. class
Bird(Species,Animal):
8. def fly(self):
9. print(’Birds can Fly.’)
12.
10. b = Bird()
11. b.breath()
12. b.eat()
13. b.fly()
Output:
Species can take breath. Animals can
Eat. Birds can Fly.
Ex:
1.
2.
3.
4.
5.
6.
7.
8.
■ ■

class A:
def m1(self):
print(’m1() in A.’)
class B:
def m1(self):
print(’m1() in B.’)
9.
10.
class C(A,B): pass
11.
10. obj1 = C()
11. obj1.m1()
output
ml() in A.
& In above program both parent classes having same
method name.
& In this case python uses Method Resolution Order.
Method Resolution Order in Python
T Every class in Python is derived from the class
object.
T In the multiple inheritance scenario, any
specified attribute or method is searched first in
the current class. If not found, the search continues
into parent classes in depth-first, left-right
fashion without searching same class twice.
Hybrid Inheritance
1. class A:
2. def m1(self):
4.
5.
4. 7.
3. print(’m1() in A.’)
class B:
def m1(self):
print(’m1() in B.’) class C(A,B): def m1(self):
8.
9.
9. 11. 12.
13.
14.
print(’m1() in C.’)
class D(C): pass
15.
15. obj1 = D()
16. obj1.m1()
Polymorphism
T Polymorphism is a Latin word which made up of
‘‘poly’ means many and ‘‘morphs-’ means forms. From
the Greek, Polymorphism means many(poly)
shapes(morph).
T This is something similar to a word having several
different meanings depending on the context.
T Generally speaking, polymorphism means that a
method or function is able to cope with different
types of input.
Method Overloading
T There is NO direct support for method overloading
in Python.
T Can be emulated (spoofed) by using default
parameters.
Ex:
1.
2.
3.
class A:
def m1(self):
print(’m1() in A.’)
def m1(self,a):
4.
5.
4. 7.
print(’m1(a) in A.’)
7. a = A()
8. #a.m1() # TypeError: m1() missing 1 require
9. #positional argument: ’a’
11.
10. a.m1(10)
Note:
Hi In above program when you are calling m1() method
it occurs an TypeError.
(S When you are calling ml(a) but no error.
il In python latest method will be call.
Method Overloading using Default Parameter
T A default parameter to a function is where a
default value is specified in the function
definition, when the function is called without the
parameter.
Ex:
1.
2.
3.
class A:
def m1(self,a=None,b=None,c=None):
if a != None and b != None and c !=
None:
4.
print(’Three Argument are
passed.’)
5.
6.
else:
print(’Zero Arrgument are
passed.’)
7.
8. a = A()
9. a.m1()
10. a.m1(10,20,30)
Operator Overloading Ex
1. class Example:
2. def init (self,a,b):
3. self.a= a
4. self.b= b
5.
5. def add
(self,other):
6. returnself.a+ other.a, self.b +
other.b
8.
7. obj1 = Example(1,2)
8. obj2 = Example(3,4)
9. obj3 = Example(1.2,2.2)
10. print(obj1 + obj2)
11. print(obj1 + obj3)
Python Magic Methods OR Special Functions
List of Assignment operators and associated magic
methods.
Assignment Magic Method or Special
Operators Function
- = object. _ isub _ (self, other)
+= object. _ iadd _ (self, other)
*= object. _ imul _ (self, other)
/= object. _ idiv _ (self, other)

//= object. _ ifloordiv _ (self,


other)

%= object. _ imod _ (self, other)


**= object. _ ipow _ (self, other)
>>= object. _ irshift _ (self,
other)
<<= object. _ ilshift _ (self,
other)
&= object. _ iand _ (self, other)
|= object. _ ior _ (self, other)
A_ object. _ ixor _ (self, other)

List of Comparison operators and associated magic


methods.
Comparison OperatorsMagic Method or Special
_a•

Function
< object. _ lt _ (self, other)

> object. _ gt _ (self, other)

<= object. __ le _ (self, other)


>= object. ge (self, other)
== object. eq (self, other)
!= object. __ ne _ (self, other)
List of Binary operators and associated magic
methods.
Binary Operators Magic Method or Special Function

object. _ sub _ (self, other)


+ object. _ add _ (self, other)
* object. _ mul _ (self, other)
/ object. _ truediv _ (self, other)

// object. _ floordiv _ (self, other)

% object. _ mod _ (self, other)


** object. _ pow _ (self, other)
>> object. _ rshift _ (self, other)

<< object. _ lshift _ (self, other)

& object. _ and _ (self, other)


| object. _ or _ (self, other)
A object. _ xor _ (self, other)

List of Unary operators and associated magic


methods.

Unary OperatorsMagic Method or Special


Function
-

object. _ neg _ (self)


+ object. _ pos _ (self)
object. _ invert _ (self)
Ex: Overloading Comparison (>) operator
1. class Example:
2. def _______________ init(self,a):
3. self.a = a
4.
def gt (self,other):
4. return self.a > other.a
7.
5. print(100 > 50)
6. e1 = Example(45)
7. e2 = Example(39)
8. print(e1 > e2)
Method Overriding
T A sub class may change the functionality of a super
class.
T It is done by re-defining the super class method in
sub class.
Ex:
1. class Parent:
2. def shopping(self):
3. print(’Formal Dress for You.’)
4.
4. class Child(Parent):
5. def shopping(self):
6. print(’My Own dress.’)
8.
7. c = Child()
8. c.shopping()
Abstraction
T The process of defining a class by hiding
implementation details of a method and providing only
necessary details to invoke this method is called
abstraction.
Note
H In python abstract class is build by using ABC
(Abstract Base CLasses) module.
H For abstract class you can be instantiated.
Ex
1. from abc import ABC, abstractmethod
2.
2. class Abstract(ABC):
3. @abstractmethod
4. def add(self,a,b):
5. pass
7.
6. class Abs(Abstract):
7. def add(self,a,b):
8. return a + b
11.
9.a = Abs()
10. print(’Add =’,a.add(10,20))
Encapsulation
T The process of binding or wrapping of data and its
corresponding method in to a single unit is called
Encapsulation.
Ex:
1.class A:
2.def init __________ (self,a):
3.self. a = a
4.
4.def geta(self):
5.return self. a
7.
6.a = A(123)
7.print(a.geta())
Note:
H In above program ___ (double underscore) is
private.
Database in Python
T Before working with queries and cursors, a
connection to the database needs to be established.
T The credentials and data source names can be
supplied in one of several ways, with similar
results.
& work with oracle install oracle database.
& After installing oracle, you need to install the
cx_Oracle module.
Ex: Connecting to the Oracle database.
1.import cx_Oracle
2.
3. db =
cx_Oracle.connect(’vasu’,’deva’,’localhost:1521/
xe’)
4. print(db.version)
Ex:
1. import cx_Oracle
2.db=cx_Oracle.connect("vasu","deva","localhost:15
21/xe")
3. pr
int("The
na
me of the data base is : ",db)
4.if(db==None):
5. print("connection is not
established")
6. else:
7. print("connection is established")
8. db.close()
9. print("end")
Cursor():
T Allows Python code to execute database command in a
database session.
^ Cursors are created by
the connection.cursor() method: they are bound to the
connection for the entire lifetime and all the
commands are executed in the context of the database
session wrapped by the connection.
Ex: Inserting a record into a table
1. import cx_Oracle
2. try:
3. con=cx_Oracle.connect
4. ('vasu/deva@localhost')
5. cursor=con.cursor()
6. cursor.execute("INSERT into Emp
7.
values(1,,Vasu','tr,,65000.23)")
7. con.commit()
8. print("Record Inserted Successfully")
9. except cx_Oracle.DatabaseError as e:
10. if con:
11. con.rollback()
12. print(e)
13. finally:
14. if cursor:
15. cursor.close()
16. if con:
17. con.close()
Ex: Update employee salary
1.import cx_Oracle
2. try:
3.con=cx_Oracle.connect('vasu/deva@localhost' )
4. cursor=con.cursor()
5. eid=int(input("Enter Employee ID:"))
6. esal=f
loat(input("Enter Salary:"))
7. sql="update Emp set salary = salary + %f
where id
8. = %d"
9. cursor.execute(sql %(esal,eid))
94 | P a g e SS TECHNOLOGIES Pvt Ltd.
Software Training & Development. www.sstechnologis.com
con.commit()
10.
11.
12.
13.
14.
15.
16.
17.
13. 19.
print("Record Updated successfully") except
cx_Oracle.DatabaseError as e:
con.rollback()
print(e)
finally:
if cursor:
cursor.close()
if con:
con.close()
Ex: Displaying a table.
1. import cx_Oracle
2.
3. db =
cx_Oracle.connect('vasu/deva@localhost')
4. cursor = db.cursor()
5. cursor.execute(’Select *
from Emp1’)
6. for row in cursor:
7. print(row)
8.
8. cursor.close()
9. db.close()
Software Training & Development. www.sstechnologis.com
Regular Expression Modifiers: Option Flags
Modifier Description

re.I Performs case-insensitive matching.


re.L Interprets words according to the
current locale. This interpretation
affects the alphabetic group (\w and
\W), as well as word boundary behavior
(\b and \B).
re.M Makes $ match the end of a line (not
just the end of the string) and makes
A match the start of any line (not

just the start of the string).

re.S Makes a period (dot) match any


character, including a newline.

re.U Interprets letters according to the


Unicode character set. This flag affects the behavior
of \w, \W, \b, \B.
re.X Permits "cuter" regular expression
syntax. It ignores whitespace (except inside a set []
or when escaped by a backslash) and treats unescaped #
as a comment marker.
Regular Expression Patterns
Pattern Description

A Matches beginning of line.

S Matches end of line.

Matches any single character except


newline. Using m option allows it to
match newline as well.

[...] Matches any single character in


brackets.
[A...] Matches any single character not in
brackets
re* Matches 0 or more occurrences of
preceding expression.

re+ Matches 1 or more occurrence of


preceding expression.
Matches 0 or 1 occurrence of
preceding expression.
re?
re{ n}

re{ n,} re{ n, m}

a| b (ne)

(?imx)

(?-imx)

(?: re)

Matches exactly n number of


occurrences of preceding
expression.
Matches n or more occurrences of
preceding expression.
Matches at least n and at most m
occurrences of preceding
expression.
Matches either a or b.
Groups regular expressions and
remembers matched text.
Temporarily toggles on i, m, or x
options within a regular
expression. If in parentheses, only
that area is affected.
Temporarily toggles off i, m, or x
options within a regular
expression. If in parentheses, only
that area is affected.
Groups regular expressions without
remembering matched text.
JILLA VASU DEVA SRAVAN
i* python
(?imx: re) Temporarily toggles on i, m, or x
options within parentheses.

(?-imx: re) Temporarily toggles off i, m, or x


options within parentheses.
(?#...) Comment.

(?= re) Specifies position using a pattern.


Doesn’t have a range.

(?! re) Specifies position using pattern


negation. Doesn’t have a range.

(?> re) Matches independent pattern without


backtracking.

\w Matches word characters.

\W Matches nonword characters.

\s Matches whitespace. Equivalent to


[\t\n\r\f].
\S Matches nonwhitespace.

\d Matches digits. Equivalent to [0-9].

\D Matches nondigits.

\A Matches beginning of string.

\Z Matches end of string. If a newline


exists, it matches just before newline.
\z Matches end of string.
\G Matches point where last match
finished.
\b Matches word boundaries when outside
brackets. Matches backspace (0x08) when inside
brackets.
\B Matches nonword boundaries.
\n, \t, etc. Matches newlines, carriage returns,
tabs, etc.

\1...\9 Matches nth grouped subexpression.

\10 Matches nth grouped subexpression if


it matched already. Otherwise refers to the octal
representation of a character code.
Character classes Example Description

[Pp]ython Match "Python" or "python"

rub[ye] Match "ruby" or "rube"


[aeiou] Match any one lowercase vowel
[0-9] Match any digit; same as
[0123456789]

[a-z] Match any lowercase ASCII letter

[A-Z] Match any uppercase ASCII letter


[a-zA-Z0-9] Match any of the above

[Aaeiou] Match anything other than a


lowercase vowel

[A0-9] Match anything other than a digit

Special Character Classes


Example Description

• Match any character except newline

\d Match a digit: [0-9]


\D Match a nondigit: [A0-9]

\s Match a whitespace character: [ \t\r\n\f]

\S Match nonwhitespace: [A \t\r\n\f]


TM

i* python JILLA VASU DEVA SRAVAN

\w Match a single word character: [A-Za-


z0-9_]

\W Match a nonword character: [AA-Za-z0-


9_]

Repetition Cases

Example Description

ruby? Match "rub" or "ruby": the y is


optional

ruby* Match "rub" plus 0 or more ys

ruby+ Match "rub" plus 1 or more ys

\d{3} Match exactly 3 digits

\d{3,} Match 3 or more digits

\d{3,5} Match 3, 4, or 5 digits

Nongreedv repetition

Example Description

<.*> Greedy repetition: matches


"<python>perl>"
<.*?> Nongreedy: matches "<python>" in
"<python>perl>"

Grouping with Parentheses


102 | P a g e SS TECHNOLOGIES Pvt Ltd.
Software Training & Development. www.sstechnologis.com

Example Description
\D\d+ No group: + repeats \d
(\D\d)+ Grouped: + repeats \D\d
pair
([Pp]ython(, )?)+ Match "Python", "Python,
python, python", etc.

Backreferences
Example Description

([Pp])ython&\1ails Match python&pails or


Python&Pails

([’"])[A\1]*\1 Single or double-quoted string.


\1 matches whatever the 1st group
matched. \2 matches whatever the
2nd group matched, etc.

Alternatives
Example Description
python|perl Match "python" or "perl"

rub(y|le)) Match "ruby" or "ruble"

Python(!+|\?) "Python" followed by one or more ! or


one ?
Anchors

Example Description
APython Match "Python" at the start of a string
or internal line
Python$ Match "Python" at the end of a string or
line

\APython Match "Python" at the start of a string

Python\Z Match "Python" at the end of a string

\bPython\b Match "Python" at a word boundary

\brub\B \B is nonword boundary: match "rub" in


"rube" and "ruby" but not alone

Python(?=!) Match "Python", if followed by an


exclamation point.

Python(?!!) Match "Python", if not followed by an


exclamation point.

Special Syntax with Parentheses

Example Description

R(?#comment) Matches "R". All the rest is a


comment
R(?i)uby Case-insensitive while matching
"uby"
Same as above
rub(?:y|le))
R(?i:uby)
Group only without creating \1
backreference
match Function
T This function attempts to match RE pattern to
string with optional flags.
syntax
re.match(pattern, string, flags=0)
Ex:
I. import re
2.
3.line = "Cats are smarter than dogs"
4.
4.matchObj = re.match( r’(.*) are (.*?) .*’, line,
re.M|re.I)
6.
7.if matchObj:
8. print("matchObj.group()
: ", matchObj.group())
9. print("matchObj.group(1)
: ", matchObj.group(1))
10. print("matchObj.group(2)
: ", matchObj.group(2))
II. else:
9. print("No match!!")
search Function
T This function searches for first occurrence of RE
pattern within string with optional flags.
syntax
re.search(pattern, string, flags=0)
Ex
I. import re
2.
3.line = "Cats are smarter than dogs";
4.
4.searchObj = re.search( r’(.*) are (.*?) .*’,
line, re.M|re.I)
6.
7.if searchObj:
8. print("searchObj.group() : ",
searchObj.group())
9. print("searchObj.group(1) : ",
searchObj.group(1))
10. print("searchObj.group(2) : ",
searchObj.group(2))
II. else:
10. print("Nothing found!!")
Program
1. Design a Python program to find the average of best two
marks out of three marks taken as input.
2. Write a python program to swap two variables
without using 3rd variable.
3. Write a python program to swap two variables
using Operator's
4. Write a python program to check whether a
given number is even or odd number.
5. Write a python program to check whether a
given number is positive or negative number.
6. Write a python program to check whether a given
character is vowel or consonant.
7. Write a python program to check whether a given
person age is eligible to vote or not.
8. Write a python program to find maximum number
between two numbers.
9. Write a python program to find maximum number
between three numbers.
10. Write a python program to find a given
character is upper case or lower case or not.
11. Write a python program to check whether a given year is
leap or not.
12. Write a python program to check whether a number is
divisible by 5 and 11 or not.
13. Write a Python program to input angles of a triangle and
check whether triangle is valid or not.
14. Write a Python program to calculate profit or loss.
15. Write a Python program to input marks of five subjects
Physics, Chemistry, Biology, Mathematics and Computer.
Calculate percentage and grade according to following:
Percentage >= 90% Grade A
Percentage >= 80% Grade B
Percentage >= 70% Grade C
Percentage >= 60% Grade D
Percentage >= 40% : Grade E
Percentage < 40% : Grade F
16. Write a Python program to input basic salary of an
employee and calculate its Gross salary according to
following:
Basic Salary <= 10000 : HRA = 20%, DA = 80%
Basic Salary <= 20000 : HRA = 25%, DA = 90%
Basic Salary > 20000 : HRA = 30%, DA = 95%
17. Write a Python program to input electricity unit charges
and calculate total electricity bill according to the given
condition:
For first 50 units Rs. 0.50/unit
For next 100 units Rs. 0.75/unit
For next 100 units Rs. 1.20/unit
For unitabove 250 Rs. 1.50/unit
An additional surcharge of 20% is added to the bill
18. Write a Python program to print alphabets from a to z.
19. Write a Python program to print ASCII values of all
characters.
20. Write a Python program to print multiplication table of a
given number.
21. Write a Python program to print all-natural numbers in
reverse order.
22. Write a Python program to print sum of digits enter by
user.
23. Write a Python program to find sum of even numbers
between 1 to n.
24. Write Python program to find sum of odd numbers between 1
to n.
25. Write Python program to swap first and last digit of a
number.
26. Write Python program to find the sum of first and last
digit of any number.
27. Write Python program to find first and last digit of any
number.
28. Write Python program to calculate product of digits of a
number.
29. Write Python program to reverse a number using while
loop.
30. Write Python program to calculate power using while & for
loop.
31. Write Python program to find factorial of any number.
32. Write a Python program to check whether a number is
Armstrong number or not.
33. Write Python program to find Armstrong numbers between 1
to n.
34. Write a Python program to calculate compound Interest.
35. Write a Python program to check a enter number is Prime
number or not using while & for loop.
36. Write a Python program to check whether a number is
palindrome or not.
37. Write a Pythonprogram to print number in
words.
38. Write a Pythonprogram to find HCF of two
numbers.
39. Write a Pythonprogram to find LCM of two
numbers.
40. Write a Pythonprogram to find Fibonacci
series.
41. Write a Pythonprogram to Reverse a string
using
slice operator.
42. Write a Python program to Reverse a string without using
any operator or method.
43. Write a python program to find the sum of all numbers in
a list.
44. Write a python program to find largest number in a given
list without using max()
45. Write a python program to find the common numbers from
two lists.
46. Write a python program to print all even numbers from a
given list.
47. Write a python program to create a list of even numbers
and another list of odd numbers from a given list.
48. Write a python program to remove repeated elements from a
given list without using built-in methods.
49. Write a python program to find the longest word in a
given sentence.
50. Write a python program to find number of occurrences of
given number without using built-in methods.
51. Write a python program to sort a given list of numbers
without using sort() function.

You might also like