0% found this document useful (0 votes)
125 views

Python Record

This certificate certifies that K DHARANEESWARI, a student with register number 321126510L03 studying in the III/IV year of the Computer Science and Engineering branch at ANIL NEERUKONDA INSTITUTE OF TECHNOLOGY & SCIENCES, has completed 15 experiments in the subject of Essentials of Python during the academic year 2022-23 under the guidance of the Lecturer-in-Charge and Head of the Department.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
125 views

Python Record

This certificate certifies that K DHARANEESWARI, a student with register number 321126510L03 studying in the III/IV year of the Computer Science and Engineering branch at ANIL NEERUKONDA INSTITUTE OF TECHNOLOGY & SCIENCES, has completed 15 experiments in the subject of Essentials of Python during the academic year 2022-23 under the guidance of the Lecturer-in-Charge and Head of the Department.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 101

ANIL NEERUKONDA INSTITUTE OF

TECHNOLOGY & SCIENCES


(AUTONOMOUS)
(Affiliated to AU Approved by AICTE & Accredited by NBA & NAAC with ‘A’ Grade)
SANGIVALASA – 531162, BHEEMUNIPATNAM MANDAL , Visakhapatnam Dist.
Phone:08933-225083/84/87 Fax:226395

CERTIFICATE

This is to certify that K DHARANEESWAR is a student


studying III/IV register No. 321126510L03
branch Computer Science and Engineering has
done 15 no. of experiments during the year 2022-23
in the subject Essentials of Python .

Lecturer in-Charge Head of the Department


Variable Assignment:-
in python we need not explicitly declare variables,the declaration is done automatically
when a value is assigned,to the variable using the equal(=) sign.operand on the left is the
name of the variable,and the operand on the right is the value to be stored in the
variable.the value assigned can be of any data type.In python we can assign boolean values
to a variable.Assignment of variables can be done in two ways:
• normal assignment:this is normal assignment of values which we normally do in a
program.
• multiple assignment:python allows programmers to assign a single value to more
than variable at a time ,we can also assign different values to different variables at a
time.
a = 5
b = 5
print(a,b)

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.

id() and type():-


the id function returns the refence id in which the data is mapped to. the type funtion
returns the datatype class of the variable whether it is string,list,tuple or etc.
a = 10
print(id(a))
print(type(a))
b = 'str'
print(id(b))
print(type(b))
c = {}
print(type(c))

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

types of arithematic operators:


Operator Name Description
+ Addition adds values on the either side of the
operator
- Subtraction Subtracts the right oprator from the left
* Multiplicatio multiply values on the either side of the
n operator
/ Division divides the left hand operand with the
right hand operand
% Modulus gives the remainder after divison
** Exponent performs the exponential calculations of
the operands
// Floor gives the result removing the decimal
Division places i.e the exact quotient is given
a,b = 5,8
print(a+b)
print(a-b)
print(a*b)
print(a/b)
print(a%b)
print(a**b)

13
-3
40
0.625
5
390625
2.Assignment Operators:-
Assignment operators are used to assign values to variables

types of assignment operators:


Operator Description
= value on the right hand side gets assigned to the
left handside
+= the value on the RHS gets added to LHS and gets
assigned to LHS
-= the value on the RHS gets subtracted from the LHS
and gets assigned to the LHS
*= the value on the RHS gets multiplied with RHS and
gets assigned to the LHS
/= the value on the LHS gets divided by RHS and the
result will be stored in LHS
%= the value on the LHS gets divide by RHS and the
remainder gets assigned to LHS
**= exponential takes place and the value gets
assigned to LHS
//= the value of LHS gets divided by RHS and the floor
value gets assigned to LHS
a = 21
b = 10
c = 0
c = a + b
print(c)
c += a
print(c)
c *= a
print(c)
c /= a
print(c)
c %= a
print(c)
c **= a
print(c)
c //= a
print(c)

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

Operator Name Description


and logical AND returns true only if all the expressions
are true
or logical OR returns true if either of the expression is
true
not logical NOT it takes a single expression and returns
true if thr expression is false and vice
versa
a,b = 11,23
print(a and b)
print(a or b)
print(not b)

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.

Python has 5 key Conditional Statements that you should know:


•if statements •if-else statements •elif statements •Nested if and if-else Statements •elif
ladder

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

height = int(input("enter a your height in cm "))


age = int(input("enter a your age "))
if height > 120 :
print("you are eligible for riding rollercoaster")
if age > 18 :
print("pay full price $20")
else :
print("pay only half price $10")
else :
print("not eligible for riding rollercoaster")

enter a your height in cm 34


enter a your age 23
not eligible for riding rollercoaster

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")

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

Nested if-else statements:


• If <\expr> is true,the it check for the inner if <\expr>,if it is true the first suite is
executed, and the second is skipped. if inner <\expr> is false, the inner suite is
executed ,otherwise outer suite is executed.
• Every suites are defined by indentation.

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')

choice = int( input() )

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!')

Select your ride:


1. Bike
2. Car
3. SUV
3
You have selected SUV

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.

Types of Looping statements:


1.for loop 2.for-else 3.while 4.while-else

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")

