Python Record
Python Record
CERTIFICATE
5 5
a,b = 3,5
print(a,b)
3 5
I/O functions:-
we have two I/O functions 1) print() 2) input()
• with the help of print function we can print the data,the data written within the
double quotes will be displayed in the output
• with the help of input function we can take the input through
console(dynsmicslly),by default the data taken through input function is of string
type,which needs to be converted into different types according to our need.
a,b,*c = 1,2,3,4,5,6
print(a)
print(b)
print(c)
print(type(a), type(b))
print(type(c))
1
2
[3, 4, 5, 6]
<class 'int'> <class 'int'>
<class 'list'>
z = input()
print(z)
hello
hello
Data Types:-
we know that variables can hold values of different types called datatypes,we need
different datatypes to store different types of data.python has various standard datatypes
like numbers,strings,list,tuple,sets,dictionary.
1848530004560
<class 'int'>
1848532683376
<class 'str'>
<class 'dict'>
Type Conversions:-
the conversion of data from one data type to another datatype is known as type conversion.
we can perform type conversion explicitly usinf the class
names:int,list,string,set,tuple,dictionary.
• to convert a value into int we can use int(variable/value)
• similarly to convert a value into string,list,tuple,set,dictionary we use
str(variable),list(),set(),dict()
k = "hello"
num = len(k)
new = str(num)
print("your name hase " + new + " characters")
a = 10
print(float(a))
b = 23
print(str(b))
l = [1,2,3]
print(tuple(l))
print(set(l))
your name hase 5 characters
10.0
23
(1, 2, 3)
{1, 2, 3}
OPERATORS:-
• operators are used to perform operations on variables and values
• python operators are divided into following groups 1.Arithematic
operators2.Assignment operators3.Comparison operators4.Logical
operators5.Identity operators6.Membership operators7.Bitwise operators
1.Arithematic Operators:-
These operators are used with numeric values to perform common mathematical
operations
13
-3
40
0.625
5
390625
2.Assignment Operators:-
Assignment operators are used to assign values to variables
31
52
1092
52.0
10.0
1e+21
4.761904761904762e+19
3.Comparison Operators:-
-Comparison(relational) operators are used to campare the values on the either side of the
operator and returns either "TRUE" or "FALSE"
type of operators:
Operator
==
!=
<
>
<=
>=
a = 10
b = 34
print(a==b)
print(a<b)
print(a>b)
print(a!=b)
print(a<=b)
print(a>=b)
False
True
False
True
True
False
4.Logical Operators:-
A logical operator is a symbol used to connect two or more expressions such that the value
of the compound expression produced depends only on that of the original expressions and
on the meaning of the operator. the logical expression gets evaluated from left to right
23
11
False
5.Bitwise Operators:-
• these operators perform operations among the bits,the data is converted into bits
and the operation is performed |Operator|Name|Description| |--------|----|-----------| |
&|Bitwise AND|The bitwise AND operator comprise each bit of the first operand
with the corresponding bit of its second operand. If both bits are 1, the
corresponding bit in the result is 1, and 0 otherwise| |¿|Bitwise OR|The bitwise OR
operator comprise each bit of the first operand with the corresponding bit of its
second operand. If onr or both bits are 1, the corresponding bit in the result is 1, and
0 otherwise| |^|Bitwise XOR|The bitwise XOR operator comprise each bit of the first
operand with the corresponding bit of its second operand. If one of bits are 1, the
corresponding bit in the result is 1, and 0 otherwise| |~|Bitwise NOT|Bitwise NOT
operator sets the bit to 1, if it is initially 0 and sets it to 0, if it was initially 1|
a,b = 6,8
print(a & b)
print(a | b)
print(a ^ b)
print(~a)
print(a << 3)
print(a >> 2)
0
14
14
-7
48
1
6.Identity Operators:-
Tests for identity i.e, it checks the id of both the operands
Operator Description
is returns true if both the operands have the same
reference id or refers to the same object
is not returns true if both the operands does not have
the same reference id or do not refer to the same
object
a,b = 6,8
print(a is not b)
print(a is b)
True
False
7.Membership Operators:-
these operators tests for the membership in a sequence i.e,checks whether a value present
in a sequence or not
Operator Description
in returns true if a value is found in a sequence else
returns false
not in returns true if a value is not found in a sequence
else returns false
list1 = [1, 2, 3, 4, 5]
list2 = [6, 7, 8, 9]
for item in list1:
if item in list2:
print("overlapping")
else:
print("not overlapping")
not overlapping
not overlapping
not overlapping
not overlapping
not overlapping
a = [1,2,3,4,5]
b,c = 23,1
print(b in a)
print(c in a)
print(c not in a)
False
True
False
item = 29
list_1 = list(range(1, 30))
print(item in list_1)
Conditional statements in Python
Conditional statements are also known as decision-making statements. We need to use
these conditional statements to execute the specific block of code if the given condition is
true or false.
If statements:
• <\expr> is an expression evaluated in a Boolean context.
• "statement" is a valid Python statement, which must be indented.
• Note that the colon (:) following <\expr> is required. Some programming languages
require <\expr> to be enclosed in parentheses, but Python does not.
Syntax
if <\expr\> : Statement1
Example Program:
a = 23
b = 100
if b > a:
print("b is greater than a")
b is greater than a
a = 54
b = 54
if a==b:
print("equal")
equal
If-else statements:
• If <\expr> is true, the first suite is executed, and the second is skipped. If <\expr> is
false, the first suite is skipped and the second is executed.
• Both suites are defined by indentation.
Syntax:
if <\expr\>: Statement else: Statement
Example Program:
a = int(input("enter a number"))
if (a % 2 == 0):
print("this is a even number")
else :
print("this is a odd number")
enter a number4
this is a even number
elif Statement:
• if and elif clauses evaluates each <\expr> in turn and executes the suite
corresponding to the first that is true. If none of the expressions are true, and an else
clause is specified, then its suite is executed.
Syntax:
if <\expr\>: statement1(when condition is true,execute)
elif <\expr\>: statement2(when if condition is false,then check the elif for conditionif
true,execute) else: statement3(execute when both if and elif is false)
Example Program:
a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
name = 'Joe'
if name == 'Fred':
print('Hello Fred')
elif name == 'Joe':
print('Hello Joe')
elif name == 'Arnold':
print('Hello Arnold')
else:
print("I don't know who you are!")
Hello Joe
Syntax:
if<\expr\>: #Statements to execute if condition is true if<\expr\>:
#Statements to execute if condition is true else : #Statement to execute to
nested if condition is false
else: #Statement execute when if condition is false
Example Program:
num = 16
if num >= 0:
if num == 0:
print("zero")
else:
print("positive number")
else:
print("negative number")
positive number
num = 5
str = 'hello'
if num > 1:
if str == "hello":
print("equal")
else :
print("not equal")
equal
elif Ladder:
• if and elif clauses evaluates each <\expr> in turn and executes the suite
corresponding to the first that is true. If none of the expressions are true, and an else
clause is specified, then its suite is executed.
• An arbitrary number of elif clauses can be specified. The else clause is optional. If it
is present, there can be only one, and it must be specified last.
Syntax:
if <\expr1\>: #Set of statement to execute if condition is true elif <\expr2\>:
#Set of statements to be executed when if condition is false and elif condition is true elif <\
expr3\>: #Set of statements to be executed when both if and first elif condition is
false and second elif condition is true elif <\expr4\>: #Set of statements to be
executed when if, first elif and second elif conditions are false and third elif statement is
true else: #set of statement is executed when if and all elif statement is false
Example Program:
print('Select your ride:')
print('1. Bike')
print('2. Car')
print('3. SUV')
if( choice == 1 ):
print('You have selected Bike')
elif( choice == 2 ):
print('You have selected Car')
elif( choice == 3 ):
print('You have selected SUV')
else:
print('wrong choice!')
name = 'Fred'
if name == 'Fred':
print('Hello Fred')
elif name == 'Joe':
print('Hello Joe')
elif name == 'Arnold':
print('Hello Arnold')
else:
print("I don't know who you are!")
LOOPING STATEMENTS:
• A Loop statement allows us to execute a statement or group of statements multiple
times.
• A Loop is used to execute a block of statements repeatedly until a given condition is
satisfied. And when the condition becomes false, the line immediately after the loop
in the program is executed.
For loop:-
• A for loops are used for sequencial traversal(that is either a list,a tuple,a dictionary,a
set or a string).
• With the for loop we can execute a set of statements,once for each item in a list,tuple
etc.
Syntax:
for iterator_var in sequence: statements(s)
fruits = ["apples","mango","banana","peach"]
for i in fruits:
print(i)
score = [33,43,76,99,45,34,64,34,66,77,53]
s = 0
for i in score:
if i > s:
s = i
print(f"the highest score is : {s}")
For-else:
• The else block just after the for loop is executed only when the loop is NOT
terminated by a break statement.
Syntax:
for variable in sequence: "statement" else: "statements to be executed after loop"
for x in range(2):
print(x)
else:
print("Finally finished!")
0
1
Finally finished!
for x in range(6):
if x == 3: break
print(x)
else:
print("done")
0
1
2
While loop:
• while loop is used to execute a block of statements repeatedly until a given
condition is satisfied
• while loops falls under the category of indefinite iteration.
Syntax:
while condition : "statements"
i = 1
while i < 3:
print(i)
i += 1
1
2
count = 0
while (count < 2):
count = count + 1
print("this is while loop")
while-else:
• When the condition becomes False and the loops runs normally,the else clause will
execute.
• If the loop is terminated prematurely by either a break or return statement,the
clause won't execute at all.
Syntax:
while condition: "statement" else: "statement"
i = 1
while i < 3:
print(i)
i += 1
else:
print("after the while loop")
1
2
after the while loop
i = 0
while i < 2:
print("inside while")
i+=1
else:
print("outside while")
inside while
inside while
outside while
Break , Continue and Pass in Python
Python supports the following control statements.
1.Break statement 2.Continue statement 3.Pass statement
1.Break statement:
• The break statement is used to terminate the loop or statement in which it is
present .After that, the control will pass to the statement that are present after the
break statement.
number = 0
print('Out of loop')
Number is 0
Number is 1
Number is 2
Number is 3
Number is 4
Out of loop
current number 10
current number 40
2.Continue statement:
• Continue statement is opposite to that of break statement,instead of terminating the
loop,it forces to execute the next iteration of the loop.
• The continue statement forces the loop to continue or execute the next iteration
• NOTE:The statement after the "continue" wont be executed.
number = 0
print('Out of loop')
Number is 0
Number is 1
Number is 2
Number is 3
Number is 4
Number is 6
Number is 7
Number is 8
Number is 9
Out of loop
Current Number is 2
Square of a current number is 4
Current Number is 3
Square of a current number is 9
Current Number is 11
Current Number is 7
Square of a current number is 49
3.Pass statement:
• Pass statement simply does nothing.The pass statement in python is used when a
statement is requried syntactically but you do not want any command or code to
execute.
• NOTE:The statement after the "pass" statement will be executed
number = 0
print('Out of loop')
Number is 0
Number is 1
Number is 2
Number is 3
Number is 4
Number is 5
Number is 6
Number is 7
Number is 8
Number is 9
Out of loop
2 is a multiple of 2
4 is a multiple of 2
6 is a multiple of 2
8 is a multiple of 2
Python Data Structures
Data Structures are the way of organizing data so that it can be accessed more efficiently
depending upon the situation. Data Structures are fundamentals of any programming
language around which a program is built .Python helps to learn the fundamentals of these
data structures in a simpler way as compared to other programming language.
These data structures are specific to python language and they give flexibility in storing
different types and faster processing in python environment. 1.Strings 2.List 3.Tuple
4.Set 5.Dictionary
Strings:
• A string ia a sequence of characters. • String in python are surrounded by either single
quotation mark,or double quotation marks. • 'Hello' is same as "Hello".
----------------------------------------------------------------------
-----
TypeError Traceback (most recent call
last)
Input In [10], in <cell line: 2>()
1 s="abc"
----> 2 s[1]="2"
3 s
'a123bc[1,2]'
Syntax:
x="hello" print(x)
METHODS
capitalize():
s='who cares?'
x=s.capitalize()
print(x)
Who cares?
count():
s="abaracadabra"
print(s.count("a"))
find():
s="abaracadbra"
print(s.find("r"))
index():
s="abaracadbra"
print(s.index("b"))
islower():
s="hello !"
print(s.islower())
True
isupper():
s="HELLO"
print(s.isupper())
True
join():
t= ("Hello", "am", "looser")
x = " ".join(t)
print(x)
Hello am looser
lower():
s="I TOO"
print(s.lower())
i too
replace():
s="Hello "
s.replace(' ','hi')
'Hellohi'
split():
s="abarakadabra"
s.split("b")
startswith():
s="Hello !"
s.startswith("he")
False
upper():
s="abcdef"
s.upper()
'ABCDEF'
len():
s="abarakadabra"
print(len(s))
12
chr():
b=chr(97)
print(b)
ord():
print(ord("a"))
print(ord("A"))
97
65
str():
s=1234
str(s)
'1234'
Concatenation:
s1="hello"
s2="world"
s1+s2
'helloworld'
Repetation:
s1="a"
s1*5
'aaaaa'
s="hellooo!"
print(s[0:4])
hell
Lists:
• A list is a collection of arbitrary objects, somewhat akind to an array in many other
programming languages but more flexible. Lists are defined in Python by enclosing a
comma-separated sequence of objects in square brackets ([ ]).
• Lists need not be homogeneous always which makes it the most powerful tool in
Python. A single list may contain DataTypes like Integers, Strings, as well as Objects.
## Positive Accessing:
a=[1,2,3,4]
a[1:2]
[2]
## Negative Accessing:
a=[1,2,3,4]
a[-1]
Slicing also works. If a is a list, the expression a[m:n] returns the portion of a from index m to,
but not including, index n:
Both positive and negative indices can be specified:
a=[1,2,3,4,5]
print(a[-5:-1])
print(a[0:4])
[1, 2, 3, 4]
[1, 2, 3, 4]
Omitting the first index starts the slice at the beginning of the list, and omitting the second
index extends the slice to the end of the list:
l=[1,2,3,4]
print(l[:4],l[2:])
[1, 2, 3, 4] [3, 4]
['a', 'c']
['d', 'b']
The syntax for reversing a list works the same way it does for strings:
l=[1,2,3,4,5]
l[::-1]
[5, 4, 3, 2, 1]
The [:] syntax works for lists. However, there is an important difference between how this
operation works with a list and how it works with a string.
s="hello"
print(s[:])
print(s[:] is s)
hello
True
a=[1,2,3,4]
print(a[:])
print(a[:] is a)
[1, 2, 3, 4]
False
['a', ['bb', ['ccc', 'ddd'], 'ee', 'ff'], 'g', ['hh', 'ii'], 'j']
print(x[1])
print(x[1][1])
['bb', ['ccc', 'ddd'], 'ee', 'ff']
['ccc', 'ddd']
1530918151168
1530918151168
[1, 2, 3, 1, 2, 3]
Syntax:
A list is created by placing elements inside square brackets [], separated by commas.
Example: my_list=[1,2,3] print(my_list)
METHODS:
append() :
l1=[1,2,3,4]
l1.append(5)
print(l1)
[1, 2, 3, 4, 5]
insert():
l1=[0,2,3,4,5]
l1.insert(1,1)
print(l1)
[0, 1, 2, 3, 4, 5]
extend():
l1=[1,2,3,4]
l1.extend([5,6,7])
print(l1)
[1, 2, 3, 4, 5, 6, 7]
clear():
l1=[1,2,3,4]
l1.clear()
print(l1)
[]
copy():
l = [1,2,3,4]
l1 = l.copy()
print(l1)
[1, 2, 3, 4]
count():
l1=[1,2,3,1,1,4,5]
print(l1.count(1))
index():
l=['h','e','e',' ','n','t','g']
print(l.index(' '))
print(l.index('e'))
3
1
pop():
l1=[1,2,3,4]
l1.pop()
print(l1)
[1, 2, 3]
remove():
l1=[1,11,22,33,55]
l1.remove(l1[1])
print(l1)
reverse():
l1=[1,2,3,4,5,6]
l1.reverse()
print(l1)
[6, 5, 4, 3, 2, 1]
sort():
l=[5,6,7,2,4,3]
l.sort()
print(l)
[2, 3, 4, 5, 6, 7]
del:
l=[1,2,3,4]
del l[1]
l
[1, 3, 4]
Concatenation:
l1=[1,2,3]
l2=['a','b','c']
l1+l2
Repetation:
l1=[1,2,3,4]
l1*2
[1, 2, 3, 4, 1, 2, 3, 4]
Packing:
n1=1
n2=2
n3=3
l=[n1,n2,n3]
l
[1, 2, 3]
Unpacking:
l1=[1,2,3]
a,b,c=l1
print(a,b,c)
1 2 3
Tuple:
• Tuples are sequences, just like lists. The differences between tuples and lists are, the
tuples cannot be changed unlike lists and tuples use parentheses, whereas lists use
square brackets.
• NOTE:If tuple element is a list(mutable) value ,then we can do the modifications on
that element.
False
1530919309376
1530920066800
(x,y,z,w)=t
print(x,y,z,w)
a b c d
n1=1
n2=2
n3=3
t=(n1,n2,n3)
t
(1, 2, 3)
l1=(1,2,3)
a,b,c=l1
print(a,b,c)
1 2 3
Syntax:
A tuple is created by placing all the items (elements) inside parentheses () , separated by
commas. Example: my_tuple=(1,2,3) print(my_tuple)
METHODS:
count():
t=(1,2,3,2,2,1,3,4)
t.count(2)
index():
t=(1,2,3,4,5,6)
t.index(1)
del:
t=(1,2,3,4)
del t
print(t)
----------------------------------------------------------------------
-----
NameError Traceback (most recent call
last)
Input In [123], in <cell line: 3>()
1 t=(1,2,3,4)
2 del t
----> 3 print(t)
Concatenation:
t1=(1,2,3)
t2=('a','b','c')
t1+t2
Repetition:
t1= (1,2,3)
t1*2
(1, 2, 3, 1, 2, 3)
Set:
• A Python set is the collection of the unordered items. Each element in the set must
be unique, hashable.There is no index attached to the elements of the set, i.e., we
cannot directly access any element of the set by the index.
----------------------------------------------------------------------
-----
TypeError Traceback (most recent call
last)
Input In [146], in <cell line: 1>()
----> 1 s={1,2,3,[1,2]}
2 s
{1, 2, 3}
3
True
Syntax:
A set is created by placing all the items (elements) inside curly braces {}, separated by
comma. Example(set of integers): my_set={1,2,3} print(my_set)
METHODS:
add():
s={1,2,3}
s.add(4)
print(s)
{1, 2, 3, 4}
clear():
s={1,2,3}
s.clear()
s
set()
copy():
x={1,2,3}
y=x.copy()
y
{1, 2, 3}
difference():
s={1,2,3,4,5,6}
s1={4,5,6,7,8,9}
s.difference(s1)
{1, 2, 3}
discard():
x={1,2,3}
x.discard(3)
x
{1, 2}
x={1,2,3}
x.discard()
x
----------------------------------------------------------------------
-----
TypeError Traceback (most recent call
last)
Input In [165], in <cell line: 2>()
1 x={1,2,3}
----> 2 x.discard()
3 x
x={1,2,3}
x.discard(4)
x
{1, 2, 3}
intersection():
s={1,2,3}
s1={3,4,5}
s.intersection(s1)
{3}
isdisjoint():
s={1,2,3,4,5,6}
s1={4,5,6,7,8,9}
s.isdisjoint(s1)
False
issubset():
s={1,2,3,4,5,6}
s1={4,5,6,7,8,9}
s.issubset(s1)
False
issuperset():
s={1,2,3,4,5,6}
s1={4,5,6,7,8,9}
s.issuperset(s1)
False
pop():
s={1,2,3}
s.pop()
s
{2, 3}
s={'a','b','c'}
s.pop('a')
s
----------------------------------------------------------------------
-----
TypeError Traceback (most recent call
last)
Input In [157], in <cell line: 2>()
1 s={'a','b','c'}
----> 2 s.pop('a')
3 s
remove():
x={'a','b','c'}
x.remove('a')
x
{'b', 'c'}
s={1,2,3,4}
s.remove()
s
----------------------------------------------------------------------
-----
TypeError Traceback (most recent call
last)
Input In [161], in <cell line: 2>()
1 s={1,2,3,4}
----> 2 s.remove()
3 s
s={1,2,3,4}
s.remove(5)
s
----------------------------------------------------------------------
-----
KeyError Traceback (most recent call
last)
Input In [162], in <cell line: 2>()
1 s={1,2,3,4}
----> 2 s.remove(5)
3 s
KeyError: 5
symmetric_difference():
s={1,2,3,4,5,6}
s1={4,5,6,7,8,9}
s.symmetric_difference(s1)
{1, 2, 3, 7, 8, 9}
union():
s={1,2,3}
s1={3,4,5}
s1.union(s)
{1, 2, 3, 4, 5}
update():
s={1,2,3}
s.update(4)
s
----------------------------------------------------------------------
-----
TypeError Traceback (most recent call
last)
Input In [158], in <cell line: 2>()
1 s={1,2,3}
----> 2 s.update(4)
3 s
s={1,2,3}
s.update((1,4))
s
{1, 2, 3, 4}
Frozenset method:
• Frozenset method makes set as an immutable object.
• as it is a set object therefore we cannot have a duplicate values in the frozenset.
f={'a','b','c'}
f=frozenset(f)
print(f)
frozenset objects are mainly used as key in dictionary or elements of other sets.
d={'a':1,'b':2,'c':3}
key=frozenset(d)
key
frozenset({1, 2, 3})
----------------------------------------------------------------------
-----
TypeError Traceback (most recent call
last)
Input In [179], in <cell line: 4>()
2 f=frozenset(l)
3 print(f)
----> 4 f[1]=0
{1, 2, 3, 4, 5}
{3}
{1, 2, 3}
{1, 2, 3, 7, 8, 9}
True
## using '>=' method
s={1,2,3,4,5,6}
s1={4,5,6}
s>=s1
True
Dictionary:
• A dictionary consists of a collection of key-value pair.Each key-value pair maps the
key to its value.
d={1:'a',1:'b'}
d
{1: 'b'}
----------------------------------------------------------------------
-----
TypeError Traceback (most recent call
last)
Input In [211], in <cell line: 1>()
----> 1 d = {[1, 1]: 'a', [1, 2]: 'b', [2, 1]: 'c', [2, 2]: 'd'}
2 d
10
'b'
d = {[1, 1]: 'a', [1, 2]: 'b', [2, 1]: 'c', [2, 2]: 'd'}
d[[1,2]]
----------------------------------------------------------------------
-----
TypeError Traceback (most recent call
last)
Input In [209], in <cell line: 1>()
----> 1 d = {[1, 1]: 'a', [1, 2]: 'b', [2, 1]: 'c', [2, 2]: 'd'}
2 d[[1,2]]
True
Syntax:
Creating a dictionary is as simple as placing items inside curly braces { } separated by
commas.An item has a key and a corresponding value that is expressed as a pair (key:
value). Example: my_dict={1:'a',2:'b'} print(my_dict)
METHODS:
clear():
d = {'a': 10, 'b': 20, 'c': 30}
d.clear()
d
{}
copy():
d = {'a': 10, 'b': 20, 'c': 30}
d1=d.copy()
d1
get():
d={1:10,2:20,3:30,4:40}
print(d.get(2))
print(d.get(5))
20
None
items():
d = {'a': 10, 'b': 20, 'c': 30}
d.items()
keys():
d = {'a': 10, 'b': 20, 'c': 30}
d.keys()
values():
d = {'a': 10, 'b': 20, 'c': 30}
d.values()
pop():
d={1:10,2:20,3:30,4:40}
d.pop(1)
d
d.pop(1)
d
----------------------------------------------------------------------
-----
KeyError Traceback (most recent call
last)
Input In [220], in <cell line: 1>()
----> 1 d.pop(1)
2 d
KeyError: 1
popitem():
d={1:10,2:20,3:30,4:40}
print(d.popitem())
d
(4, 40)
print(d.popitem(2))
d
----------------------------------------------------------------------
-----
TypeError Traceback (most recent call
last)
Input In [222], in <cell line: 1>()
----> 1 print(d.popitem(2))
2 d
update():
d1={'a':1,'b':2,'c':3}
d2={'d':4,'e':5}
d1.update(d2)
print(d1)
len():
d1={0:1,1:2}
d2={1:1,2:2}
print(len(d1))
max():
d1={0:1,1:2}
d2={1:1,2:2}
print(max(d1))
print(max(d2))
1
2
min():
d1={0:1,1:2}
d2={1:1,2:2}
print(min(d1))
print(min(d2))
0
1
sum():
l=[1,2,3,4,5]
print(sum(l))
15
all():
d1={0:1,1:2}
d2={1:1,2:2}
print(all(d1))
print(all(d2))
False
True
any():
d1={0:1,1:2}
d2={1:1,2:2}
print(any(d1))
print(any(d2))
True
True
sorted():
l=[1,4,5,3,2]
l1=sorted(l)
l1
[1, 2, 3, 4, 5]
PROGRAMS:
## sorting elements in the list without sort() method
l=[5,3,4,2,8,1]
for i in range(0,len(l)):
for j in range(0,len(l)):
if(l[i]<l[j]):
l[i],l[j]=l[j],l[i]
print(l)
[1, 2, 3, 4, 5, 8]
## swap of first and last element in the list
l=[10,20,30,40,50]
a,*b,c=l
a,c=c,a
l=a,*b,c
print(l)
print(list(l))
1234
1
found
print("Max",l[k-1])
print("Min",l[-k])
122343125
2
[1, 2, 3, 4, 5]
Max 2
Min 4
COMPREHENSIONS
• Comprehensions in Python provide us with a short and concise way to construct
new sequences (such as lists, set, dictionary etc.) using sequences which have been
already defined.
1. List Comprehensions
2. Dictionary Comprehensions
3. Set Comprehensions Note: Tuple comprehensions are not possible because, tuples
are immutable.
1. LIST COMPREHENSION
List Comprehensions provide an elegant way to create new lists.
• Always returns a list.
• Returns a single line list.
Syntax:
new_list = [expression for member in iterable]
• expression is a call to a method,or any other valid expression that returns a value.
• member is the object or value in the list.
• iterable is a list,set or any other object that can return its elements one at a time.
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = []
for x in fruits:
if "a" in x:
newlist.append(x)
print(newlist)
print(n)
a = [1,2,3,4,5]
b = [i**2 for i in a]
print(b)
[2, 4, 6, 8]
[1, 4, 9, 16, 25]
a = [1,2,3,4,5,6,7,8,9]
b = [i**2 for i in a if i%2==0]
print(b)
a = [1,2,3,4,5,6,7]
b = b + [i for i in a]
print(b)
2. DICTIONARY COMPREHENSION
Dictionary comprehensions are similar, with the additional requirement of defining a key.
• A dictionary comprehension is a compact way to process all or part of the elements
in a collection and return a dictionary as a results.
Syntax:
new_dict={key: value for key, value in iteration}
• When a dictionary comprehension is run, the resulting key-value pairs are inserted
into a new dictionary in the same order in which they were produced.
keys = [1,2,3,4,5]
values = ["appple","banana","oranges","pears","grapes"]
mydict = {x:y for (x,y) in zip(keys,values)}
print(mydict)
keys1 = [1,2,3,4,5]
mydict2 = {x:y**2 for (x,y) in zip(keys1,keys)}
print(mydict2)
3. SET COMPREHENSION
A set comprehension is almost exactly the same as a list comprehension in Python. The
difference is that set comprehensions make sure the output contains no duplicates.
• Create a set comprehension by using curly braces.
Syntax:
new_set={expression for member in iterable}
• expression is a call to a method,or any other valid expression that returns a value.
• member is the object or value in the list.
• iterable is a list,set or any other object that can return its elements one at a time.
list1 = [1,2,3,4,5,6,7,8,9]
myset = {i for i in list1 if i%2==0}
print(myset)
{8, 2, 4, 6}
{1, 4, 9, 16, 25}
list1 = [1,2,3,4,5,6,7,8,9]
s2 = {i for i in list1 if i%2!=0}
print(s2)
{1, 3, 5, 7, 9}
list1 = [1,2,3,4,5,6,7,8,9]
s3 = {str(i) for i in list1 }
print(s3)
{'7', '4', '6', '3', '5', '8', '2', '9', '1'}
range() Function in Python:
• The range() function returns the sequence of numbers between the given range.
• By default it starts from '0',and incremented by '1'(by default) and stops before a
given range.
• It ia a implicit function.
Syntax:
range(start,stop,step)
• start:start value of the sequence.
• stop:next value after the end value of sequence.
• step:the difference between the any two numbers in the sequence(integer value).
Programs:
for i in range(3):
print("hello")
hello
hello
hello
n = 0
for i in range(1,101):
n = n + i
print(n)
5050
n = 0
for i in range(1,101):
if i%2 == 0:
n = n + i
print(n)
2550
n = 0
for i in range(2,101,2):
n = n + i
print(n)
2550
#fizzbuszz
n = 0
for i in range(1,10):
if (i%3 == 0 and i%5 == 0):
print("fizzbuzz")
elif i%3 == 0:
print("fizz")
elif i%5 == 0:
print("buzz")
else :
print(i)
1
2
fizz
4
buzz
fizz
7
8
fizz
Zip Function:
Python’s zip() function is defined as zip(*iterables).The function takes in iterables as
arguments and returns an iterator. This iterator generates a series of tuples containing
elements from each iterable. zip() can accept any type of iterable, such as files, lists, tuples,
dictionaries, sets, and so on.
Characterstics:
• If you use zip() with n arguments, then the function will return an iterator that
generates tuples of length n.
• If you use zip(numbers, letters) to create an iterator that produces tuples of the
form (x, y). In this case, the x values are taken from numbers and the y values are
taken from letters.
• If you can call zip() with no arguments as well. In this case, you’ll simply get an
empty iterator.
a = ("1", "2", "2")
b = ("dane","lame", "bruce")
x = zip(a, b)
print(x)
for i in x:
print(i)
res = zip(l, v)
print(list(res))
2536083875376
l=[1,2,3,4]
print(len(l))
l=[True,False,False]
print(any(l))
True
print('Before call')
f()
print('After call')
Before call
Inside function
After call
Input In [5]
^
IndentationError: expected an indented block
def func():
pass
Argument Passing:
• passing data into a function.
Positional Arguments:
The way to pass arguments to a Python function is with positional arguments (also called
required arguments).
• In the function definition, you specify a comma-separated list of parameters inside
the parentheses.
• When the function is called, you specify a corresponding list of arguments.
• The parameters behave like variables that are defined locally to the function.
• When the function is called, the arguments that are passed are bound to the
parameters in order, as though by variable assignment. NOTE: We must specify the
same number of arguments in the function call as there are parameters in the
definition, and in exactly the same order.
def fun(**args):
print(args)
fun(a=10,b=7,c=4,d=4)
The arguments in the call and the parameters in the definition must agree not only in order but
in number as well.
def palin(a1):
b1 = a1[::-1]
if a1 == b1:
print(a1,": is a palindrome")
else:
print(a1,": is not a palindrome")
palin('hello')
def fun1(x,y):
print(x,y)
fun1(20,30)
fun1(30,20)
20 30
30 20
Keyword Arguments:
When you’re calling a function, you can specify arguments in the form <keyword>=<value>.
• <keyword> must match a parameter in the Python function definition.
def team(name, project):
print(name, "is working on an", project)
Referencing a keyword that doesn’t match any of the declared parameters generates an
exception.
def func(fname,lname,age):
print("Name:",fname,'.',lname)
print("Age:",age)
func(fname="dane",lname="t",size=20)
--------------------
TypeErrorTraceback (most recent call last)
Input In [7], in <cell line: 5>()
2 print("Name:",fname,'.',lname)
3 print("Age:",age)
----> 5 func(fname="dane",lname="t",size=20)
func(lname="t",age=19,fname="dane")
Name: dane . t
Age: 19
--------------------
TypeErrorTraceback (most recent call last)
Input In [12], in <cell line: 4>()
1 def team(name, project , pos):
2 print(name, "is working on an", project)
----> 4 team(project = "Edpresso", name = 'FemCode')
func("dane","t",age=19)
Name: dane . t
Age: 19
You've specified a keyword argument,there can't be any positional arguments to the right of it.
def func(fname,lname,age):
print("Name:",fname,'.',lname)
print("Age:",age)
func("dane",age=19,"t")
Input In [14]
func("dane",age=19,"t")
^
SyntaxError: positional argument follows keyword argument
Default Parameters:
If a parameter specified in a Python function definition has the form <name>=<value>, then
<value> becomes a default value for that parameter. Parameters defined this way are
referred to as default or optional parameters.
def func(fname,lname,age=19):
print("Name:",fname,'.',lname)
print("Age:",age)
func("dane","t")
Name: dane . t
Age: 19
func("dane",age=19,"t")
Input In [16]
def func(fname,lname="t",age):
^
SyntaxError: non-default argument follows default argument
return Statement:
A return statement in a Python function serves two purposes.
• It immediately terminates the function and passes execution control back to the
caller.
• It provides a mechanism by which the function can pass data back to the caller.
• NOTE:Statement after the return function can't be executed.
def add(a,b):
print(a,b)
return a+b
add(2,3)
2 3
def add(a,b):
return a+b
print(a,b)
add(2,3)
"return" statements don’t need to be at the end of a function. They can appear anywhere in a
function body, and even multiple times.
def add(a,b):
return a+b
print(add(2,3))
print(add(3,4))
5
7
When no return value is given, a Python function returns the special Python value None.
def func():
return
print(func())
None
if the function body doesn’t contain a return statement at all and the function falls off the end.
def func():
pass
print(func())
None
If multiple comma-separated expressions are specified in a return statement, then they’re
packed and returned as a tuple.
def func(a,b):
return a+b,a-b,a*b,a/b
func(3,2)
(5, 1, 6, 1.5)
(1, 2, 3, 4)
{'a': 1, 'b': 2}
Orbitory Concept:
• Python arbitrary arguments are used. In this, we use the asterisk (*) to denote this
method before the parameter in the function.
• Starred assignment must be in a tuple or list
def func():
a,b=5,10
return a+b,b-a,b*a,b/a
*x=func()
Input In [14]
*x=func()
^
SyntaxError: starred assignment target must be in a list or tuple
def func():
a,b=5,10
return a+b,b-a,b*a,b/a
[*x]=func()
print(x)
print(*x)
11
Local Scope:
• Every time you call a function, you’re also creating a new local scope.
• When the function returns, the local scope is destroyed and the names are forgotten.
def square(n):
res=n**2
print("Square of n :",res)
square(10)
Square of n : 100
Note: If you try to access result or base after the function call, then you get a NameError,
because these only exist in the local scope created by the call to function.
print(res)
----------------------------------------------------------------------
-----
NameError Traceback (most recent call
last)
Input In [18], in <cell line: 1>()
----> 1 print(res)
Global Scope:
• If you define a name at the top level of any Python module, then that name is
considered global to the program.
• There’s only one global Python scope per program execution. This scope remains in
existence until the program terminates and all its names are forgotten. Otherwise,
the next time you were to run the program, the names would remember their values
from the previous run.
• You can access or reference the value of any global name from any place in your
code. This includes functions and classes.
x=10
def func():
return x
func()
10
print(x)
10
----------------------------------------------------------------------
-----
UnboundLocalError Traceback (most recent call
last)
Input In [21], in <cell line: 4>()
2 def inc():
3 x+=1
----> 4 inc()
5 x
Input In [21], in inc()
2 def inc():
----> 3 x+=1
x=1
def inc():
global x
x+=1
inc()
Recursive function
• When you call a function in Python, the interpreter creates a new local namespace
so that names defined within that function don’t collide with identical names
defined elsewhere. One function can call another, and even if they both define
objects with the same name, it all works out fine because those objects exist in
separate namespaces.
• The same holds true if multiple instances of the same function are running
concurrently.
def factorial(x):
if x == 1:
return 1
else:
return (x * factorial(x-1))
num = 7
result = factorial(num)
print("The factorial of", num, "is", result)
Programs:
The function of an argument by surrounding the function and its argument with parentheses.
(lambda x:x+1)(2)
The object created by a lambda expression is a first-class citizen, just like a standard function or
any other object in Python. You can assign it to a variable and then call the function using that
name.
res=lambda x,y:x+y
res(2,3)
The implicit tuple packing doesn’t work with an anonymous lambda function:
(lambda x:x,x ** 2,x ** 3)(3)
----------------------------------------------------------------------
-----
NameError Traceback (most recent call
last)
Input In [19], in <cell line: 1>()
----> 1 (lambda x:x,x ** 2,x ** 3)(3)
But you can return a tuple from a lambda function. You just have to denote the tuple explicitly
with parentheses. You can also return a list or a dictionary from a lambda function.
(lambda x: (x, x ** 2, x ** 3))(3)
(3, 9, 27)
'even'
Arguments:
Like a normal function object defined with def, Python lambda expressions support all the
different ways of passing arguments.
• Positional arguments
(lambda x, y: x + y)(1, 2)
• Keyword arguments
(lambda x=1,y=2:x+y)()
Programs:
a = lambda x,y : x+y
print(a(1,5))
b = lambda x,y:x*y
print(b(4,3))
12
b = lambda x : x**2
print(b(5))
25
6
l1 = [1,2,3]
l2 = [2,3,6]
res = map(lambda x,y : x+y , l1,l2)
print(list(res))
[3, 5, 9]
def fun1(x):
return lambda x : x*2
myfun = fun1(3)
myfun(3)
def fun1(a):
return lambda x : x*a
myfun = fun1(4)
myfun(3)
12
HIGHER ORDER FUNCTIONS
• A function is said to be a higher order function if it contains other functions as a
parameter or returns a function as an output.
• filter()
Map:
• The built-in function map() takes a function as a first argument and applies it to
each of the elements of its second argument, an iterable. Examples of iterables are
strings, lists, and tuples.
• map() returns an iterator corresponding to the transformed collection.
words = ['hello','world']
upper = list(map(lambda n: n.upper(),words))
print(upper)
['HELLO', 'WORLD']
def rev(n):
return n[::-1]
l = ['hi','hello']
res = list(map(rev,l))
print(res)
['ih', 'olleh']
def func1(n):
for i in range(1,n+1):
p += i
return p
func1(4)
----------------------------------------------------------------------
-----
UnboundLocalError Traceback (most recent call
last)
Input In [4], in <cell line: 5>()
3 p += i
4 return p
----> 5 func1(4)
l1 = [1,2,3]
l2 = [4,5,6]
res = map(lambda x,y : x+y, l1, l2)
print((res))
print(list(res))
import math
l = [1.08,2.5,5.6,8.9]
res = map(lambda x : math.ceil(x),l)
print(list(res))
[2, 3, 6, 9]
Filter
• The built-in function filter(), another classic functional construct, can be converted
into a list comprehension.
• It takes a predicate as a first argument and an iterable as a second argument.
• It builds an iterator containing all the elements of the initial collection that satisfies
the predicate function.
[2, 4, 6]
stu = [12,31,4,45,34,57,16,132,45,3,2,512,1245,345]
print(stu)
def age_1(n):
if n < 19:
return False
else:
return True
for i in res:
print(i,end = ' ')
[12, 31, 4, 45, 34, 57, 16, 132, 45, 3, 2, 512, 1245, 345]
31 45 34 57 132 45 512 1245 345
Reduce
• reduce() has gone from a built-in function to a functools module function.Its first
two arguments are respectively a function and an iterable. It may also take an
initializer as a third argument that is used as the initial value of the resulting
accumulator.
• For each element of the iterable, reduce() applies the function and accumulates the
result that is returned when the iterable is exhausted.
l1 = [1,2,3,4,5]
print(res)
15
from functools import reduce
l2 = [100,123,1134,2344,45233,234,211,2434,345,2356]
print(maxi)
45233
Python Modules and packages
• Modular programming refers to the process of breaking a large, unwieldy
programming task into separate, smaller, more manageable subtasks or modules.
Individual modules can then be cobbled together like building blocks to create a
larger application.
Python Modules:
There are actually three different ways to define a module in Python:
• A module can be written in Python itself.
• A module can be written in C and loaded dynamically at run-time, like the re
(regular expression) module.
• A built-in module is intrinsically contained in the interpreter, like the itertools
module.
A module’s contents are accessed the same way in all three cases: with the import statement.
• we focus will mostly be on modules that are written in Python
All you need to do is create a file that contains legitimate Python code and then give the file
a name with a .py extension.
Syntax:
import <module_name>
• The statement import only places in the caller’s symbol table. The objects that are
defined in the module remain in the module’s private symbol table.
• From the caller, objects in the module are only accessible when prefixed with via
dot notation, as illustrated below.
Example:
File:
mod.py s = "If Comrade Napoleon says it, it must be right." a = [100, 200, 300] def foo(arg):
print(f'arg = {arg}')
class Foo: pass
• Assuming mod.py is in an appropriate location,these objects can be accessed by
importing the module as follows.
program:
import mod print(mod.s) output: If Comrade Napoleon says it, it must be right.
module1.py
import module1 as m
print(m.div(2,3))
print(m.add(2,3))
print(m.sub(2,3))
print(m.mul(2,3))
import sys
print(sys.path)
import math as mt
print(mt.sqrt(16))
print(mt.factorial(6))
import math
print("The value of pi is", math.pi)
Syntax:
from <module_name> import <name(s)>
Example:
File:
mod.py s = "If Comrade Napoleon says it, it must be right." a = [100, 200, 300] def foo(arg):
print(f'arg = {arg}')
class Foo: pass
• <name(s)> can be referenced in the caller’s environment without the prefix.
program:
from mod import s, foo s output: 'If Comrade Napoleon says it, it must be right.'
from math import *
print("The value of pi is", pi)
Python Packages:
Suppose you have developed a very large application that includes many modules. As the
number of modules grows, it becomes difficult to keep track of them all if they are dumped
into one location. This is particularly so if they have similar names or functionality. You
might wish for a means of grouping and organizing them.
• Packages allow for a hierarchical structuring of the module namespace using dot
notation. In the same way that modules help avoid collisions between global
variable names, packages help avoid collisions between module names.
creating a package:
• create a folder with specified name.
• Inside the folder create the python files which are used in the program.
Example:
• There is a directory named pkg that contains two modules, mod1.py and mod2.py.
mod1.py
def foo(): print('[mod1] foo()')
class Foo: pass
mod2.py
def bar(): print('[mod2] bar()')
class Bar: pass
• If the pkg directory resides in a location where it can be found (in one of the
directories contained in sys.path), you can refer to the two modules with dot
notation (pkg.mod1, pkg.mod2) and import them .
Syntax: import <module_name>[, <module_name> ...]
Program:
import pkg.mod1, pkg.mod2 pkg.mod1.foo() output: [mod1] foo()
mypackage
__init__.py
function.py
def sum(x,y):
return x+y
def average(x,y):
return (x+y)/2
def power(x,y):
return x**y
greet.py
def SayHello(name):
print("Hello ", name)
mypackage2
__init__.py
module1.py
def add(x, y):
return x + y
module2.py
def sub(x, y):
return x - y
module3.py
def mul(x, y):
return x * y
module4.py
def div(x, y):
return x / y
--------------------
ZeroDivisionErrorTraceback (most recent call last)
Input In [11], in <cell line: 2>()
1 number = 100
----> 2 divided_by_zero = number / 0
3 print(divided_by_zero)
number = 57
if number == 57:
print(57)
Input In [12]
print(57)
^
IndentationError: expected an indented block
str = "hello"
print(str + 1)
--------------------
TypeErrorTraceback (most recent call last)
Input In [10], in <cell line: 2>()
1 str = "hello"
----> 2 print(str + 1)
import module
--------------------
ModuleNotFoundErrorTraceback (most recent call last)
Input In [13], in <cell line: 1>()
----> 1 import module
l1 = [1,2,3,4]
print(l1[7])
--------------------
IndexErrorTraceback (most recent call last)
Input In [15], in <cell line: 2>()
1 l1 = [1,2,3,4]
----> 2 print(l1[7])
try:
even_numbers = [2,4,6,8]
print(even_numbers[5])
except ZeroDivisionError:
print("cant divide with zero")
except IndexError:
print("index out of bounds")
try:
even_numbers = [2,4,6,8]
print(even_numbers[2])
except ZeroDivisionError:
print("Denominator cannot be 0.")
except IndexError:
print("Index Out of Bound.")
else:
print("after handling")
6
after handling
try:
even_numbers = [2,4,6,8]
print(even_numbers[2])
except ZeroDivisionError:
print("Denominator cannot be 0.")
except IndexError:
print("Index Out of Bound.")
else:
print("after handling")
finally:
print("final statement")
6
after handling
final statement
Introduction to OOPS(Object Oriented Programming):
• Object-oriented programming is a programming paradigm that provides a means of
structuring programs so that properties and behaviors are bundled into individual
objects.
• OOP models real-world entities as software objects that have some data associated
with them and can perform certain functions.
• The key takeaway is that objects are at the center of object-oriented programming
in Python, not only representing the data, as in procedural programming, but in the
overall structure of the program as well.
Classes in Python
• Classes are used to create user-defined data structures. Classes define functions
called methods, which identify the behaviors and actions that an object created from
the class can perform with its data.
• for example a Dog class that stores some information about the characteristics and
behaviors that an individual dog can have.
Objects in Python
• It is a basic unit of Object-Oriented Programming and represents the real-life
entities.
• behavior
Class Attributes
• Class attributes are the variables defined directly in the class that are shared by all
objects of the class.
• Class attributes can be accessed using the class name as well as using the objects.
'ANITS'
Student.clg_Name
'ANITS'
Before Changing
ANITS
After Changing
Anil Neerukonda Institute of Technology and Sciences
Instance Methods
• Instance methods are functions that are defined inside a class and can only be called
from an instance of that class. Just like .__init__(), an instance method’s first
parameter is always self.
• Methods like init() and str() are called dunder methods because they begin and end
with double underscores. There are many dunder methods that you can use to
customize classes in Python.
Example
class Student:
def __init__(self): # constructor method
print('Constructor invoked')
std1 = Student()
Constructor invoked
std2 = Student()
Constructor invoked
Instance Attributes
• Instance attributes are attributes or properties attached to an instance of a class.
• Instance attributes are defined in the constructor.
Example
class Student:
clg_Name = 'ANITS' # class attribute
std = Student()
std.name
'xyz'
std.age
20
'Bill'
25
Setting attribute values using instance method
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
std = Student('Ram',23)
std.name
'Ram'
std.age
23
std = Student()
std.name
'Guest'
std.age
25
Class Methods
• one can define as many methods as you want in a class using the def keyword.
• Each method must have the first parameter, generally named as self, which refers to
the calling instance.
• Self is just a conventional name for the first argument of a method in the class.
• A method defined as mymethod(self, a, b) should be called as x.mymethod(a, b) for
the object x of the class.
class cla_method:
def __init__(self,x,y):
self.x=x
self.y=y
@classmethod
def square(cls,side):
return cls(side,side)
def display(self):
return self.x*self.y
obj=cla_method.square(10)
print(obj.display())
100
class Student:
def displayInfo(self): # class method
print('Student Information')
std = Student()
std.displayInfo()
Student Information
std = Student()
std.displayInfo()
Student Information
Defining a method in the class without the self parameter would raise an exception when
calling a method.
class Student:
def displayInfo(): # method without self parameter
print('Student Information')
std = Student()
std.displayInfo()
----------------------------------------------------------------------
-----
TypeError Traceback (most recent call
last)
Input In [39], in <cell line: 2>()
1 std = Student()
----> 2 std.displayInfo()
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
def displayInfo(self): # class method
print('Student Name: ', self.name,', Age: ', self.age)
Static method
• Static methods are special case of methods.
• Any functionality that belongs to a class,but that does not require the object to be
placed in the static method.
• They does not require any additional arguments as class method.They are just like
normal functions that belongs to a class.
• The static method is marked with the @staticmethod decorator.
• A Static method can be called either on the class or on an instance. Note:A Static
method does not depend on the state of the object.
import math
class Pizza:
def __init__(self, radius, ingredients):
self.radius = radius
self.ingredients = ingredients
def __repr__(self):
return (f'Pizza({self.radius!r}, '
f'{self.ingredients!r})')
def area(self):
return self.circle_area(self.radius)
@staticmethod
def circle_area(r):
return r ** 2 * math.pi
p=Pizza(4,['mozzarella','tomatoes'])
p.area()
50.26548245743669
----------------------------------------------------------------------
-----
AttributeError Traceback (most recent call
last)
Input In [43], in <cell line: 2>()
1 del std.name # deleting attribute
----> 2 std.name
----------------------------------------------------------------------
-----
NameError Traceback (most recent call
last)
Input In [44], in <cell line: 2>()
1 del std # deleting object
----> 2 std.name
----------------------------------------------------------------------
-----
NameError Traceback (most recent call
last)
Input In [45], in <cell line: 2>()
1 del Student # deleting class
----> 2 std = Student('Steve', 25)
Inheritance in python
• Inheritance is the process by which one class takes on the attributes and methods of
another. Newly formed classes are called child classes, and the classes that child
classes are derived from are called parent classes.
• Child classes can override or extend the attributes and methods of parent classes. In
other words, child classes inherit all of the parent’s attributes and methods but can
also specify attributes and methods that are unique to themselves.
Syntax
Class BaseClass: {Body} Class DerivedClass(BaseClass): {Body}`
Example
Syntax
class Superclass: # Class body... class Subclass(Superclass): # Class body...`
q1=quadriLateral(7,5,6,4)
q1.perimeter()
perimeter= 22
r1=rectangle(10, 20)
r1.perimeter()
perimeter= 60
Multiple Inheritance
• When a class can be derived from more than one base class this type of inheritance
is called multiple inheritances.
• In multiple inheritances, all the features of the base classes are inherited into the
derived class.
Syntax
class Superclass1: # Class body... class Superclass2: # Class body... ................... .... ....
class SuperclassN: # Class body... class Subclass(Superclass1, Superclass2,...,
SuperclassN): # Class body...`
s1 = smarthulk()
print(s1.smash(), "and", s1.speak())
• class smarthulk inherits from two parents classes, hulk and banner.
• So smarthulk will have all methods and attributes of both its parent classes.
• We then create an object s1 of class smarthulk and call the methods smash() and
speak() on it.
MultiLevel Inheritance
• When a class inherits a child class, it is called Multilevel Inheritance. - The class
which inherits the child class is called a grandchild class.
• Multilevel Inheritance causes grandchild and child relationships.
• The grandchild class has access to both child and parent class properties.
syntax
class Superclass: # Class body... class Subclass1(Superclass): # Class body... class
Subclass2(Subclass1): # Class body...`
PythonGeeks
Hierarchical Inheritance
• When multiple classes inherit the same class, it is called Hierarchical Inheritance.
Syntax
class Superclass: # Class body... class Subclass1(Superclass): # Class body... class
Subclass2(Superclass): # Class body... . . . class
SubclassN(Superclass): # Class body...`
class parent:
def __init__(self,regno,name):
self.regno = regno
self.name = name
def prn(self):
print("name: {} , regno : {}".format(self.name,self.regno))
p1 = parent("p1","parent")
p1.prn()
class child1(parent):
def __init__(self,regno,name):
parent.__init__(self,regno,name)
ch1 = child1("child1","c1")
ch1.prn()
class child2(parent):
def _init_(self,regno,name):
parent.__init__(self,regno,name)
ch2 = child2("child2","c2")
ch2.prn()
Operator Overloading
• In object-oriented programming, there exists this concept called “Polymorphism”.
• Polymorphism means “one action, many forms”.
• OOPS allows objects to perform a single action in different ways.
• One way of implementing Polymorphism is through operator overloading.
• Operator overloading is the process of using an operator in different ways
depending on the operands.
• You can change the way an operator in Python works on different data-types.
• Just think how the ‘+’ operator operates on two numbers and the same operator
operates on two strings.
• It performs “Addition” on numbers whereas it performs “Concatenation” on strings.
class Sum:
def __init__(self,x):
self.x = x
def __add__(self, other):
return self.x + other.x
b1 = Sum(20)
b2 = Sum(30)
b1+b2
50
s1 = Sum("First_Name")
s2 = Sum("Last_Name")
s1+s2
'First_NameLast_Name'
Encapsulation
• Encapsulation in Python describes the concept of bundling data and methods within
a single unit
• So, for example, when you create a class, it means you are implementing
encapsulation.
• A class is an example of encapsulation as it binds all the data members (instance
variables) and methods into a single unit.
class Computer:
def __init__(self):
self.__maxprice = 900
def sell(self):
print("Selling Price: {}".format(self.__maxprice))
def setMaxPrice(self, price):
self.__maxprice = price
c = Computer()
c.sell()
Polymorphism
• Polymorphism means multiple forms.
• In python we can find the same operator or function taking multiple forms.
Polymorphism in operators
• The + operator can take two inputs and give us the result depending on what the
inputs are.
• In the below examples we can see how the integer inputs yield an integer and if one
of the input is float then the result becomes a float.
• Also for strings, they simply get concatenated.
a = 23
b = 11
c = 9.5
s1 = "Hello"
s2 = "There!"
print(a + b)
print(type(a + b))
print(b + c)
print(type (b + c))
print(s1 + s2)
print(type(s1 + s2))
34
<class 'int'>
20.5
<class 'float'>
HelloThere!
<class 'str'>
#instantiate objects
blu = Parrot()
peggy = Penguin()
Function Overloading:
• The problem with method overloading in Python is that we may overload the
methods but can only use the latest defined method.
def mul(a,b):
return a*b
def mul(a,b,c):
return a*b*c
mul(2,3)
----------------------------------------------------------------------
-----
TypeError Traceback (most recent call
last)
Input In [9], in <cell line: 5>()
3 def mul(a,b,c):
4 return a*b*c
----> 5 mul(2,3)
mul(2,3,4)
24
To overcome method over loading in python we use method(By Using Multiple Dispatch
Decorator ).
from multipledispatch import dispatch
@dispatch(int,int)
def product(a,b):
return a*b
@dispatch(int,int,int)
def product(a,b,c):
return a*b*c
@dispatch(float,float,float)
def product(a,b,c):
return a*b*c
product(2,3)
product(2,3,4)
24
product(2.0,2.0,2.0)
8.0
Method overriding:
• Method overriding is an ability of any object-oriented programming language that
allows a child class to provide a specific implementation of a method that is already
provided by one of its parent classes.
• When a method in a childclass has the same name, same parameters or signature
and same return type as a method in its parentclass, then the method in the
childclass is said to override the method in the parentclass.
class Grandparent:
def home(self):
print("Iam the owner")
def age(self):
print("Iam 75 years old")
class Parent(Grandparent):
def age(self):
print("Iam 45 years old")
class Child(Parent):
def age(self):
print("Iam 25 years old")
c=Child()
c.home()
c.age()
super method:
• super() does much more than just search the parent class for a method or an
attribute. It traverses the entire class hierarchy for a matching method or attribute.
If you aren’t careful, super() can have surprising results.
class Parent:
def show(self):
print("Iam parent")
class Child(Parent):
def show(self):
super().show()
print("Iam child")
c=Child()
c.show()
Iam parent
Iam child
REGULAR EXPRESSION
• Regular expressions, also known as regexes, in Python. A regex is a special sequence
of characters that defines a pattern for complex string-matching functionality.
The re Module
• Regex functionality in Python resides in a module named re. The re module contains
many useful functions and methods.
Programs:
# period(.)
import re
txt = "hello planet"
x = re.findall("he..o", txt)
print(x)
['hello']
# (^)
import re
txt = "hello planet"
x = re.findall("^hello", txt)
if x:
print("Yes, the string starts with 'hello'")
else:
print("No match")
#$
import re
txt = "hello planet"
x = re.findall("planet$", txt)
if x:
print("Yes, the string ends with 'planet'")
else:
print("No match")
#[]
import re
txt = "The rain in Spain"
x = re.findall("[a-m]", txt)
print(x)
# +
import re
txt = "hello planet"
x = re.findall("he.+o", txt)
print(x)
['hello']
# *
import re
txt = "hello planet"
x = re.findall("he.*o", txt)
print(x)
['hello']
# ?
import re
txt = "hello planet"
x = re.findall("he.?o", txt)
print(x)
[]
# |
import re
txt = "The rain in Spain falls mainly in the plain!"
x = re.findall("falls|stays", txt)
print(x)
if x:
print("Yes, there is at least one match!")
else:
print("No match")
['falls']
Yes, there is at least one match!
Special Sequences:
Programs:
#\D
import re
txt = "The rain in Spain"
x = re.findall("\d", txt)
print(x)
if x:
print("Yes, there is at least one match!")
else:
print("No match")
[]
No match
#\w
import re
txt = "The rain in Spain"
x = re.findall("\w", txt)
print(x)
if x:
print("Yes, there is at least one match!")
else:
print("No match")
['T', 'h', 'e', 'r', 'a', 'i', 'n', 'i', 'n', 'S', 'p', 'a', 'i', 'n']
Yes, there is at least one match!
#\W
import re
txt = "The rain in Spain"
x = re.findall("\w", txt)
print(x)
if x:
print("Yes, there is at least one match!")
else:
print("No match")
['T', 'h', 'e', 'r', 'a', 'i', 'n', 'i', 'n', 'S', 'p', 'a', 'i', 'n']
Yes, there is at least one match!
#\s
import re
txt = "The rain in Spain"
x = re.search("\s", txt)
print("The first white-space character is located in position:",
x.start())
#\S
import re
txt = "The rain in Spain"
x = re.findall("\S", txt)
print(x)
if x:
print("Yes, there is at least one match!")
else:
print("No match")
['T', 'h', 'e', 'r', 'a', 'i', 'n', 'i', 'n', 'S', 'p', 'a', 'i', 'n']
Yes, there is at least one match!
#\b
import re
txt = "The rain in Spain"
x = re.findall(r"\bain", txt)
print(x)
if x:
print("Yes, there is at least one match!")
else:
print("No match")
[]
No match
#\ B
import re
txt = "The rain in Spain"
x = re.findall(r"\Bain", txt)
print(x)
if x:
print("Yes, there is at least one match!")
else:
print("No match")
['ain', 'ain']
Yes, there is at least one match!
re.compile(pattern, flags=0)
• (Compile a regular expression pattern into a regular expression object, which can be
used for matching using its match(),search() and other methods, described below.)
import re
p = re.compile('[a-e]')
import re
txt = "The rain in Spain"
x = re.search("Portugal", txt)
print(x)
None
email = '[email protected]'
pattern = r'[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}'
match = re.fullmatch(pattern, email)
['ai', 'ai']
s = 'Readability counts.'
pattern = r'[aeoui]'
matches = re.finditer(pattern, s)
for match in matches:
print(match)
The9rain9in9Spain
Other programs:
import re
Start Index: 13
End Index: 19
import re
p = re.compile('[a-e]')
print(p.findall("the number of ovels in this sentence"))