this is while loop


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

for number in range(10):


if number == 5:
break

print('Number is ' + str(number))

print('Out of loop')

Number is 0
Number is 1
Number is 2
Number is 3
Number is 4
Out of loop

numbers = [10, 40, 120, 230]


for i in numbers:
if i > 100:
break
print('current number', i)

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

for number in range(10):


if number == 5:
continue # continue here
print('Number is ' + str(number))

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

numbers = [2, 3, 11, 7]


for i in numbers:
print('Current Number is', i)
if i > 10:
continue
square = i * i
print('Square of a current number is', square)

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

for number in range(10):


if number == 5:
pass # pass here

print('Number is ' + str(number))

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

for number in range(1, 10):


if number % 2 != 0:
pass
else:
print(f'{number} is a multiple of 2')

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".

Characteristics of Python string:


• Strings are immutable.
• String can contains any arbitrary objects.

Strings are immutable.


s="abc"
s[1]="2"
s

----------------------------------------------------------------------
-----
TypeError Traceback (most recent call
last)
Input In [10], in <cell line: 2>()
1 s="abc"
----> 2 s[1]="2"
3 s

TypeError: 'str' object does not support item assignment

String can contains any arbitrary objects.


s="a123bc[1,2]"
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")

['a', 'arakada', 'ra']

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'

Indexing and slicing:


s="abarakadabra"
print(s[2])

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.

Characteristics of Python list:


• Lists are ordered.
• Lists can contain any arbitrary objects.
• List elements can be accessed by index.
• Lists can be nested to arbitrary depth.
• Lists are mutable.
• Lists are dynamic.

Lists are ordered.


The order in which you specify the elements when you define a list is an innate
characteristic of that list and is maintained for that list’s lifetime.
a=[1,2,3]
b=[3,2,1]
a==b
False

Lists can contain any arbitrary objects


A list can contain any number of objects, from zero to as many as your computer’s memory
will allow.The elements of a list can all be the same type Or varying types.List objects
needn’t be unique. A given object can appear in a list multiple times.
l=[1,2,"hello",[1,2]]
l

[1, 2, 'hello', [1, 2]]

List elements can be accessed by index(Both positive and negative indexing).


Individual elements in a list can be accessed using an index in square brackets. This is
exactly accessing an individual characters in a string and it is zero-based indexing.

## 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]

You can specify a stride—either positive or negative:


l=['a','b','c','d']
print(l[0:4:2])
print(l[4:0:-2])

['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

Lists can be nested to arbitrary depth.


A list can contain sublists, which in turn can contain sublists themselves, and so on to
arbitrary depth.
x=['a',['bb',['ccc','ddd'],'ee','ff'],'g',['hh','ii'],'j']
x

['a', ['bb', ['ccc', 'ddd'], 'ee', 'ff'], 'g', ['hh', 'ii'], 'j']

print(x[1])
print(x[1][1])
['bb', ['ccc', 'ddd'], 'ee', 'ff']
['ccc', 'ddd']

Lists are mutable.


Once a list has been created, elements can be added, deleted, shifted, and moved around at
will. Python provides a wide range of ways to modify lists.
a=[1,2,3]
print(id(a))
a+=[4,5]
print(id(a))

1530918151168
1530918151168

Lists are dynamic.


When items are added to a list, it grows as needed:
a=[1,2,3]
a+=a
a

[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)

[1, 22, 33, 55]

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]

Some other operations:

del:
l=[1,2,3,4]
del l[1]
l

[1, 3, 4]

Concatenation:
l1=[1,2,3]
l2=['a','b','c']
l1+l2

[1, 2, 3, 'a', 'b', 'c']

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.

Characteristics of python tuple:


• Tuple are ordered.
• Tuple are immutable.
• Tuple allows duplications.

Tuple are ordered.


a=(1,2,3)
b=(3,2,1)
a==b

False

Tuple are immutable.


a=(1,2,3)
print(id(a))
a+=(4,5)
print(id(a))

1530919309376
1530920066800

Tuple allows duplication.


a=('a','b','b','a')
a

('a', 'b', 'b', 'a')

Tuple Assignment, Packing, and Unpacking.


t=('a','b','c','d')

(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)

Some other operations:

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)

NameError: name 't' is not defined

Concatenation:
t1=(1,2,3)
t2=('a','b','c')
t1+t2

(1, 2, 3, 'a', 'b', 'c')

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.

Characteristics of python set:


• Set are unordered.
• Set are mutable.
• Set elements are unique.Duplication are not allowed.
• A set itself may be modified, but the elements contained in the set must be of an
immutable type.

Set are unordered.


s={'a','b','c','d'}
print(s)

{'a', 'd', 'b', 'c'}

Set are mutable.


s={1,2,3,[1,2]}
s

----------------------------------------------------------------------
-----
TypeError Traceback (most recent call
last)
Input In [146], in <cell line: 1>()
----> 1 s={1,2,3,[1,2]}
2 s

TypeError: unhashable type: 'list'

Set don't allow duplication.


s1={1,2,3,1,2,3}
print(s)

{1, 2, 3}

Set Size and Membership


x={1,2,3}
print(len(x))
print(1 in x)

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

TypeError: set.discard() takes exactly one argument (0 given)

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

TypeError: set.pop() takes no arguments (1 given)

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

TypeError: set.remove() takes exactly one argument (0 given)

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

TypeError: 'int' object is not iterable

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({'a', 'b', 'c'})

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({'a', 'b', 'c'})

Exception while changing the frozen objects.


l=[1,2,3]
f=frozenset(l)
print(f)
f[1]=0

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

TypeError: 'frozenset' object does not support item assignment

we can use operators instead of some methods:

Programs using operators on sets:


##using '|'operator
s={1,2,3}
s1={3,4,5}
s|s1

{1, 2, 3, 4, 5}

##using " &" operator


s={1,2,3}
s1={3,4,5}
s&s1

{3}

## using '-' operator


s={1,2,3,4,5,6}
s1={4,5,6,7,8,9}
s-s1

{1, 2, 3}

## using '^' operator


s={1,2,3,4,5,6}
s1={4,5,6,7,8,9}
s^s1

{1, 2, 3, 7, 8, 9}

##using '<=' operator


s={1,2,3,4,5,6}
s1={4,5}
s1<=s

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.

Characteristics of python dictionary:


• Keys must be unique.
• Keys must be immutable.
• Dictionaries are mutable

Keys must be unique.


d={1:'a',2:'b'}
d

{1: 'a', 2: 'b'}

d={1:'a',1:'b'}
d

{1: 'b'}

Keys must be immutable.


d = {[1, 1]: 'a', [1, 2]: 'b', [2, 1]: 'c', [2, 2]: 'd'}
d

----------------------------------------------------------------------
-----
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

TypeError: unhashable type: 'list'

Dictionaries are mutable.


d={1:'a',2:'b'}
d[2]='c'
d

{1: 'a', 2: 'c'}


Accessing Dictionary Values.
d={1:10,2:20,3:30}
d[1]

10

Restrictions on Dictionary Keys.


d = {(1, 1): 'a', (1, 2): 'b', (2, 1): 'c', (2, 2): 'd'}
d[(1,2)]

'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]]

TypeError: unhashable type: 'list'

Restrictions on Dictionary Values.


d = {0: 'a', 1: 'a', 2: 'a', 3: 'a'}
print(d)
d[0]==d[1]

{0: 'a', 1: 'a', 2: 'a', 3: 'a'}

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

{'a': 10, 'b': 20, 'c': 30}

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()

dict_items([('a', 10), ('b', 20), ('c', 30)])

keys():
d = {'a': 10, 'b': 20, 'c': 30}
d.keys()

dict_keys(['a', 'b', 'c'])

values():
d = {'a': 10, 'b': 20, 'c': 30}
d.values()

dict_values([10, 20, 30])

pop():
d={1:10,2:20,3:30,4:40}
d.pop(1)
d

{2: 20, 3: 30, 4: 40}

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)

{1: 10, 2: 20, 3: 30}

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

TypeError: dict.popitem() takes no arguments (1 given)

update():
d1={'a':1,'b':2,'c':3}
d2={'d':4,'e':5}
d1.update(d2)
print(d1)

{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}

Built-in function in list,tuple,set and dict:

Perform built-in functions using any of the sequence:

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))

(50, 20, 30, 40, 10)


[50, 20, 30, 40, 10]

##linear search using list


l=list((input()))
i=0
c=0
key=input()
for i in range(len(l)):
if l[i]==key:
c=1
break
if c==1:
print("found")
else:
print("not found")
l

1234
1
found

['1', '2', '3', '4']

## find kth min and kth max element


l=list(map(int,input()))
k=int(input())
s=set(l)
l=list(s)
print(l)

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)

['apple', 'banana', 'mango']

fruits = ["apple", "banana", "cherry", "kiwi", "mango"]

n = [i for i in fruits if "a" in i]

print(n)

['apple', 'banana', 'mango']

Using Conditional Logic(Before the closing brackets):


new_list=[expression for member in iterable (if conditional)]
• The most common way to add conditional logic to a list comprehension is to add a
condition to the end of the expression.
• Conditionals are important because they allow list comprehensions to filter out
unwanted values.
a = [1,2,3,4,5,6,7,8,9]
b = [i for i in a if i%2==0]
print(b)

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)

[4, 16, 36, 64]


[4, 16, 36, 64, 1, 2, 3, 4, 5, 6, 7]

Using Conditional Logic(Near the begining of the expression):


new_list = [expression (if conditional) for member in iterable]
• Conditional logic to select from multiple possible output options.
• It will returns the boolean values as output.
xs = [22, 13, 45, 50, 98, 69, 43, 44, 1]
[x+1 if x >= 45 else x+5 for x in xs]

[27, 18, 46, 51, 99, 70, 48, 49, 6]

xs = [22, 13, 45, 50, 98, 69, 43, 44, 1]


[x+10 if x >= 20 else x+5 for x in xs]

[32, 18, 55, 60, 108, 79, 53, 54, 6]

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)

{1: 'appple', 2: 'banana', 3: 'oranges', 4: 'pears', 5: 'grapes'}

keys1 = [1,2,3,4,5]
mydict2 = {x:y**2 for (x,y) in zip(keys1,keys)}
print(mydict2)

{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

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)

s1 = {i**2 for i in [1,2,3,4,5]}


print(s1)

{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)

<zip object at 0x000001C152BABB00>


('1', 'dane')
('2', 'lame')
('2', 'bruce')

l = ['Java', 'Python', 'JavaScript']


v = [14, 3, 6]

res = zip(l, v)
print(list(res))

[('Java', 14), ('Python', 3), ('JavaScript', 6)]

books = ['book1', 'book2','book3']


prices = [2175, 1127, 2750]

new_dict = {books: prices for bookss,


prices in zip(books, prices)}
print(new_dict)
FUNCTIONS
Function is a self-contained block of code that encapsulates a specific task or related group
of tasks.
• We know some of the built-in functions provided by Python like
id(),len(),type(),any().... -For Example:
• id() takes one argument and returns that object’s unique integer identifier.
• len() returns the length of the argument passed to it.
• any() takes an iterable as its argument and returns True if any of the items in the
iterable are truthy and False otherwise.
• Each of these built-in functions performs a specific task. The code that accomplishes
the task is defined somewhere, but you don’t need to know where or even how the
code works.
s="PYTHON"
print(id(s))

2536083875376

l=[1,2,3,4]
print(len(l))

l=[True,False,False]
print(any(l))

True

All we need to know about function's interface:


If we call the function and pass the appropriate arguments. Program execution goes off to
the designated body of code. When the function is finished,the function may or may not
return data from code based on the code written.
• When we define our own Python function, it works just the same. From our code,
we’ll call our Python function and program execution will transfer to the body of
code that makes up the function.when the function is finished,data may be passed in
when the function is called, and return values may be passed back when it finishes.

Syntax for defining a Python function:


def ([<parameters>]):     <statement(s)> Components of the definition:
• def:The keyword that informs Python that a function is being defined.
• <function_name> :A valid Python identifier that names the function.
• <parameters>:An optional, comma-separated list of parameters that may be passed
to the function.
• " : " Punctuation that denotes the end of the Python function header (the name and
parameter list).
• <statement(s)>:A block of valid Python statements. The final item, <statement(s)>, is
called the body of the function. The body is a block of statements that will be
executed when the function is called. The body of a Python function is defined by
indentation in accordance with the off-side rule.

Syntax for calling a Python function:


<function_name>([<arguments>])
• <arguments> are the values passed into the function.They correspond to the
<parameters> in the Python function definition. NOTE:
• You can define a function that doesn’t take any arguments, but the parentheses are
still required.
• Both a function definition and a function call must always include parentheses, even
if they’re empty.
def f():
s = 'Inside function'
print(s)

print('Before call')
f()
print('After call')

Before call
Inside function
After call

Defining an empty function that does nothing.


• Block in a control structure can’t be empty, neither can the body of a function.
• To define a a empty function, use the pass statement:
def func():

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)

{'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')

hello : is not a palindrome

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)

team(project = "Edpresso", name = 'FemCode')


FemCode is working on an Edpresso

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)

TypeError: func() got an unexpected keyword argument 'size'

keyword arguments lifts the restriction on argument order.


• Each keyword argument explicitly designates a specific parameter by name, so you
can specify them in any order .
def func(fname,lname,age):
print("Name:",fname,'.',lname)
print("Age:",age)

func(lname="t",age=19,fname="dane")

Name: dane . t
Age: 19

The number of arguments and parameters must still match.


def team(name, project , pos):
print(name, "is working on an", project)

team(project = "Edpresso", name = 'FemCode')

--------------------
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')

TypeError: team() missing 1 required positional argument: 'pos'

Using Both Positional and Keyword arguments:


• When positional and keyword arguments are both present, all the positional
arguments must come first.
def func(fname,lname,age):
print("Name:",fname,'.',lname)
print("Age:",age)

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

If a non-default argument follows default argument then it raise an error:


def func(fname,lname="t",age):
print("Name:",fname,'.',lname)
print("Age:",age)

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)

Tuple packing:When a parameter name in a Python function definition is preceded by an


asterisk (*), it indicates argument tuple packing.
def func(*args):
return args
func(1,2,3,4)

(1, 2, 3, 4)

Dictinary packing: Preceding a parameter in a Python function definition by a double asterisk


(**) indicates that the corresponding arguments, which are expected to be key=value pairs,
should be packed into a dictionary:
def func(**args):
return args
func(a=1,b=2)

{'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)

[15, 5, 50, 2.0]


15 5 50 2.0
Nested function:
Inner functions, also known as nested functions, are functions that you define inside other
functions. In Python, this kind of function has direct access to variables and names defined
in the enclosing function.
• A common use case of inner functions arises when you need to protect, or hide, a
given function from everything happening outside of it so that the function is totally
hidden from the global scope. This kind of behavior is commonly known as
encapsulation.
def increment(number):
def inner_increment():
return number+1
return inner_increment()
increment(10)

11

Understanding scope of an variable:


• The scope of a name or variable depends on the place in your code where you create
that variable.
• The scope of a name defines the area of a program in which you can unambiguously
access that name, such as variables, functions, objects, and so on. A name will only
be visible to and accessible by the code in its scope. Commonly there are two
general types:
• Global Scope: The names that you define in this scope are available to all your code.
• Local scope: The names that you define in this scope are only available or visible to
the code within the scope.

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)

NameError: name 'res' is not defined

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

Making local variables as global variables using "global" Keyword:


• If we need to modify a variable that isn’t defined in a function but is defined in the
global scope, then you’ll need to use the global keyword. This works by specifying in
the function which variables need to be pulled into the function from the global
scope.
• syntax:
global <variable>
x=1
def inc():
x+=1
inc()
x

----------------------------------------------------------------------
-----
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

UnboundLocalError: local variable 'x' referenced before assignment

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)

The factorial of 7 is 5040

Programs:

GCD OF TWO NUMBERS USING FUNCTION


def gcd(a,b):
while b!=0:
a,b = b,a%b
print(a,b)
return a
print(gcd(24,36))

FACTORIAL OF TWO NUMBERS USING FUNCTIONS


def fact(n):
pro = 1
for i in range(1,n+1):
pro = pro*i
print(n+1-i,end='*')
return pro
fact(7)
LAMBDA FUNCTIONS
• Python Lambda Functions are anonymous function means that the function that
does not have a name.

syntax of a lambda expression:


lambda <parameter_list>: <expression>
• lambda -- The keyword that introduces a lambda expression
• <parameter_list -- An optional comma-separated list of parameter names
• : --Punctuation that separates from <expression>.
• <expression> --An expression usually involving the names in <parameter_list> The
value of a lambda expression is a callable function, just like a function defined with
the def keyword. It takes arguments, as specified by , and returns a value, as
indicated by <expression>.

The function of an argument by surrounding the function and its argument with parentheses.
(lambda x:x+1)(2)

• Above function can be evaluted as follows: (lambda x: x + 1)(2) = lambda 2: 2 + 1  


              =2+1                =3
(lambda x,y:x+y)(2,3)

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)

<>:1: SyntaxWarning: 'tuple' object is not callable; perhaps you


missed a comma?
<>:1: SyntaxWarning: 'tuple' object is not callable; perhaps you
missed a comma?
C:\Users\akhil\AppData\Local\Temp\ipykernel_8868\3644221584.py:1:
SyntaxWarning: 'tuple' object is not callable; perhaps you missed a
comma?
(lambda x:x,x ** 2,x ** 3)(3)
C:\Users\akhil\AppData\Local\Temp\ipykernel_8868\3644221584.py:1:
SyntaxWarning: 'tuple' object is not callable; perhaps you missed a
comma?
(lambda x:x,x ** 2,x ** 3)(3)
C:\Users\akhil\AppData\Local\Temp\ipykernel_8868\3644221584.py:1:
SyntaxWarning: 'tuple' object is not callable; perhaps you missed a
comma?
(lambda x:x,x ** 2,x ** 3)(3)
C:\Users\akhil\AppData\Local\Temp\ipykernel_8868\3644221584.py:1:
SyntaxWarning: 'tuple' object is not callable; perhaps you missed a
comma?
(lambda x:x,x ** 2,x ** 3)(3)
C:\Users\akhil\AppData\Local\Temp\ipykernel_8868\3644221584.py:1:
SyntaxWarning: 'tuple' object is not callable; perhaps you missed a
comma?
(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)

NameError: name 'x' is not defined

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)

Lamda function using conditional statements:

using if-else in lambda function


• The lambda function will return a value for every validated input based on the
condition. Syntax: lambda <arguments> : <statement1> if <condition> else
<statement2>
• Here, if block will be returned when the condition is true, and else block will be
returned when the condition is false.
(lambda x:"even" if x%2==0 else "odd")(2)

'even'

Using if else & elif in lambda function


• We can also use nested if, if-else in lambda function. Syntax: lambda <args> :
<statement1> if <condition> (<statement2> if <condition> else <statement3>)
• Here, statement1 will be returned when if the condition is true, statement2 will be
returned when elif true, and statement3 will be returned when else is executed.
res=lambda x,y : f'{x} is smaller than {y}' if x<y else (f'{x} is
greater than {y}' if x>y else f'{x} is equal to {y}')
res(2,3)

'2 is smaller than 3'

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)()

• Variable list of positional arguments


(lambda *args: sum(args))(1,2,3)

• Variable list of keyword arguments


(lambda **kwargs: sum(kwargs.values()))(one=1, two=2, three=3)

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

x = lambda a,b,c : a+b+c


x(1,2,3)

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.

Some Higher-order functions are like


• map()

• filter()

• functools.reduce() can be converted to more elegant forms with slight twists of


creativity, in particular with list comprehensions or generator expressions.

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.

Syntax for calling map():


map(<f>, <iterable>)
• map(, ) returns in iterator that yields the results of applying function to each
element of .
letters = ['h','e','l','l','o']
upper = list(map(lambda n: n.upper(),letters))
print(upper)

['H', 'E', 'L', 'L', 'O']

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)

Input In [4], in func1(n)


1 def func1(n):
2 for i in range(1,n+1):
----> 3 p += i
4 return p

UnboundLocalError: local variable 'p' referenced before assignment

l1 = [1,2,3]
l2 = [4,5,6]
res = map(lambda x,y : x+y, l1, l2)
print((res))
print(list(res))

<map object at 0x000001CF8155CCD0>


[5, 7, 9]

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.

Syntax for calling filter():


filter(<f>, <iterable>)
• filter(<f>, <iterable>) applies function <f> to each element of <iterable> and returns
an iterator that yields all items for which <f> is truthy. Conversely, it filters out all
items for which <f> is falsy.
nums = [1,2,3,4,5,6,7]

fil_nums = filter(lambda x: x%2 == 0, nums)


print(list(fil_nums))

[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

res = filter(age_1, stu)

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.

Syntax for calling reduce():


reduce(<f>, <iterable>)
• reduce(<f>, <iterable>) uses <f>, which must be a function that takes exactly two
arguments, to progressively combine the elements in <iterable>. To start, reduce()
invokes <f> on the first two elements of <iterable>. That result is then combined
with the third element, then that result with the fourth, and so on until the list is
exhausted. Then reduce() returns the final result.
from functools import reduce

l1 = [1,2,3,4,5]

res = reduce(lambda x,y: x+y,l1)

print(res)

15
from functools import reduce

l2 = [100,123,1134,2344,45233,234,211,2434,345,2356]

maxi = reduce(lambda x,y: x if x > y else y,l2)

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

def add(x, y):


return x + y
def sub(x, y):
return x - y
def mul(x, y):
return x * y
def div(x, y):
return x / y

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)

from math import sqrt, factorial


print(sqrt(16))
print(factorial(6))

from math import *


print(sqrt(16))
print(factorial(6))

import math as mt
print(mt.sqrt(16))
print(mt.factorial(6))

import math
print("The value of pi is", math.pi)

['C:\\Users\\dhara\\Downloads', 'G:\\anaconda\\python39.zip', 'G:\\


anaconda\\DLLs', 'G:\\anaconda\\lib', 'G:\\anaconda', '', 'G:\\
anaconda\\lib\\site-packages', 'G:\\anaconda\\lib\\site-packages\\
win32', 'G:\\anaconda\\lib\\site-packages\\win32\\lib', 'G:\\
anaconda\\lib\\site-packages\\Pythonwin']
4.0
720
4.0
720
4.0
720
The value of pi is 3.141592653589793
An alternate form of the import statement allows individual objects from the module to be
imported directly into the caller’s symbol table.

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)

from math import *


print(pi)
print(factorial(6))

The value of pi is 3.141592653589793


3.141592653589793
720

from calculation import add


print(add(1,2))

from calculation import *


print(add(1,2))
print(sub(3,2))

import calculation as cal


print(cal.add(1,2))

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)

from mypackage import functions


functions.power(3,2)

from mypackage.functions import sum


sum(10,20)

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

from mypackage2 import module1


print(module1.div(2,3))
print(module.add(2,3))
print(module1.sub(2,3))
print(module.mul(2,3))
Errors and Exception Handling:-
Errors are the problems in a program due to which the program will stop the execution. On
the other hand, exceptions are raised when some internal events occur which changes the
normal flow of the program. Two types of Error occurs in python.
• Syntax Errors
• Logical Errors/Exceptions
Under logical errors we have different types of errors like:
• NameError
• IndentationError
• TypeError
• ModuleNotFoundError
• FileNotFoundError
• AttributeError
• KeyError
• ValueError
• IndexError
• KeyError
• ZeroDivisionError
number = 100
divided_by_zero = number / 0
print(divided_by_zero)

--------------------
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)

ZeroDivisionError: division 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)

TypeError: can only concatenate str (not "int") to str

import module

--------------------
ModuleNotFoundErrorTraceback (most recent call last)
Input In [13], in <cell line: 1>()
----> 1 import module

ModuleNotFoundError: No module named '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])

IndexError: list index out of range

The errors or the exceptions can be handled by using the following:


• try:
• except:
• except as:
• else:
• finally: ** syntax errors cannot be handled by using the above statements
try:
a = 10
b = 0
res = a/b
print(res)
except:
print("Error: division with zero")

Error: division with zero

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")

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.

Syntax for defining a class


• All class definitions start with the class keyword, which is followed by the name of
the class and a colon. Any code that is indented below the class definition is
considered part of the class’s body.
class <ClassName>:     <statement1>     <statement2>     .     .     <statementN>`
• Note: Python class names are written in CapitalizedWords notation by convention.

Objects in Python
• It is a basic unit of Object-Oriented Programming and represents the real-life
entities.

• An Object is an instance of a Class.

• When a class is defined, no memory is allocated but when it is instantiated (i.e. an


object is created) memory is allocated.

• An object has an identity, state, and behavior.

• Each object contains data and code to manipulate the data.

An Object has two CharacterCharacteristics


• attributes

• behavior

Syntax for creating an object


<ObjectName> = <ClassName>()
Creating a class without any Members
• The following example defines an empty class using the pass keyword.

Example : Defining a python class


class Student:
pass

Example :Creating an Object for a class


std = Student()

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.

Example for class attribute


class Student:
clg_Name = 'ANITS'

• Above, the clg_Name is a class attribute defined inside a class.


• The value of the clg_Name will remain the same for all the objects unless modified
explicitly.

Accessing a class attribute


• We can access a class attribute in two ways.They are
• object name dot class attribute
• class name dot class attribute
std = Student()
std.clg_Name

'ANITS'

Student.clg_Name

'ANITS'

Explicitly changing a class attribute


print("Before Changing")
print(Student.clg_Name)
print("After Changing")
Student.clg_Name="Anil Neerukonda Institute of Technology and
Sciences"
print(Student.clg_Name)

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

def __init__(self): # constructor


self.name = 'xyz' # instance attribute
self.age = 20 # instance attribute

std = Student()
std.name

'xyz'

std.age

20

std.name = "Bill" # assign value to instance attribute


std.age=25 # assign value to instance attribute
std.name # access instance attribute value

'Bill'

std.age # access value to instance attribute

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

Example: Setting Default Values of Attributes


class Student:
def __init__(self, name="Guest", age=25):
self.name=name
self.age=age

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

• The first parameter of the method need not be named self.


• You can give any name that refers to the instance of the calling method.
• The following displayInfo() method names the first parameter as obj instead of self
and that works perfectly fine.
class Student:
def displayInfo(obj): # class method
print('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()

TypeError: displayInfo() takes 0 positional arguments but 1 was given

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)

std = Student('Bill', 25)


std.displayInfo()
Student Name: Bill , Age: 25

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

Deleting Attribute, Object, Class


• You can delete attributes, objects, or the class itself, using the del keyword, as shown
below.
del std.name # deleting attribute
std.name

----------------------------------------------------------------------
-----
AttributeError Traceback (most recent call
last)
Input In [43], in <cell line: 2>()
1 del std.name # deleting attribute
----> 2 std.name

AttributeError: 'Student' object has no attribute 'name'


del std # deleting object
std.name

----------------------------------------------------------------------
-----
NameError Traceback (most recent call
last)
Input In [44], in <cell line: 2>()
1 del std # deleting object
----> 2 std.name

NameError: name 'std' is not defined

del Student # deleting class


std = Student('Steve', 25)

----------------------------------------------------------------------
-----
NameError Traceback (most recent call
last)
Input In [45], in <cell line: 2>()
1 del Student # deleting class
----> 2 std = Student('Steve', 25)

NameError: name 'Student' is not defined

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

Extend the Functionality of a Parent Class


• Single Inheritance
• Multiple Inheritance
• Multilevel Inheritance
• Hierarchical Inheritance
Single Inheritance
• Single inheritance enables a derived class to inherit properties from a single parent
class, thus enabling code reusability and the addition of new features to existing
code.

Syntax
class Superclass:     # Class body... class Subclass(Superclass):     # Class body...`

Example for single Inheritance


class quadriLateral:
def __init__(self, a, b, c, d):
self.side1=a
self.side2=b
self.side3=c
self.side4=d
def perimeter(self):
p=self.side1 + self.side2 + self.side3 + self.side4
print("perimeter=",p)
class rectangle(quadriLateral):
def __init__(self, a, b):
super().__init__(a, b, a, b)

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...`

Example for Multiple Inheritance


class hulk:
def smash(self):
return "I smash"
class banner:
def speak(self):
return "I've got the brains!"

class smarthulk(hulk, banner):


pass

s1 = smarthulk()
print(s1.smash(), "and", s1.speak())

I smash and I've got the brains!

• 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...`

Example for Multilevel Inheritance


class Parent:
str1 = "Python"
class Child(Parent):
str2 = "Geeks"
class GrandChild(Child):
def get_str(self):
print(self.str1 + self.str2)
person = GrandChild()
person.get_str()

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()

name: parent , regno : p1

class child1(parent):
def __init__(self,regno,name):
parent.__init__(self,regno,name)
ch1 = child1("child1","c1")
ch1.prn()

name: c1 , regno : child1

class child2(parent):
def _init_(self,regno,name):
parent.__init__(self,regno,name)
ch2 = child2("child2","c2")
ch2.prn()

name: c2 , regno : child2

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'

Magic method in python:

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()

Selling Price: 900

# change the price


c.__maxprice = 1000
c.sell()

Selling Price: 900

# using setter function


c.setMaxPrice(1000)
c.sell()

Selling Price: 1000

• In the above program, we defined a Computer class.


• We used init() method to store the maximum selling price of Computer.
• We tried to modify the price.
• However, we can't change it because Python treats the __maxprice as private
attributes.
• As shown, to change the value, we have to use a setter function
• that is setMaxPrice() which takes price as a parameter.

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'>

Ploymorphism in user define functions


class Parrot:
def fly(self):
print("Parrot can fly")
def swim(self):
print("Parrot can't swim")
class Penguin:
def fly(self):
print("Penguin can't fly")
def swim(self):
print("Penguin can swim")
# common interface
def flying_test(bird):
bird.fly()

#instantiate objects
blu = Parrot()
peggy = Penguin()

# passing the object


flying_test(peggy)

Penguin can't fly

# passing the object


flying_test(blu)

Parrot can fly

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)

TypeError: mul() missing 1 required positional argument: 'c'

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()

Iam the owner


Iam 25 years old

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.

Python Regex Metacharacters


• The real power of regex matching in Python emerges when <regex> contains special
characters called metacharacters. These have a unique meaning to the regex
matching engine and vastly enhance the capability of the search.

Metacharacters supported by the re Module:

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")

Yes, the string starts with 'hello'

#$
import re
txt = "hello planet"
x = re.findall("planet$", txt)
if x:
print("Yes, the string ends with 'planet'")
else:
print("No match")

Yes, the string ends with 'planet'

#[]
import re
txt = "The rain in Spain"
x = re.findall("[a-m]", txt)
print(x)

['h', 'e', 'a', 'i', 'i', 'a', 'i']

# +
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())

The first white-space character is located in position: 3

#\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!

Regular expression Built-in Functions:


• NOTE:Choose your own string to perform all these built-in fuctions

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]')

print(p.findall("Aye, said Mr. Gibenson Stark"))

['e', 'a', 'd', 'b', 'e', 'a']

re.search(pattern, string, flags=0)


• (Scan through string looking for the first location where the regular expression
pattern produces a match, and return a corresponding match object. Return None if
no position in the string matches the pattern; note that this is different from finding
a zero-length match at som e point in the string.)

import re
txt = "The rain in Spain"
x = re.search("Portugal", txt)
print(x)

None

re.match(pattern, string, flags=0)


• (If zero or more characters at the beginning of string match the regular expression
pattern, return a corresponding match object. Return None if the string does not
match the pattern;note that this is different from a zero-length match.)
import re

txt = "The rain in Spain"


x = re.search("ai", txt)
print(x) #this will print an object

<re.Match object; span=(5, 7), match='ai'>

re.fullmatch(pattern, string, flags=0)


• (If the whole string matches the regular expression pattern,return a corresponding
match object. Return None if the string does not match the pattern; note that this is
different from a zero-length match.)
import re

email = '[email protected]'
pattern = r'[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}'
match = re.fullmatch(pattern, email)

if match is not None:


print(f'The email "{match.group()}" is valid')
else:
print(f'The email "{email}"" is not valid')

The email "[email protected]" is valid

re.split(pattern, string, maxsplit=0, flags=0)


• (Split string by the occurrences of pattern.If capturing parentheses are used in
pattern,then the text of all groups in the pattern are also returned as part of the
resulting list.If maxsplit is nonzero, at most maxsplit splits occur,and the remainder
of the string is returned as the final element of the list.)
import re

txt = "The rain in Spain"


x = re.split("\s", txt, 1)
print(x)

['The', 'rain in Spain']


re.findall(pattern, string, flags=0)
• (Return all non-overlapping matches of pattern in string, as a list of strings or
tuples.The string is scanned left-to-right, and matches are returned in the order
found. Empty matches are included in the result.)
import re

txt = "The rain in Spain"


x = re.findall("ai", txt)
print(x)

['ai', 'ai']

re.finditer(pattern, string, flags=0)


• (Return an iterator yielding match objects over all non-overlapping matches for the
RE pattern in string. The string is scanned left-to-right,and matches are returned in
the order found.Empty matches are included in the result.)
import re

s = 'Readability counts.'
pattern = r'[aeoui]'

matches = re.finditer(pattern, s)
for match in matches:
print(match)

<re.Match object; span=(1, 2), match='e'>


<re.Match object; span=(2, 3), match='a'>
<re.Match object; span=(4, 5), match='a'>
<re.Match object; span=(6, 7), match='i'>
<re.Match object; span=(8, 9), match='i'>
<re.Match object; span=(13, 14), match='o'>
<re.Match object; span=(14, 15), match='u'>

re.sub(pattern, repl, string, count=0, flags=0)


• (Return the string obtained by replacing the leftmost non-overlapping occurrences
of pattern in string by the replacement repl.If the pattern isn’t found, string is
returned unchanged.)
import re

txt = "The rain in Spain"


x = re.sub("\s", "9", txt)
print(x)

The9rain9in9Spain

re.subn(pattern, repl, string, count=0, flags=0)


• (Perform the same operation as sub(),but return a tuple (new_string,
number_of_subs_made))
import re
s = "I am a human being."
res_1 = re.subn('a', 'x', s)
res_2 = re.subn('[a,I]','x',s)
print(res_1)
print(res_2)

('I xm x humxn being.', 3)


('x xm x humxn being.', 4)

Other programs:
import re

s = 'there are no portals'


match = re.search(r'portal', s)
print('Start Index:', match.start())
print('End Index:', match.end())

Start Index: 13
End Index: 19

import re
p = re.compile('[a-e]')
print(p.findall("the number of ovels in this sentence"))

['e', 'b', 'e', 'e', 'e', 'e', 'c', 'e']

You might also like