0% found this document useful (0 votes)
17 views143 pages

Python HOD GAR

Uploaded by

starlord68736
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views143 pages

Python HOD GAR

Uploaded by

starlord68736
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 143

List

List is a versatile data type available in python.


Access values in a list
seq=List[start:stop:step]
Example 1
num_list=[1,2,3,4,5,6,7,8,9,10]
print("num_list:",num_list)
print(num_list[2:5])
print(num_list[::2])
print(num_list[1::3])

Output:

num_list: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]


[3, 4, 5]
[1, 3, 5, 7, 9] Dr. Shiladitya Chowdhury
[2, 5, 8] Ph.D(Computer Science & Engineering)(JU)
1
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

Updating values in a list

We can append new values in a list using append() method.

We can remove existing values from a list using del statement.

Example 2

num_list=[1,2,3,4,5,6,7,8,9,10]
print("num_list:",num_list)

num_list[4]=500
print("num_list:",num_list)

num_list.append(999)
print("num_list:",num_list)

del num_list[3]
print("num_list:",num_list) Dr. Shiladitya Chowdhury
Ph.D(Computer Science & Engineering)(JU)
2
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Output:

num_list: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]


num_list: [1, 2, 3, 4, 500, 6, 7, 8, 9, 10]
num_list: [1, 2, 3, 4, 500, 6, 7, 8, 9, 10, 999]
num_list: [1, 2, 3, 500, 6, 7, 8, 9, 10, 999]

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
3
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

Example 3

num_list=[1,2,3,4,5,6,7,8,9,10]
print("num_list:",num_list)

del num_list[2:4]
print("num_list:",num_list)

del num_list[:]
print("num_list:",num_list)

Output:
num_list: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
num_list: [1, 2, 5, 6, 7, 8, 9, 10]
num_list: []

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
4
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Example 3A

num_list=[1,2,3,4,5,6,7,8,9,10]
print("num_list:",num_list)

del num_list
print("num_list:",num_list)

Output:

num_list: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Traceback (most recent call last):


File "C:/Users/Admin/PycharmProjects/List1/Example3a.py",
line 5, in <module>
print("num_list:",num_list)
NameError: name 'num_list' is not defined

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
5
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

To insert items from another list at a particular location, we can use slice
operation. This will result in the creation of a list within another list.
Example 4

num_list=[1,2,3,4,5,6,7,8,9,10]
print("num_list:",num_list)

num_list[2]=[11,22,33]
print("num_list:",num_list)

print(num_list[2][0])
print(num_list[2][1])
print(num_list[2][2])

Output:
num_list: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
num_list: [1, 2, [11, 22, 33], 4, 5, 6, 7, 8, 9, 10]
11
22 Dr. Shiladitya Chowdhury
33 Ph.D(Computer Science & Engineering)(JU)
6
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Nested list

Nested list means a list within another list.


The list has elements of different data types which can include even a list.

Example 4A

num_list=[1,2,[10,20,30],4,5]

i=0
while i < len(num_list):
print(num_list[i])
i=i+1

Output:
1
2
[10, 20, 30]
4 Dr. Shiladitya Chowdhury
5 Ph.D(Computer Science & Engineering)(JU)
7
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

Cloning list

The slice operation is used to clone a list.

Example 5

list1=[1,2,3,4,5]
print("List1:",list1)

list2=list1
print("List2:",list2)
list3=list1[2:4]
print("List3:",list3)

Output:
List1: [1, 2, 3, 4, 5]
List2: [1, 2, 3, 4, 5]
List3: [3, 4]
Dr. Shiladitya Chowdhury
Ph.D(Computer Science & Engineering)(JU)
8
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Basic List operations
Example 6
num_list=[1,2,3,4,5,6,7,8,9,10]
print("num_list:",num_list)

print("Length of list=",len(num_list))

list1=[1,2,3]
list2=[10,20,30]

list3=list1+list2
print(list3)

print(3*list1)

print("Max data:",max(num_list))
print("Min data:",min(num_list))

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
9
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

print("Sum=",sum(num_list))

list4=[1,7,5,0,6]
list5=[34,88,60,29]

print(all(list4)) # Return True if all elements of list are true; Return False otherwise
print(all(list5))

list6=[0,0,0]
print(any(list4)) # Return True if any elements of list are true; Return False otherwise
print(any(list6))

list7=list("hello") # Converts an iterable to a list.


print(list7)

list8=sorted(list5)
print(list8)

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
10
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Output:

num_list: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]


Length of list= 10
[1, 2, 3, 10, 20, 30]
[1, 2, 3, 1, 2, 3, 1, 2, 3]
Max data: 10
Min data: 1
Sum= 55
False
True
True
False
['h', 'e', 'l', 'l', 'o']
[29, 34, 60, 88]

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
11
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

List methods
count(): Count the number of times an element appears in the list.
index(): Returns the lowest index of the object in the list. Gives a ValueError if object
is not present in the list.
insert(): Insert object at the specified index in the list.
pop(): Removes the element at the specified index from the list. Index is an optional
parameter.
If no index is specified, then removes the last element from the list.
remove(): Removes object from the list. ValueError is generated if the object is not
present in the list.
If multiple copies of object exists in the list, then the first value is deleted.
reverse() : Reverse the elements in the list.
sort(): Sorts the elements in the list.
Dr. Shiladitya
extend(): Adds the elements in a list to theChowdhury
end of another list.
Ph.D(Computer Science & Engineering)(JU)
12
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Example 7
num_list=[25,48,12,78,60,18, 60,40]
print("num_list:",num_list)

print(num_list.count(60))

print(num_list.index(60))

num_list.insert(2,200)
print("num_list:",num_list)

print(num_list.pop())
print("num_list:",num_list)

print(num_list.pop(1))
print("num_list:",num_list)

num_list.remove(60)
print("num_list:",num_list)
Dr. Shiladitya Chowdhury
Ph.D(Computer Science & Engineering)(JU)
13
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

num_list.reverse()
print("num_list:",num_list)

num_list.sort()
print("num_list:",num_list)

list2=[10,20,30,40]
num_list.extend(list2)
print("num_list:",num_list)

Output:

num_list: [25, 48, 12, 78, 60, 18, 60, 40]


2
4
num_list: [25, 48, 200, 12, 78, 60, 18, 60, 40]
40
num_list: [25, 48, 200, 12, 78, 60, 18, 60]
48
num_list: [25, 200, 12, 78, 60, 18, 60]
num_list: [25, 200, 12, 78, 18, 60]
num_list: [60, 18, 78, 12, 200, 25]
num_list: [12, 18, 25, 60, 78, 200]
num_list: [12, 18, 25, 60, 78, 200, 10, 20, 30, 40]
Dr. Shiladitya Chowdhury
Ph.D(Computer Science & Engineering)(JU)
14
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
insert(), remove(), reverse() and sort() methods only modify the list and do not return
any value.

Example 8

num_list=[25,48,12,78,60,18, 60,40]
print("num_list:",num_list)

print(num_list.insert(2,200))
print("num_list:",num_list)

print(num_list.remove(60))
print("num_list:",num_list)

print(num_list.reverse())
print("num_list:",num_list)

print(num_list.sort())
print("num_list:",num_list)
Dr. Shiladitya Chowdhury
Ph.D(Computer Science & Engineering)(JU)
15
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

Output:

num_list: [25, 48, 12, 78, 60, 18, 60, 40]


None
num_list: [25, 48, 200, 12, 78, 60, 18, 60, 40]
None
num_list: [25, 48, 200, 12, 78, 18, 60, 40]
None
num_list: [40, 60, 18, 78, 12, 200, 48, 25]
None
num_list: [12, 18, 25, 40, 48, 60, 78, 200]

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
16
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
When one list is assigned to another list using assignment operator (=), then
new copy of the list is not made.
Instead, assignment makes the two variables point to the one list in memory.
This is known as aliasing. Since lists are mutable, changes made with one
alias affect the other.

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
17
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

Example 9

list1=[1,2,3]
list2=list1

print("List1 id:",id(list1))
print("List2 id:",id(list2))

print("List 1:",list1)
print("List 2:",list2)

list1[2]=30

print("List 1:",list1)
print("List 2:",list2)

list2[1]=11

print("List 1:",list1)
print("List 2:",list2)

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
18
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Output:
List1 id: 10044840
List2 id: 10044840
List 1: [1, 2, 3]
List 2: [1, 2, 3]
List 1: [1, 2, 30]
List 2: [1, 2, 30]
List 1: [1, 11, 30]
List 2: [1, 11, 30]

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
19
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

The sort() method uses ASCII values to sort the values in the list.

Example 10

num_list=['1',"60","PQR", "A",'E']

num_list.sort()
print("num_list:",num_list)

Output:

num_list: ['1', '60', 'A', 'E', 'PQR']

Note:

Items in a list can also be deleted by assigning an empty list to a slice of


elements.

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
20
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Example 11

num_list=[1,2,3,4,5,6,7,8,9,10]
print("num_list:",num_list)

num_list[2:5]=[]
print("num_list:",num_list)

Output:

num_list: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]


num_list: [1, 2, 6, 7, 8, 9, 10]

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
21
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

List Comprehensions

Example 12

cubes=[]
for i in range(6):
cubes.append(i**3)

print("Cubes:",cubes)

Output:

Cubes: [0, 1, 8, 27, 64, 125]

Python also supports computed lists called list comprehensions having the following
syntax:

List = [expression for variable in sequence]


where, the expression is evaluated once, for every item in the sequence.

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
22
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Example 12A

cubes=[i**3 for i in range(6)]


print("Cunes:",cubes)

Output:

Cubes: [0, 1, 8, 27, 64, 125]

Example 13

Program to combine and print elements of two list using list


comprehensions

print([(x,y) for x in [11,22,33] for y in [22,44,55] if x!=y])

print([(x,y) for x in [11,22,33] for y in [22,44,55] if x==y])

Output:

[(11, 22), (11, 44), (11, 55), (22, 44), (22, 55), (33, 22), (33, 44), (33, 55)]
[(22, 22)] Dr. Shiladitya Chowdhury
Ph.D(Computer Science & Engineering)(JU)
23
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

Looping in Lists
Example 14A

Access each and every elements of the list using for loop.

num_list=[1,2,3,4,5]
print("num_list:",num_list)

for i in num_list:
print(i)

Output:

num_list: [1, 2, 3, 4, 5]
1
2
3
4
5
Dr. Shiladitya Chowdhury
Ph.D(Computer Science & Engineering)(JU)
24
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
enumerate() function:

The enumerate function returns an enumerate object which contains the index and
value of all the items of the list as a tuple.

Example 14B

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

for index,num in enumerate(num_list):


print(num, " is at index:",index)

Output:

1 is at index: 0
2 is at index: 1
3 is at index: 2
4 is at index: 3
5 is at index: 4

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
25
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

Example 14C

num_list=[1,2,3,4,5]
print("num_list:",num_list)

for i in range(len(num_list)):
print("index:",i)

Output:

num_list: [1, 2, 3, 4, 5]
index: 0
index: 1
index: 2
index: 3
index: 4

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
26
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Example 14D

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

it=iter(num_list)

for i in range(len(num_list)):
print("Element at index ",i," is :",next(it))

Output:

Element at index 0 is : 1
Element at index 1 is : 2
Element at index 2 is : 3
Element at index 3 is : 4
Element at index 4 is : 5

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
27
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

Functional programming

Functional programming decomposes a problem into a set of functions.


The map(), filter() and reduce() functions work on all list items.
filter() function

The filter() function constructs a list from those elements of the list for which a function
returm true.
Syntax:
filter (function , sequence)
Example 15
def check(x):
if (x%2==0):
return 1

evens=list(filter(check,range(1,21)))
print(evens)

Output: Dr. Shiladitya Chowdhury


[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]Ph.D(Computer Science & Engineering)(JU)
Assistant Professor, Dept. of MCA
28
Techno Main Saltlake, Kolkata 700091
map() function

The map() function applies a particular function to every element of the list.

It constructs a list from those elements of the list for which a function return true.

Syntax:

map (function , sequence)

Example 16A

def add2(x):
x=x+2
return x

lst=[10,20,30,40,50]
print("Before modification:",lst)
lst=list(map(add2,lst))
print("After modification:",lst) Dr. Shiladitya Chowdhury
Ph.D(Computer Science & Engineering)(JU)
29
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

Output:
Before modification: [10, 20, 30, 40, 50]
After modification: [12, 22, 32, 42, 52]
We can pass more than one sequence in the map function.
In this case, firstly, the function must have as many arguments as there are sequences,
and secondly, each argument is called with the corresponding item from each sequence.

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
30
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Example 16B

def add(x,y):
return x+y

lst1=[10,20,30,40,50]
lst2=[1,2,3,4,5]
lst3=list(map(add,lst1,lst2))
print("Sum of ",lst1," and ",lst2, "is=",lst3)

Output:

Sum of [10, 20, 30, 40, 50] and [1, 2, 3, 4, 5] is= [11, 22, 33, 44, 55]

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
31
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

reduce() function

The reduce() function returns a single value generated by calling the function on the
first two items of the sequence, then on the result and the next item, and so on.

Syntax:

reduce (function , sequence)

Example 17

import functools

def add(x,y):
return x+y

num_list=[10,20,30,40,50]

print("Sum of list elements=",functools.reduce(add,num_list))

Output:
Dr. Shiladitya Chowdhury
Sum of list elements= 150 Ph.D(Computer Science & Engineering)(JU)
32
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Lambda function/Anonymous function
Lambda function/ Anonymous function are not declared as other functions using
the def keyword.

They are created using lambda keyword.

Lambda functions are throw-away functions, i.e., they are needed where they
have been created and can be used anywhere a function is required.

Lambda function contains only a single line.

Syntax:

lambda arguments: expression

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
1
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

Example 1

add=lambda x,y :x+y

a=int(input("Enter 1st No:"))


b=int(input("Enter 2nd No:"))

print("Result=",add(a,b))

Output:

Enter 1st No:11


Enter 2nd No:10
Result= 21

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
2
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Key points:

i) Lambda function has no name.

ii) Lambda function can take any number of arguments.

iii) Lambda function can return just one value in the form of an expression.

iv) Lambda function definition does not have an explicit return statement.

v) Lambda function is a one line version of a function and hence cannot contain
multiple expression.

vi) Lambda function cannot access variables other than those in their parameter list.

vii) Lambda function cannot even access global variables.

viii) We can pass lambda functions as arguments in other functions.


Dr. Shiladitya Chowdhury
Ph.D(Computer Science & Engineering)(JU)
3
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

Example 2

def max(x,y):
if x>y:
return x
else:
return y

a=int(input("Enter 1st No:"))


b=int(input("Enter 2nd No:"))

add=lambda x,y:x+y
sub=lambda x,y:x-y

print("Result=",max(add(a,b),sub(a,b)))

Output:

Enter 1st No:10


Enter 2nd No:-2 Dr. Shiladitya Chowdhury
Result= 12 Ph.D(Computer Science & Engineering)(JU)
4
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Example 3

def increment(x):
return (lambda a:a+1)(x)

n=int(input("Enter No:"))
print("Result=",increment(n))

Output:

Enter No:10
Result= 11

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
5
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

We can pass lambda functions as an argument to a function.

Example 4

def calc(f,n):
print(f(n))

twice=lambda x:x*2
thrice=lambda x:x*3

calc(twice,8)
calc(thrice,9)

Output:
16
27

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
6
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Example 5

x=lambda: sum(range(1,11))

print("Result=",x())

Output:

Result= 55

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
7
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

Example 6

add=lambda x,y:x+y

multiply_add=lambda x,y,z:x*add(y,z)

print("Result=",multiply_add(2,4,5))

Output:

Result= 18

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
8
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Iterative statements

Python programming language supports two types of iterative statements:


i) while loop
ii) for loop

While loop

Syntax:

while condition:
statement block

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
1
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

Example 1

i=1

while i<=5:
print("Techno India")
i=i+1

Output:

Techno India
Techno India
Techno India
Techno India
Techno India

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
2
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
For printing values in the same line use end with a separator.

We can specify any separator ( like tab, space, comma, etc.) with end.

Example 2

i=1

while i<=10:
print(i, end=" ")
i=i+1

Output:

1 2 3 4 5 6 7 8 9 10

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
3
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

Example 3

# Sum of Digits

n=int(input("Enter Number:"))
s=0
i=n

while(i>=1):
r=i%10
s=s+r
i=i//10

print("Sum of Digits=",s)

Output:

Enter Number:149
Sum of Digits= 14
Dr. Shiladitya Chowdhury
Ph.D(Computer Science & Engineering)(JU)
4
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
for loop
Syntax:

for loop_control_variable in sequence:


statement block

Example 4A

l=['a','bc',10,3.14]

for i in l:
print(i)

Output:
a
bc
10
3.14
Dr. Shiladitya Chowdhury
Ph.D(Computer Science & Engineering)(JU)
5
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

Example 4B

t = ('P', 'XYZ', 10.22, 11)

for i in t:
print(i)

Output:

P
XYZ
10.22
11

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
6
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Example 4C

d={"A":1,"B":2,"C":3,"D":4}

for i in d:
print(i)

Output:

A
B
C
D

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
7
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

Example 4D

x="abcde"

for i in x:
print(i)

Output:

a
b
c
d
e

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
8
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
The range() function

The range() is a built-in function in Python that used to iterate over a sequence
of numbers.

The syntax of range() function is:

range(start, end, [step])

The step argument is optional.

By default, every number in the range is incremented by 1, but we can specify


different increment using step.

It can both negative and positive but not zero.

If range function is given a single argument, it produces an object with value


from 0 to argument-1.
Dr. Shiladitya Chowdhury
Ph.D(Computer Science & Engineering)(JU)
9
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

Example 5A

for i in range(11,21,3):
print(i)

Output:
11
14
17
20

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
10
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Example 5B

for i in range(20,6,-5):
print(i)

Output:
20
15
10

Example 5C

for i in range(5):
print(i)

Output:
0
1
2
3
4 Dr. Shiladitya Chowdhury
Ph.D(Computer Science & Engineering)(JU)
11
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

Example 6:

Calculate factorial of a given number.

n=int(input("Enter No:"))

f=1

if n>=0:

for i in range (2,n+1):


f=f*i
print("Result=", f)

else:
print("Wrong Input")

Output:

Enter No:5
Dr. Shiladitya Chowdhury
Result= 120 Ph.D(Computer Science & Engineering)(JU)
12
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Nested loops
Python also allows nested loops, that is, loop that can be placed inside other loop.

Example 7

Write a program to print the following outputs. (Number of line should be given
by user).

*
**
***
****
n=int(input("Enter No of Lines:"))

for i in range(1,n+1,1):
for j in range(1,i+1,1):
print("*",end="")
print("")
Dr. Shiladitya Chowdhury
Ph.D(Computer Science & Engineering)(JU)
13
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

The break statement

The break statement is used to terminate the execution of the nearest enclosing
loop in which it appears.

When complier encounters a break statement, the control passes to the statement
that follows the loop in which the break statement appears.

Example 8
i=1
while True:
if(i==5):
break
print(i)
i=i+1

Output:
1
2
3 Dr. Shiladitya Chowdhury
Ph.D(Computer Science & Engineering)(JU)
4 Assistant Professor, Dept. of MCA
14
Techno Main Saltlake, Kolkata 700091
The continue statement
The continue statement can only appear in the body of a loop.
When the compiler encounters a continue statement, then the rest of the statements
in the loop are skipped and the control is transferred to the loop-continuation
portion of the nearest enclosing loop.
Example 9
for i in range(1,11):
if i%3==0:
continue
print(i)

Output:
1
2
4
5
7
8 Dr. Shiladitya Chowdhury
10 Ph.D(Computer Science & Engineering)(JU)
15
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

The pass statement

The pass statement is used when a statement is required syntactically but no


command or code has to be executed.

It specify simply No Operation Statement (NOP).

Nothing happens when the pass statement is executed.

Example 10:

for i in range(1,11):
if(i%2==0):
pass
else:
print(i)

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
16
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Output:

1
3
5
7
9

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
17
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

The else statement used with loops

In python else statement can also be used with loop statements.


If the else statement is used with the for loop, then the else statement is executed
when the loop has completed iterating.

Example 11A:
a=[13,16,21,24,8]
for i in a:
if i%5==0:
print(i)
break
else:
print("Not Found")

Output:
Not Found Dr. Shiladitya Chowdhury
Ph.D(Computer Science & Engineering)(JU)
18
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Example 11B:

a=[13,16,25,24,8]
for i in a:
if i%5==0:
print(i)
break
else:
print("Not Found")

Output:
25

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
19
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

If the else statement is used with the while loop, then the else statement is
executed when the condition become false.

Example:

i=5

while i>=0:
print(i)
i=i-1
else:
print("Present value of i is ",i,", so we exit from loop")

Output:
5
4
3
2
1
0
Dr. Shiladitya
Present value of i is -1 , so we exit from loop Chowdhury
Ph.D(Computer Science & Engineering)(JU)
20
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Function
The function is a block of organized and reusable program code that
performs a single, specific, and well-defined task.

Example 1

def display():
print("Hello")

display()

Output:

Hello

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
1
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

Example 2

def add(x,y):
r=x+y
print("Result",r)

a=int(input("Enter 1st No:"))


b=int(input("Enter 2nd No:"))

add(a,b)

Output:

Enter 1st No: 10


Enter 2nd No: 6
Result 16

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
2
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Example 3

def add(x,y):
s=x+y
return s

a=int(input("Enter 1st No:"))


b=int(input("Enter 2nd No:"))

r=add(a,b)
print("Result=",r)

Output:

Enter 1st No: 10


Enter 2nd No: 4
Result= 14

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
3
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

Example 4.1

def add(x,y):
s=x+y
return s

a=int(input("Enter 1st No:"))


b=int(input("Enter 2nd No:"))

addition=add
r=addition(a,b)
print("Result=",r)

Output:

Enter 1st No:11


Enter 2nd No:22
Result= 33
Dr. Shiladitya Chowdhury
Ph.D(Computer Science & Engineering)(JU)
4
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Example 4.2

def display():
print("ABCD")
return
print("XYZ")

display()

Output:

ABCD

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
5
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

Example 4.3

def display():
print("Hello")
return

display()
print(display())

Output:

Hello
Hello
None

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
6
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
In python programming language, a function can return more than one value.

Example 5

def add_sub(x,y):
c=x+y
d=x-y
return c,d

a=int(input("Enter 1st No:"))


b=int(input("Enter 2nd No:"))

r1,r2=add_sub(a,b)

print("Result of Addition=",r1)
print("Result of Subtraction=",r2)

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
7
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

Output:

Enter 1st No:11


Enter 2nd No:4
Result of Addition= 15
Result of Subtraction= 7

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
8
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Example 6

def swap(x,y):
return y,x

a=int(input("Enter 1st No:"))


b=int(input("Enter 2nd No:"))

print("Before Swap:")
print("a=",a)
print("b=",b)

a,b=swap(a,b)

print("After Swap:")
print("a=",a)
print("b=",b)
Dr. Shiladitya Chowdhury
Ph.D(Computer Science & Engineering)(JU)
9
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

Output:

Enter 1st No:11


Enter 2nd No:22
Before Swap:
a= 11
b= 22
After Swap:
a= 22
b= 11

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
10
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Example 7

def update(x):
print("Inside Finction 1 :x=",x,"Address=",id(x))
x=8
print("Inside Finction 2 :x=", x, "Address=", id(x))

x=10
update(x)
print("Outside Finction :x=",x,"Address=",id(x))

Output:

Inside Finction 1 :x= 10 Address= 1351825808


Inside Finction 2 :x= 8 Address= 1351825776
Outside Finction :x= 10 Address= 1351825808

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
11
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

Example 8

def update(lst):
print("\nIn function before update :")
print("List:", lst)
print("List Address:", id(lst))
print("Address of list elements:")
for i in range(3):
print((id(lst[i])))

lst[1]=25

print("\nIn function After update : :")


print("List:", lst)
print("List Address:", id(lst))
print("Address of list elements:")
for i in range(3):
print((id(lst[i])))

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
12
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
lst=[10, 20, 30]

print("Before function call :")


print("List:",lst)
print("List Address:",id(lst))
print("Address of list elements:")
for i in range(3):
print((id(lst[i])))

update(lst)

print("\nAfter function call :")


print("List:",lst)
print("List Address:",id(lst))
print("Address of list elements:")
for i in range(3):
print((id(lst[i])))
Dr. Shiladitya Chowdhury
Ph.D(Computer Science & Engineering)(JU)
13
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

Output:

Before function call :


List: [10, 20, 30]
List Address: 9848232
Address of list elements:
1348024720
1348024880
1348025040

In function before update :


List: [10, 20, 30]
List Address: 9848232
Address of list elements:
1348024720
1348024880
1348025040

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
14
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
In function After update : :
List: [10, 25, 30]
List Address: 9848232
Address of list elements:
1348024720
1348024960
1348025040

After function call :


List: [10, 25, 30]
List Address: 9848232
Address of list elements:
1348024720
1348024960
1348025040

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
15
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

Example 9

def update(tup):
print("\nIn function before update :")
print("Tuple:", tup)
print("Tuple Address:", id(tup))
print("Address of Tuple elements:")
for i in range(3):
print((id(tup[i])))

tup[1]=25

print("\nIn function After update : :")


print("Tuple:", tup)
print("Tuple Address:", id(tup))
print("Address of Tuple elements:")
for i in range(3):
print((id(tup[i])))

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
16
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
tup=(10, 20, 30)

print("Before function call :")


print("Tuple:",tup)
print("Tuple Address:",id(tup))
print("Address of Tuple elements:")
for i in range(3):
print((id(tup[i])))

update(tup)

print("\nAfter function call :")


print("Tuple:",tup)
print("Tuple Address:",id(tup))
print("Address of Tuple elements:")
for i in range(3):
print((id(tup[i])))
Dr. Shiladitya Chowdhury
Ph.D(Computer Science & Engineering)(JU)
17
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

Output:

Before function call :


Tuple: (10, 20, 30)
Tuple Address: 8071728
Address of Tuple elements:
1348024720
1348024880
1348025040

In function before update :


Tuple: (10, 20, 30)
Tuple Address: 8071728
Address of Tuple elements:
1348024720
1348024880
1348025040

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
18
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Traceback (most recent call last):
File "C:/Users/Admin/PycharmProjects/function1/fun9.py", line 29, in
<module>
update(tup)
File "C:/Users/Admin/PycharmProjects/function1/fun9.py", line 9, in
update
tup[1]=25
TypeError: 'tuple' object does not support item assignment

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
19
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

Local and Global variables

Global variables are those variables which are defined in the main body of the
program file.

The variable which is defined within a function is called local variable.

Example 1

a=10
print("In Global Section: a=",a,"Address=",id(a))

def show():
a=20
print("Inside function: a=", a, "Address=", id(a))

show()
print("Outside function: a=",a,"Address=",id(a))
Dr. Shiladitya Chowdhury
Ph.D(Computer Science & Engineering)(JU)
20
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Output:

In Global Section: a= 10 Address= 1347631504


Inside function: a= 20 Address= 1347631664
Outside function: a= 10 Address= 1347631504

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
21
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

Example 2

a=10
print("In Global Section: a=",a,"Address=",id(a))

def show():
global a
a=20
print("Inside function: a=", a, "Address=", id(a))

show()
print("Outside function: a=",a,"Address=",id(a))

Output:

In Global Section: a= 10 Address= 1347631504


Inside function: a= 20 Address= 1347631664
Outside function: a= 20 Address= 1347631664
Dr. Shiladitya Chowdhury
Ph.D(Computer Science & Engineering)(JU)
22
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Example 3

a=10
print("In Global Section: a=",a,"Address=",id(a))

def show():
global b
b=20
print("Inside function: b=", b, "Address=", id(b))

show()
print("Outside function: a=",a,"Address=",id(a))
print("Outside function: b=", b, "Address=", id(b))

Output:

In Global Section: a= 10 Address= 1347631504


Inside function: b= 20 Address= 1347631664
Outside function: a= 10 Address=Dr.1347631504
Shiladitya Chowdhury
Outside function: b= 20 Address= 1347631664
Ph.D(Computer Science & Engineering)(JU)
23
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

Function
The function is a block of organized and reusable program code that
performs a single, specific, and well-defined task.

Example 1

def display():
print("Hello")

display()

Output:

Hello

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
1
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Example 2

def add(x,y):
r=x+y
print("Result",r)

a=int(input("Enter 1st No:"))


b=int(input("Enter 2nd No:"))

add(a,b)

Output:

Enter 1st No: 10


Enter 2nd No: 6
Result 16

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
2
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

Example 3

def add(x,y):
s=x+y
return s

a=int(input("Enter 1st No:"))


b=int(input("Enter 2nd No:"))

r=add(a,b)
print("Result=",r)

Output:

Enter 1st No: 10


Enter 2nd No: 4
Result= 14

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
3
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Example 4.1

def add(x,y):
s=x+y
return s

a=int(input("Enter 1st No:"))


b=int(input("Enter 2nd No:"))

addition=add
r=addition(a,b)
print("Result=",r)

Output:

Enter 1st No:11


Enter 2nd No:22
Result= 33
Dr. Shiladitya Chowdhury
Ph.D(Computer Science & Engineering)(JU)
4
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

Example 4.2

def display():
print("ABCD")
return
print("XYZ")

display()

Output:

ABCD

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
5
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Example 4.3

def display():
print("Hello")
return

display()
print(display())

Output:

Hello
Hello
None

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
6
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

In python programming language, a function can return more than one value.

Example 5

def add_sub(x,y):
c=x+y
d=x-y
return c,d

a=int(input("Enter 1st No:"))


b=int(input("Enter 2nd No:"))

r1,r2=add_sub(a,b)

print("Result of Addition=",r1)
print("Result of Subtraction=",r2)

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
7
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Output:

Enter 1st No:11


Enter 2nd No:4
Result of Addition= 15
Result of Subtraction= 7

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
8
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

Example 6

def swap(x,y):
return y,x

a=int(input("Enter 1st No:"))


b=int(input("Enter 2nd No:"))

print("Before Swap:")
print("a=",a)
print("b=",b)

a,b=swap(a,b)

print("After Swap:")
print("a=",a)
print("b=",b)
Dr. Shiladitya Chowdhury
Ph.D(Computer Science & Engineering)(JU)
9
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Output:

Enter 1st No:11


Enter 2nd No:22
Before Swap:
a= 11
b= 22
After Swap:
a= 22
b= 11

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
10
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

Example 7

def update(x):
print("Inside Finction 1 :x=",x,"Address=",id(x))
x=8
print("Inside Finction 2 :x=", x, "Address=", id(x))

x=10
update(x)
print("Outside Finction :x=",x,"Address=",id(x))

Output:

Inside Finction 1 :x= 10 Address= 1351825808


Inside Finction 2 :x= 8 Address= 1351825776
Outside Finction :x= 10 Address= 1351825808

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
11
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Example 8

def update(lst):
print("\nIn function before update :")
print("List:", lst)
print("List Address:", id(lst))
print("Address of list elements:")
for i in range(3):
print((id(lst[i])))

lst[1]=25

print("\nIn function After update : :")


print("List:", lst)
print("List Address:", id(lst))
print("Address of list elements:")
for i in range(3):
print((id(lst[i])))

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
12
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

lst=[10, 20, 30]

print("Before function call :")


print("List:",lst)
print("List Address:",id(lst))
print("Address of list elements:")
for i in range(3):
print((id(lst[i])))

update(lst)

print("\nAfter function call :")


print("List:",lst)
print("List Address:",id(lst))
print("Address of list elements:")
for i in range(3):
print((id(lst[i])))
Dr. Shiladitya Chowdhury
Ph.D(Computer Science & Engineering)(JU)
13
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Output:

Before function call :


List: [10, 20, 30]
List Address: 9848232
Address of list elements:
1348024720
1348024880
1348025040

In function before update :


List: [10, 20, 30]
List Address: 9848232
Address of list elements:
1348024720
1348024880
1348025040

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
14
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

In function After update : :


List: [10, 25, 30]
List Address: 9848232
Address of list elements:
1348024720
1348024960
1348025040

After function call :


List: [10, 25, 30]
List Address: 9848232
Address of list elements:
1348024720
1348024960
1348025040

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
15
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Example 9

def update(tup):
print("\nIn function before update :")
print("Tuple:", tup)
print("Tuple Address:", id(tup))
print("Address of Tuple elements:")
for i in range(3):
print((id(tup[i])))

tup[1]=25

print("\nIn function After update : :")


print("Tuple:", tup)
print("Tuple Address:", id(tup))
print("Address of Tuple elements:")
for i in range(3):
print((id(tup[i])))

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
16
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

tup=(10, 20, 30)

print("Before function call :")


print("Tuple:",tup)
print("Tuple Address:",id(tup))
print("Address of Tuple elements:")
for i in range(3):
print((id(tup[i])))

update(tup)

print("\nAfter function call :")


print("Tuple:",tup)
print("Tuple Address:",id(tup))
print("Address of Tuple elements:")
for i in range(3):
print((id(tup[i])))
Dr. Shiladitya Chowdhury
Ph.D(Computer Science & Engineering)(JU)
17
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Output:

Before function call :


Tuple: (10, 20, 30)
Tuple Address: 8071728
Address of Tuple elements:
1348024720
1348024880
1348025040

In function before update :


Tuple: (10, 20, 30)
Tuple Address: 8071728
Address of Tuple elements:
1348024720
1348024880
1348025040

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
18
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

Traceback (most recent call last):


File "C:/Users/Admin/PycharmProjects/function1/fun9.py", line 29, in
<module>
update(tup)
File "C:/Users/Admin/PycharmProjects/function1/fun9.py", line 9, in
update
tup[1]=25
TypeError: 'tuple' object does not support item assignment

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
19
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Local and Global variables

Global variables are those variables which are defined in the main body of the
program file.

The variable which is defined within a function is called local variable.

Example 1

a=10
print("In Global Section: a=",a,"Address=",id(a))

def show():
a=20
print("Inside function: a=", a, "Address=", id(a))

show()
print("Outside function: a=",a,"Address=",id(a))
Dr. Shiladitya Chowdhury
Ph.D(Computer Science & Engineering)(JU)
20
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

Output:

In Global Section: a= 10 Address= 1347631504


Inside function: a= 20 Address= 1347631664
Outside function: a= 10 Address= 1347631504

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
21
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Example 2

a=10
print("In Global Section: a=",a,"Address=",id(a))

def show():
global a
a=20
print("Inside function: a=", a, "Address=", id(a))

show()
print("Outside function: a=",a,"Address=",id(a))

Output:

In Global Section: a= 10 Address= 1347631504


Inside function: a= 20 Address= 1347631664
Outside function: a= 20 Address= 1347631664
Dr. Shiladitya Chowdhury
Ph.D(Computer Science & Engineering)(JU)
22
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

Example 3

a=10
print("In Global Section: a=",a,"Address=",id(a))

def show():
global b
b=20
print("Inside function: b=", b, "Address=", id(b))

show()
print("Outside function: a=",a,"Address=",id(a))
print("Outside function: b=", b, "Address=", id(b))

Output:

In Global Section: a= 10 Address= 1347631504


Inside function: b= 20 Address= 1347631664
Outside function: a= 10 Address=Dr.1347631504
Shiladitya Chowdhury
Outside function: b= 20 Address= 1347631664
Ph.D(Computer Science & Engineering)(JU)
23
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Resolution of Names

When a variable name is used in a code block, it is resolved using the


nearest enclosing scope.

If no variable of that name is found, then NameError is raised.

Example 1

def fun():
print("a=",a)

a=20
fun()

Output:

a= 20
Dr. Shiladitya Chowdhury
Ph.D(Computer Science & Engineering)(JU)
24
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

A local variable cannot be defined with the same name as global variable.
To do this we must need global statement.
Example 2

def fun():
print("a=",a)
a=10
print("a=", a)

a=20
fun()

Output:
Traceback (most recent call last):
File "C:/Users/Admin/PycharmProjects/function1/resolutionName_2.py", line 7, in
<module>
fun()
File "C:/Users/Admin/PycharmProjects/function1/resolutionName_2.py", line 2, in fun
print("a=",a) Dr. Shiladitya Chowdhury
UnboundLocalError: local variable Ph.D(Computer Science &
'a' referenced Engineering)(JU)
before assignment 25
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Example 3

def fun():
global a
print("a=",a)
a=10
print("a=", a)

a=20
fun()

Output:

a= 20
a= 10

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
26
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

Nested function

In case of nested functions (function inside another function), the inner function
can access variables defined in both outer as well as inner function; but the
outer function can access variables defined only in the outer function.

def outer_fun():
outer_var=10
def inner_fun():
inner_var=20
print("In Inner fun: outer variable=",outer_var)
print("In Inner fun: inner variable=",inner_var)
inner_fun()
print("In Outer fun: outer variable=", outer_var)
print("inner variable=",inner_var)

outer_fun()

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
27
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Output:

Traceback (most recent call last):


File "C:/Users/Admin/PycharmProjects/function1/nestedfun1.py", line 11,
in <module>
outer_fun()
File "C:/Users/Admin/PycharmProjects/function1/nestedfun1.py", line 9, in
outer_fun
print("inner variable=",inner_var)
NameError: name 'inner_var' is not defined
In Inner fun: outer variable= 10
In Inner fun: inner variable= 20
In Outer fun: outer variable= 10

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
28
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

If a variable in the inner function is defined with the same name as that of a
variable defined in the outer function, then a new variable is created in the
inner function.

def outer_fun():
var=10
def inner_fun():
var=20
print("In Inner fun: var=",var,"Address=",id(var))
inner_fun()
print("In Outer fun: var=", var,"Address=",id(var))

outer_fun()

Output:

In Inner fun: var= 20 Address= 1347631664


In Outer fun: var= 10 Address= 1347631504

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
29
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Keyword Arguments

Python allows functions to be called using keyword arguments in which the


order (or position) of the arguments can be changed.

Example 1

def display(name,roll,avgmarks):
print("Name:",name)
print("Roll:",roll)
print("Avg Marks:",avgmarks)

display(roll=10,avgmarks=78.25,name="Raja Roy")

Output:

Name: Raja Roy


Roll: 10
Avg Marks: 78.25 Dr. Shiladitya Chowdhury
Ph.D(Computer Science & Engineering)(JU)
30
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

Example 2

def display(ename,age,salary):
print("Name:",ename)
print("Age:",age)
print("Salary:",salary)

n="Arun Das"
a=35
sal=50000
display(salary=sal,ename=n,age=a)

Output:

Name: Arun Das


Age: 35
Salary: 50000

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
31
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Default Arguments
Python allows users to specify function arguments that can have default
values. So, the function can be called with fewer arguments than it is defined to
have.
Example 1
def display(name,course="B.Tech"):
print("Name:",name)
print("Course:",course)

display("Raja Roy")
display("Amit Das","BCA")
display("Arup Saha","MCA")
Output:
Name: Raja Roy
Course: B.Tech
Name: Amit Das
Course: BCA
Name: Arup Saha Dr. Shiladitya Chowdhury
Ph.D(Computer Science & Engineering)(JU)
Course: MCA Assistant Professor, Dept. of MCA
32
Techno Main Saltlake, Kolkata 700091

We can specify any number of defaults arguments to a function.


Example 2
def display(name,course="B.Tech",age=18):
print("Name:",name)
print("Course:",course)
print("Age:",age)
display("Raja Roy")
display("Amit Das","BCA")
display("Arup Saha","MCA",21)
Output:
Name: Raja Roy
Course: B.Tech
Age: 18
Name: Amit Das
Course: BCA
Age: 18
Name: Arup Saha
Course: MCA Dr. Shiladitya Chowdhury
Ph.D(Computer Science & Engineering)(JU)
Age: 21 33
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
If we have default arguments, then they must be written after the non-default
arguments.

Example 3

def display(name,course="B.Tech",age):
print("Name:",name)
print("Course:",course)
print("Age:",age)

display("Amit Das","BCA",18)
display("Arup Saha","MCA",21)

Output:

C:\Users\Admin\PycharmProjects\function1\venv\Scripts\python.exe
C:/Users/Admin/PycharmProjects/function1/defaultArg3.py
File "C:/Users/Admin/PycharmProjects/function1/defaultArg3.py", line 1
def display(name,course="B.Tech",age):
^ Dr. Shiladitya Chowdhury
SyntaxError: non-default argument follows
Ph.D(Computer default
Science argument
& Engineering)(JU)
34
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

Variable-length Arguments

In some situations, it is not known in advance how many arguments


will be passed to a function.

In such case, Python allows programmers to make function calls with


arbitrary (or any) number of arguments.

The arbitrary number of arguments passed to a function basically


forms a tuple before being passed into function.

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
35
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Example 1

def display(name,*fevsubs):
print("Name:",name,"likes following subjects:")
for i in fevsubs:
print(i)

display("Raja Roy","Mathematics")
display("Amit Das","Mathematics","Biology")
display("Arup Saha","Mathematics","Physics","Chemistry")
display("Arun Dutta","Biology","Mathematics","Physics","Chemistry")

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
36
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

Output:

Name: Raja Roy Likes following subjects:


Mathematics
Name: Amit Das Likes following subjects:
Mathematics
Biology
Name: Arup Saha Likes following subjects:
Mathematics
Physics
Chemistry
Name: Arun Dutta Likes following subjects:
Biology
Mathematics
Physics
Chemistry

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
37
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Example 2

def show(a,*b):
print("a=",a)
print("b:",b)
for i in b:
print(i)

show(5,10,20,30)
show("Arun Dutta","Biology","Mathematics","Physics","Chemistry")

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
38
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

Output:

a= 5
b: (10, 20, 30)
10
20
30
a= Arun Dutta
b: ('Biology', 'Mathematics', 'Physics', 'Chemistry')
Biology
Mathematics
Physics
Chemistry

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
39
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Recursion
A function that calls itself is known as a recursive function; and this
technique is known as recursion.

Recursion one can solve problems in easy way while its iterative solution
is very big and complex.

Recursion uses more processor time.

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
40
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

Example 1

def fact(n):
f=1
if n==0 or n==1:
return 1
else:
return n*fact(n-1)

n=int(input("Enter No:"))
if n>=0:
r=fact(n)
print("Result=",r)
else:
print("Wrong Input")

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
41
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Output:

Enter No:6
Result= 720

Enter No:-4
Wrong Input

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
42
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

Function redefinition
We can redefine function in Python programming language.

Example 1

def add(x,y):
s=x+y
return s

a=int(input("Enter 1st No:"))


b=int(input("Enter 2nd No:"))

r=add(a,b)
print("Result=",r)

def add(x,y,z):
s=x+y+z
return s Dr. Shiladitya Chowdhury
Ph.D(Computer Science & Engineering)(JU)
43
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
a=int(input("Enter 1st No:"))
b=int(input("Enter 2nd No:"))
c=int(input("Enter 3rd No:"))

r=add(a,b,c)
print("Result=",r)

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
44
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

Output:

Enter 1st No:1


Enter 2nd No:2
Result= 3
Enter 1st No:10
Enter 2nd No:20
Enter 3rd No:30
Result= 60

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
45
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
File

A file is a collection of data stored on a storage device.

The file is basically used because real life applications involve large amounts of
data and in such situations the console oriented I/O operations poses two major
problems:

i) It is become very difficult and time consuming to handle huge amount of data
through terminals.

ii) When doing I/O using terminal, the entire data is lost when the entire program
is terminated or computer is turned off.

Therefore, it becomes necessary to store data on a permanent storage and read


whenever necessary, without destroying data.

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
1
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

Types of File

Python supports two types of files: text files and binary files.

Text file

A text file is a stream of characters that can be sequentially processed by a


computer in forward direction.

As text files can process characters, they can only read or write data one
character at a time.

The newline character may be converted to or from carriage-return/linefeed


combinations.

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
2
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Binary file

A binary file is a file which may contain any type of data, encoded in binary
from for computer storage and processing purpose.

A binary file does not require any special processing of the data and each byte of
data is transformed to or from the disk unprocessed.

The binary file takes less space to store the same piece of data than text file.

While text file is process sequentially, binary file, on the other hand, can be
either process sequentially or randomly depending on the needs of the
application.

To process binary file randomly, the programmer must move the current file
position to an appropriate place in the file before reading or writing data.

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
3
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

Opening a file

The open() function is used to create a file or open an existing file.

There are many modes for opening a file:

r: Open a text file in read mode

w: Opens or create a text file in write mode

a: Opens a text file in append mode

r+: Opens a text file in both read and write mode

w+: Opens a text file in both read and write mode

a+: Opens a text file in both read and append mode

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
4
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
rb: Open a binary file in read mode

wb: Opens or create a binary file in write mode

ab: Opens a binary file in append mode

rb+: Opens a binary file in both read and write mode

wb+: Opens a binary file in both read and write mode

ab+: Opens a binary file in both read and append mode

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
5
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

Example 1

f=open("F1.txt","w")

f.write("Techno India")

f.close()

print("File created successfully")

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
6
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
writelines(lines) method is used to write a list of strings.

Example 2

f=open("F2.txt","w")

lines=["Name:Raja Roy\n", "Dept: B.Tech (CSE)\n","Roll No: 10\n",


"Grade:A"]

f.writelines(lines)

f.close()

print("File created successfully")

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
7
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

Example 3

f=open("F3.txt","w")

f.write("Name: Raja Roy \n")

f.write("Dept: B.Tech (CSE)\n")

f.write("Roll No: 10 \n")

f.write("Grade:A")

f.close()

print("File created successfully")

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
8
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Example 4

f=open("F1.txt","r")

print("Name of the File:",f.name)

print("File is closed:",f.closed)

print("File is open in ",f.mode," mode")

f.close()

print("File is closed:",f.closed)

Output:

Name of the File: F1.txt


File is closed: False
File is open in r mode
File is closed: True Dr. Shiladitya Chowdhury
Ph.D(Computer Science & Engineering)(JU)
9
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

Example 5

f=open("F2.txt","r")

print(f.read(16))

f.close()

Output:

Name:Raja Roy
De

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
10
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Example 6

f=open("F2.txt","r")

print(f.read())

f.close()

Output:

Name:Raja Roy
Dept: B.Tech (CSE)
Roll No: 10
Grade:A

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
11
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

Example 7

f=open("F2.txt","r")
print(f.readline())
print(f.readline())
print(f.readline())
print(f.readline())
f.close()

Output:

Name:Raja Roy
Dept: B.Tech (CSE)
Roll No: 10
Grade:A

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
12
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Example 8

f=open("F2.txt","r")

print(f.readlines())

f.close()

Output:

['Name:Raja Roy\n', 'Dept: B.Tech (CSE)\n', 'Roll No: 10\n', 'Grade:A']

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
13
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

The list() method is also used to display the entire contents of the file.

Example 9

f=open("F2.txt","r")
print(list(f))
f.close()

Output:

['Name:Raja Roy\n', 'Dept: B.Tech (CSE)\n', 'Roll No: 10\n', 'Grade:A']

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
14
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Example 10

f=open("F1.txt","a")

f.write("\nDept: MCA")

f.close()

print("New data added successfully")

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
15
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

Opening Files using with keyword


F2.txt
Name:Raja Roy
Dept: B.Tech (CSE)
Roll No: 10
Grade:A

Example 11a

with open("F2.txt","r") as file:


for line in file:
print(line)
print("Is file closed:",file.closed)

Output:
Name:Raja Roy
Dept: B.Tech (CSE)
Roll No: 10
Grade:A Dr. Shiladitya Chowdhury
Is file closed: True Ph.D(Computer Science & Engineering)(JU)
16
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Example 11b

file=open("F2.txt","r")
for line in file:
print(line)
print("Is file closed:",file.closed)

Output:

Name:Raja Roy
Dept: B.Tech (CSE)
Roll No: 10
Grade:A
Is file closed: False

If the file is opened using with keyword, then after the file is used in the for
loop, it is automatically closed as soon as the block of code comprising of
the for loop is over.

But when the file is opened without the with


Dr. Shiladitya keyword, it is not closed.
Chowdhury
Ph.D(Computer Science & Engineering)(JU)
17
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

Splitting Words
In python programming, we can read lines from a file and split the line
(treated as string) based on character.
By default this character is space, but we can specify any other character to
split words in the string.

F4.txt

Techno India, Dept of MCA

Example 12

with open("F4.txt","r") as file:


line=file.readline()
words=line.split()
print(words)

Output:
Dr. Shiladitya Chowdhury
['Techno', 'India,', 'Dept', 'of',Ph.D(Computer
'MCA'] Science & Engineering)(JU) 18
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Example 13

with open("F4.txt","r") as file:


line=file.readline()
words=line.split(',')
print(words)

Output:

['Techno India', ' Dept of MCA']

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
19
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

File positions

With every file, the file management system associates a pointer often known
as file pointer that facilitates the movement across the file for reading and/or
writing data.
The file pointer specifies a location from where the current read/write
operation is initiated.
Once the read/write operation is completed, the pointer is automatically
updated.
The tell() method tells the current position within the file at which the next
read/write operation is completed.
The seek(Offset,From)

From Reference Position


0 From the beginning of the file
1 From the current position of the file
2 From the end of the file
Dr. Shiladitya Chowdhury
Ph.D(Computer Science & Engineering)(JU)
20
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Example 14

file=open("F4.txt","rb")
print("Position of file pointer before reading is:",file.tell())
print(file.read(6))
print("Position of file pointer after reading is:",file.tell())
print("Read the entire file after 3 characters from the current position of file
pointer:")
file.seek(3,1)
print(file.read())
print("Read 8 characters from the End of file:")
file.seek(-8,2)
print(file.read())
print("Read the entire file after 6 characters from the beginning of the file")
file.seek(6,0)
print(file.read())
print("Position of file pointer after reading is:",file.tell())
Dr. Shiladitya Chowdhury
Ph.D(Computer Science & Engineering)(JU)
21
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

Output:

Position of file pointer before reading is: 0


b'Techno'
Position of file pointer after reading is: 6
Read the entire file after 3 characters from the current position of file pointer:
b'dia, Dept of MCA'
Read 8 characters from the End of file:
b't of MCA'
Read the entire file after 6 characters from the beginning of the file
b' India, Dept of MCA'
Position of file pointer after reading is: 25

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
22
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Renaming and Deleting File

The os module in python has various methods that can be used to perform file-
processing operation like renaming and deleting file.

Example 15

import os
os.rename("F12.txt","F12a.txt")
print("File Renamed")

Example 16

import os
os.remove("F31.txt")
print("File Deleted")

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
23
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

Directory

The getcwd() method:

The getcwd() method is used to display the current directory.

Example 1:

import os
print("Present Directory:",os.getcwd())
Output:
Present Directory: C:\Users\Admin\PycharmProjects\Directory1

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
1
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
The mkdir() method:

The mkdir() method of the os module is used to create directories in the current
directory.

Example 2:

import os
os.mkdir("NewDir1")
print("Directory created")
print("Present Directory:",os.getcwd())

Output:

Directory created
Present Directory: C:\Users\Admin\PycharmProjects\Directory1

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
2
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

The chdir() method:

The chdir() method of the os module is used to change the current directory.

Example 3:

import os
print("Present Directory:",os.getcwd())
os.chdir("NewDir1")
print("After chdir Present Directory:",os.getcwd())

Output:

Present Directory: C:\Users\Admin\PycharmProjects\Directory1


After chdir Present Directory:
C:\Users\Admin\PycharmProjects\Directory1\NewDir1

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
3
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
The rmdir() method:

The rmdir() method of the os module is used to remove or delete a directory.

Example 4:

import os
print("Present Directory:",os.getcwd())
os.rmdir("NewDir1")
print("Directory removed")
print("Present Directory:",os.getcwd())

Output:

Present Directory: C:\Users\Admin\PycharmProjects\Directory1


Directory removed
Present Directory: C:\Users\Admin\PycharmProjects\Directory1

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
4
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

Dictionary
Dictionary is a data structure in which we store values as a pair of key and value.
Each key is separated from its value by a colon (:), can consecutive items are
separated by commas.
Example 1
d={}
print(d)
print(type(d))

Output:
{}
<class 'dict'>

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
1
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Example 2

d={"Name":"Raja Roy","Roll":11,"course":"MCA"}
print(d)

Output:

{'Name': 'Raja Roy', 'Roll': 11, 'course': 'MCA'}

Example 3

d=dict([("Name","Raja Roy"),("Roll",11),("course","MCA")])
print(d)

Output:

{'Name': 'Raja Roy', 'Roll': 11, 'course': 'MCA'}

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
2
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

Example 4

d={i:2*i for i in range(1,11)}


print(d)

Output:
{1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12, 7: 14, 8: 16, 9: 18, 10: 20}

Example 5

d={"Name":"Raja Roy","Roll":11,"course":"MCA"}
print("NAME:",d["Name"])
print("ROLL:",d["Roll"])
print("COURSE:",d["course"])

Output:

NAME: Raja Roy


ROLL: 11
Dr. Shiladitya Chowdhury
COURSE: MCA Ph.D(Computer Science & Engineering)(JU)
3
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Adding an item in a Dictionary

Example 6

d={"Name":"Raja Roy","Roll":11,"course":"MCA"}
print(d)
d["Marks"]=85
print(d)

Output:
{'Name': 'Raja Roy', 'Roll': 11, 'course': 'MCA'}
{'Name': 'Raja Roy', 'Roll': 11, 'course': 'MCA', 'Marks': 85}

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
4
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

Modifying an item in a Dictionary

Example 7

d={"Name":"Raja Roy","Roll":11,"course":"MCA"}
print(d)
d["course"]="BCA"
print(d)

Output:

{'Name': 'Raja Roy', 'Roll': 11, 'course': 'MCA'}


{'Name': 'Raja Roy', 'Roll': 11, 'course': 'BCA'}

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
5
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Deleting an item from a Dictionary

We can delete one or more items using the del keyword.

To delete all the items in a single statement, we have to use clear() function.

To remove the directory from the memory, we have to use del statement del
directory_name.

Example 8A

d={"Name":"Raja Roy","Roll":11,"course":"MCA"}
print(d)
del d["course"]
print(d)

Output:

{'Name': 'Raja Roy', 'Roll': 11, 'course': 'MCA'}


{'Name': 'Raja Roy', 'Roll': 11}Dr. Shiladitya Chowdhury
Ph.D(Computer Science & Engineering)(JU)
6
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

Example 8B

d={"Name":"Raja Roy","Roll":11,"course":"MCA"}
print(d)
d.clear()
print(d)

Output:

{'Name': 'Raja Roy', 'Roll': 11, 'course': 'MCA'}


{}

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
7
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Example 8C

d={"Name":"Raja Roy","Roll":11,"course":"MCA"}
print(d)
del d
print(d)

Output:
{'Name': 'Raja Roy', 'Roll': 11, 'course': 'MCA'}

Traceback (most recent call last):


File "C:/Users/admin/PycharmProject/Dictionary/Example8C.py", line 4, in
<module>
print(d)
NameError: name 'd' is not defined

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
8
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

We can also use pop() method to delete a particular key from the dictionary.

Example 8D

d={"Name":"Raja Roy","Roll":11,"course":"MCA"}
print(d)
d.pop("Roll")
print(d)

Output:
{'Name': 'Raja Roy', 'Roll': 11, 'course': 'MCA'}
{'Name': 'Raja Roy', 'course': 'MCA'}

Keys must have unique values. If we try to add duplicate key, then the last assignment
is retained.

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
9
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Example 9

d={"Name":"Raja Roy","Roll":11,"course":"MCA","Name":"Amit Das"}


print(d)

Output:

{'Name': 'Amit Das', 'Roll': 11, 'course': 'MCA'}

The in keyword can be used to check whether a single key is present in the directory.

Example 10

d1={"Name":"Raja Roy","Roll":11,"course":"MCA"}
if "course" in d1:
print(d1["course"])

d2={"Name":"Amit Das","Roll":15,"Gender":"Male"}
if "course" in d2:
print(d2["course"])

Output: Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
MCA 10
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

Loop over a Dictionary

Example 11

d={"Name":"Raja Roy","Roll":11,"course":"MCA"}
print(d)

print("Keys:")
for key in d:
print(key,end=' ')

print("\nValues:")
for val in d.values():
print(val,end=' ')

print("\nDictionary:")
for key,val in d.items():
print(key,val,end='; ')

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
11
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Output:

{'Name': 'Raja Roy', 'Roll': 11, 'course': 'MCA'}


Keys:
Name Roll course
Values:
Raja Roy 11 MCA
Dictionary:
Name Raja Roy; Roll 11; course MCA;

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
12
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

Nested Dictionaries

We can define a directory, inside a directory.

Example 12

d={"Raja Roy":{"Phy":90,"Chem":92,"Math":98},
"Amit Das":{"Phy":80,"Chem":85,"Math":90},
"Amal Saha":{"Phy":75,"Chem":82,"Math":88}}

print(d)

for key,val in d.items():


print(key,val,end='\n')

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
13
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Output:
{'Raja Roy': {'Phy': 90, 'Chem': 92, 'Math': 98}, 'Amit Das': {'Phy': 80, 'Chem': 85, 'Math': 90},
'Amal Saha': {'Phy': 75, 'Chem': 82, 'Math': 88}}
Raja Roy {'Phy': 90, 'Chem': 92, 'Math': 98}
Amit Das {'Phy': 80, 'Chem': 85, 'Math': 90}
Amal Saha {'Phy': 75, 'Chem': 82, 'Math': 88}

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
14
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

Conditional Branching statements

Python language supports different types of conditional branching statements


which are as follows:

if statement

if-else statement

if-elif-else statement

Nested if statement

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
1
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
if statement

Syntax of if statement
if test_expression:
statement block

Example:

a=int(input("Enter 1st No:"))


b=int(input("Enter 2nd No:"))
c=int(input("Enter 3rd No:"))
max=a
if (b>max):
max=b
if(c>max):
max=c
print("Maximum No:", max) Dr. Shiladitya Chowdhury
Ph.D(Computer Science & Engineering)(JU)
2
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

if-else statement

Syntax of if-else statement

if test_expression:
statement block 1
else:
statement block 2

Example:

age=int(input("Enter your age:"))

if (age>=18):
print("You are Adult")
else:
print("You are Not Adult")

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
3
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
if-elif-else statement

Syntax of if-elif-else statement

if test_expression 1:
statement block 1
elif test_expression 2:
statement block 2
……………..
elif test_expression n-1:
statement block (n-1)
else:
statement block n

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
4
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

Example:

m=int(input("Enter Marks:"))

if ( m>=60 and m<=100):


print("Div I")
elif(m>=45 and m<=59):
print("Div II")
elif(m>=30 and m<=44):
print("Div III")
else:
print("Fail")

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
5
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Nested if statement

If statement can be nested, i.e., can be placed one inside the another.

Example:

m=int(input("Enter Marks:"))

if(m>=0 and m<=100):


if ( m>=60 and m<=100):
print("Div I")
elif(m>=45 and m<=59):
print("Div II")
elif(m>=30 and m<=44):
print("Div III")
else:
print("Fail")
else:
print("Wrong Input")
Dr. Shiladitya Chowdhury
Ph.D(Computer Science & Engineering)(JU)
6
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

Bubble Sort

Bubble sort is one of the simplest sorting algorithms.

Bubble sort compares each pair of adjacent items and swaps them if they are in
the wrong order.

The pass through the list is repeated until no swaps are needed, that means array
is sorted.

Just like the movement of air bubbles in the water that rise up to the surface, each
element of the array move to the end in each iteration. Therefore, it is called a
bubble sort.
Example:

Program

#include<stdio.h>
#include<conio.h>
#include<alloc.h>

void main()
{ int i,n,*p;
void bubble_sort(int *,int );

clrscr();

printf("\n Enter how many elements :");


scanf("%d",&n);

p=(int *)malloc(n*sizeof(int));
if(p==NULL)
{ printf("\n Memory allocation unsuccessful");
return;
}
printf("\n Create array :");
for(i=0;i< n;i++)
{ printf("\n Enter %d th Element:",i+1);
scanf("%d",&p[i]);
}

printf("\n Before Sorting : \n");


for(i=0;i<n;i++)
{ printf(" %d ",p[i]);
}

bubble_sort(p,n);

printf("\n After Sorting : \n");


for(i=0;i<n;i++)
{ printf(" %d ",p[i]);
}

getch();
}

void bubble_sort(int *p, int n)


{ int i, j, temp;

for(i=(n-1); i>=1; i--)


{ for(j=1; j<=i; j++)
{ if(p[j-1] > p[j])
{ temp=p[j-1];
p[j-1]=p[j];
p[j]=temp;
}
}
}

}
from array import *

def BubbleSort(a,n):
for i in range(n-1,0,-1):
for j in range(1,i+1,1):
if(a[j-1]>a[j]):
a[j-1],a[j]=a[j],a[j-1]

a=array('i',[])
n=int(input("Enter how many elements:"))
for i in range(n):
x=int(input("Enter Data:"))
a.append(x)

print("Before Sorting:")
for i in range(n):
print(a[i],end=' ')

BubbleSort(a,n)

print("\nAfter Sorting:")
for i in range(n):
print(a[i],end=' ')
Basics of Python Programming

Literal Constants

The word literal has been derived from literally.

The value of a literal constant can be used directly in programs.

Numbers

Number as the name suggests, refers to a numeric value.

i) Integer

Example:
10

>>> type(10)
<class 'int'>
Dr. Shiladitya Chowdhury
Ph.D(Computer Science & Engineering)(JU)
1
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

ii) Floating point

Example:
3.14

>>> type(3.14)
<class 'float'>

iii) Complex number

Example:
2+4j

>>> type(2+4j)
<class 'complex'>

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
2
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Strings
String is a group of characters.
To use a text in Python we have to use string.
In python, string can be used in two ways:

i) Using single Quotes (‘)

>>> 'hello'
'hello'

ii) Using double Quotes (“)

>>> "hello"
'hello'

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
3
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

iii) Using triple Quotes (''')

We can specify multiline using triple quotes.

>>> ''' Welcome to the


family of
TECHNO INDIA '''

' Welcome to the\nfamily of\nTECHNO INDIA '

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
4
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
>>> print('hello')
hello

>>> print("hello")
hello

>>> print(''' Techno


Main
Saltlake''')
Techno
Main
Saltlake

>>> print("Raja's PC")


Raja's PC

>>> print('abcd "xyz"')


abcd "xyz"

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
5
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

String literal concatenation

Python concatenates two string literals that are placed side by side.

Example:

>>> print('abc' 'xyz')


abcxyz

>>> print("abc" "xyz")


abcxyz

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
6
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Unicode String

Unicode is a standard way of writing international text.

Python allows us to specify Unicode text by prefixing the string with u or U.

Example:

>>> u"ধন বাদ"


'ধন বাদ'

>>> U"ধন বাদ"


'ধন বাদ'

>>> print(u"ধন বাদ")


ধন বাদ

>>> print(U"ধন বাদ")


ধন বাদ
Dr. Shiladitya Chowdhury
Ph.D(Computer Science & Engineering)(JU)
7
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

Escape sequences

Some characters (like ‘, “”,\) connot be directly included into the string.

Such characters must be escaped by placing a backslash before them.

Example:

>>> print('Raja's PC')


SyntaxError: invalid syntax

>>> print('Raja\'s PC')


Raja's PC

>>> print("He says "I am Raja"")


SyntaxError: invalid syntax

>>> print("He says \"I am Raja\"")


He says "I am Raja"
Dr. Shiladitya Chowdhury
Ph.D(Computer Science & Engineering)(JU)
8
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
>>> print("abc \xyz")
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in
position 4-5: truncated \xXX escape
>>> print("abc \\xyz")
abc \xyz

We can use an escape sequence for the newline character (\n).


Example:
>>> print("aaa \n bbb \n ccc")
aaa
bbb
ccc

>>> print("aaa\nbbb\nccc")
aaa
bbb
ccc
Dr. Shiladitya Chowdhury
Ph.D(Computer Science & Engineering)(JU)
9
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

We can use an escape sequence (\t) to insert tab into the string.

Example:
>>> print("aaa\tbbb\tccc")

aaa bbb ccc

If a single backslash (\) at the end of the string is added, then it indicates that
the string is continued in the next line, but no new line is added.

Example:

>>> print("Welcome to \
Techno India")

Welcome to Techno India

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
10
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Raw Strings

To specify a string that should not handle any escape sequences and want to
display exactly as specified ; then the string should be specified as raw string.

Example:

>>> print(r"abc \n xyz's \t pqr")

abc \n xyz's \t pqr

>>> print(R"abc \n xyz's \t pqr")

abc \n xyz's \t pqr

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
11
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

String formatting

The built-in function format() can be used to control the display of the string.

Example:

The string ‘hello’ is displayed as left-justified, right-justified, and center-


aligned in a field with 10 characters.

>>> format('hello','<10')
'hello '

>>> format('hello','>10')
' hello'

>>> format('hello','^10')
' hello '

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
12
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
>>> format("hello","<10")
'hello ‘

>>> format("hello",">10")
' hello'

>>> format("hello","^10")
' hello '

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
13
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

Data Type

Python supports 5 standard data types:

Number
String
List
Tuple
Dictionary

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
14
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Variables
Variables are reserved memory locations that store values.

For naming variables we should obey following rules:

i) The first character of an variable must be an underscore(‘_’) or letter (upper or


lower case).

ii) Rest of the character name can be underscore(‘_’), letter (upper or lower
case) and digits( 0 to 9).

iii) Variables are case sensitive

iv) Punctuation character (such as @ $ % ) are not allowed within variables.

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
15
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

Prog. 1:

# Display data of different types using variables and literal constants


i=10
f=3.14
c=4+8j
msg="hello"

print("i=",i,"Datatype:",type(i))
print("f=",f,"Datatype:",type(f))
print("c=",c,"Datatype:",type(c))
print("msg=",msg,"Datatype:",type(msg))

Output:

i= 10 Datatype: <class 'int'>


f= 3.14 Datatype: <class 'float'>
c= (4+8j) Datatype: <class 'complex'>
msg= hello Datatype: <class 'str'>
Dr. Shiladitya Chowdhury
Ph.D(Computer Science & Engineering)(JU)
16
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Prog. 2:

# Reassign values to a variable

x=10
print("x=",x,type(x))
x=3.14
print("x=",x,type(x))
x=4+8j
print("x=",x,type(x))
x="hello"
print("x=",x,type(x))

Output:

x= 10 <class 'int'>
x= 3.14 <class 'float'>
x= (4+8j) <class 'complex'>
x= hello <class 'str'>
Dr. Shiladitya Chowdhury
Ph.D(Computer Science & Engineering)(JU)
17
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

Multiple Assignments

In python we can assign single value to more than one variable


simultaneously.

Example

>>> a=b=c=d=0
>>> print("a=",a,"b=",b,"c=",c,"d=",d)

a= 0 b= 0 c= 0 d= 0

We can also assign different values to multiple variables simultaneously.

Example

>>> a,b,c,d=10,3.14,4+5j,"xyz"
>>> print("a=",a,"b=",b,"c=",c,"d=",d)
Dr. Shiladitya Chowdhury
a= 10 b= 3.14 c= (4+5j) d=Ph.D(Computer
xyz Science & Engineering)(JU)
18
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Trying to reference a variable that has not been assigned any value causes an
error.

Example

>>> print(y)
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
print(y)
NameError: name 'y' is not defined

>>> x=10
>>> print(x)
10

>>> del x
>>> print(x)
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
print(x) Dr. Shiladitya Chowdhury
Ph.D(Computer Science & Engineering)(JU)
NameError: name 'x' is not defined 19
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

Multiple statements on a single line

In python we can specify more than one statements in a single line using
semicolon (;).

Example

>>> s="abc" print(s)


SyntaxError: invalid syntax

>>> s="abc" ; print(s)


abc

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
20
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Boolean
Boolean is another data type in python.
A variable in boolean can have one of the two values- True or False
Example
>>> x=True
>>> x
True
>>> type(x)
<class 'bool'>
>>> x=False
>>> x
False
>>> 20==20
True
>>> 20==30
False Dr. Shiladitya Chowdhury
Ph.D(Computer Science & Engineering)(JU)
21
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

Input operation
Prog.
# Read variables from user
name=input("Enter your Name:")
age=input("Enter your age:")

print("Your Name:",name,"Age:",age)

Output:
Enter your Name:Raja Roy
Enter your age:35
Your Name: Raja Roy Age: 35

Comments

Comments are the non-executable statements in a program.


In python, a hash sign (#) begins a comment.
Dr. Shiladitya Chowdhury
Ph.D(Computer Science & Engineering)(JU)
22
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Keywords

Python programming language has following keywords:

>>> help("keywords")

Here is a list of the Python keywords. Enter any keyword to get more help.
False class from or
None continue global pass
True def if raise
and del import return
as elif in try
assert else is while
async except lambda with
await finally nonlocal yield
break for not

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
23
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

Operators

Arithmetic Operators

Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
// Floor Division
** Exponent

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
24
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
>>> a=5
>>> b=3
>>> a+b
8
>>> a-b
2
>>> a*b
15
>>> a/b
1.6666666666666667
>>> a%b
2
>>> a//b
1
>>> a**b
125 Dr. Shiladitya Chowdhury
Ph.D(Computer Science & Engineering)(JU)
25
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

Comparison Operators

Operator Description
== Returns True if two values are exactly equal
!= Returns True if two values are not equal
> Returns True if value of the left side operand is
greater than value of the right side operand
>= Returns True if value of the left side operand is
greater than or equal to value of the right side
operand
< Returns True if value of the left side operand is less
than value of the right side operand
<= Returns True if value of the left side operand is less
than or equal to value of the right side operand
Dr. Shiladitya Chowdhury
Ph.D(Computer Science & Engineering)(JU)
26
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
>>> a=5
>>> b=3
>>> print(a==b)
False

>>> print(a!=b)
True

>>> print(a>b)
True

>>> print(a>=b)
True

>>> print(a<b)
False

>>> print(a<=b)
False
Dr. Shiladitya Chowdhury
Ph.D(Computer Science & Engineering)(JU)
27
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

Assignment Operators

Operator Description
= Assign value of the right side operand to the value of the
left side operand
+= Addition and assign
-= Subtraction and assign
*= Multiplication and assign
/= Division and assign
%= Modulus and assign
//= Floor Division and assign
**= Exponent and assign

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
28
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
>>> a=10
>>> r=a
>>> r
10
>>> a=10
>>> b=7
>>> a+=b
>>> print("a=",a,"b=",b)
a= 17 b= 7
>>> a=10
>>> b=7
>>> a-=b
>>> print("a=",a,"b=",b)
a= 3 b= 7
>>> a=10
>>> b=7
>>> a*=b
>>> print("a=",a,"b=",b)
Dr. Shiladitya Chowdhury
a= 70 b= 7 Ph.D(Computer Science & Engineering)(JU)
29
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

>>> a=10
>>> b=7
>>> a/=b
>>> print("a=",a,"b=",b)
a= 1.4285714285714286 b= 7
>>> a=10
>>> b=8
>>> a%=b
>>> print("a=",a,"b=",b)
a= 2 b= 8
>>> a=10
>>> b=4
>>> a//=b
>>> print("a=",a,"b=",b)
a= 2 b= 4
>>> a=2
>>> b=6
>>> a**=b
>>> print("a=",a,"b=",b) Dr. Shiladitya Chowdhury
Ph.D(Computer Science & Engineering)(JU)
a= 64 b= 6 Assistant Professor, Dept. of MCA
30
Techno Main Saltlake, Kolkata 700091
Tuple
Tuple is a sequence of immutable objects.
We can change the value of one or more items in a list, but we cannot change the value in
tuple.
To create a tuple with single element we have to add a comma after the element. In absence
of comma, python treats the element as an ordinary data type.
Example 1
t1=()
print(t1)
print(type(t1))

t2=(10,20,30)
print(t2)
print(type(t2))

t3=(10)
print(t3) Dr. Shiladitya Chowdhury
print(type(t3)) Ph.D(Computer Science & Engineering)(JU)
1
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

t4=(10,)
print(t4)
print(type(t4))

Output:

()
<class 'tuple'>
(10, 20, 30)
<class 'tuple'>
10
<class 'int'>
(10,)
<class 'tuple'>

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
2
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Utility of Tuples

Tuples are very useful for representing records or structures.

These structure store related information about a subject together.

The information belongs to different datatypes.

Example 2

t=("Raja Roy","CSE",10,80.75)
print(t)

Output:

('Raja Roy', 'CSE', 10, 80.75)

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
3
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

Some built-in functions return a tuple.

For example divmod() function returns two values – quotient and remainder after
performing division operation.

Example 3A
t=divmod(10,3)
print(t)

Output:
(3, 1)

Example 3B

q,r=divmod(10,3)
print("Quotient=",q)
print("Remainder=",r)

Output:
Quotient= 3
Remainder= 1
Dr. Shiladitya Chowdhury
Ph.D(Computer Science & Engineering)(JU)
4
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Accessing values in a Tuple

Tuple is also started at zero (0).

We can perform operations like slice, concatenate, etc. on a tuple.

Example 4

t=(11,22,33,44,55,66,77,88,99,110)
print("t[3:6]:",t[3:6])
print("t[:4]:",t[:4])
print("t[5:]:",t[5:])
print("t[:]:",t[:])

Output:
t[3:6]: (44, 55, 66)
t[:4]: (11, 22, 33, 44)
t[5:]: (66, 77, 88, 99, 110)
t[:]: (11, 22, 33, 44, 55, 66, 77, 88, 99, 110)
Dr. Shiladitya Chowdhury
Ph.D(Computer Science & Engineering)(JU)
5
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

Updating Tuple

Tuple is immutable, so the value in the tuple cannot be changed.

We can only extract values from a tuple to form a tuple.

Example 5

t1=(1,2,3,4,5)
t2=(10,20,30,40,50)
t3=t1+t2
print("t3:",t3)

Output:

t3: (1, 2, 3, 4, 5, 10, 20, 30, 40, 50)

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
6
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Tuple Assignment
Tuple assignment allows a tuple of variables on the left side of the assignment operator
to be assigned values from a tuple given on the right side of the assignment operator.
In case, an expression is specified on the right side of the assignment operator, first the
expression is evaluated and then assignment is done.

Example 8
(a,b,c)=(11,22,33)
print("a=",a,"b=",b,"c=",c)
t=(10,20,30)
(a,b,c)=t
print("a=",a,"b=",b,"c=",c)
(a,b,c)=(2+3,2*5,2/5)
print("a=",a,"b=",b,"c=",c)

Output:
a= 11 b= 22 c= 33
a= 10 b= 20 c= 30 Dr. Shiladitya Chowdhury
a= 5 b= 10 c= 0.4 Ph.D(Computer Science & Engineering)(JU)
7
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

While assigning values on a tuple, we must ensure that the number of values on both side of
the assignment operator are same, otherwise an error will be generated.

Example 8A

(a,b,c)=(11,22)
print("a=",a,"b=",b,"c=",c)

Output:

Traceback (most recent call last):


File "C:/Users/admin/PycharmProject/Tuples/Example8A.py", line 1, in <module>
(a,b,c)=(11,22)
ValueError: not enough values to unpack (expected 3, got 2)

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
8
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Tuple for returning multiple values
When function returns multiple values, then we can group together multiple values
and return them together.

Example 9

def max_min(tup):
x=max(tup)
y=min(tup)
return x,y

t=(10,20,30,70,25,5,55)
max_val,min_val=(max_min(t))
print("Max=",max_val)
print("Min=",min_val)
r=max_min(t)
print(r)

Output:
Max= 70
Min= 5 Dr. Shiladitya Chowdhury
Ph.D(Computer Science & Engineering)(JU)
(70,5) Assistant Professor, Dept. of MCA
9
Techno Main Saltlake, Kolkata 700091

Nested Tuples

Python allows us to define a tuple inside another tuple. This is called nested
tuple.

Example 10

t=(("abc",11,3.14),("xyz",12,5.11),("pqr",15,7.45))
for i in t:
print(i)

Output:

('abc', 11, 3.14)


('xyz', 12, 5.11)
('pqr', 15, 7.45)
Dr. Shiladitya Chowdhury
Ph.D(Computer Science & Engineering)(JU)
10
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Checking the index: index() method

Example 11

t=(11,22,33,44,55,66, 44,77,88,77)
print("Index of 44 is=",t.index(44))
l=t.index(77)
print("Index of 77 is=",l)

Output:

Index of 44 is= 3
Index of 77 is= 6

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
11
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

Checking the Elements: count() method

Example 12

t=(11,22,33,44,55,66,77,88,33,11,77,11,66,11,44)
print("Occurrence of 44=",t.count(44))
print("Occurrence of 11=",t.count(11))
print("Occurrence of 77=",t.count(77))

Output:

Occurrence of 44= 2
Occurrence of 11= 4
Occurrence of 77= 2

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
12
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
List Comprehension and Tuples

We can use the list comprehension technique to manipulate the values in


one tuple.

Example 13

def double(T):
return([i*2 for i in T])

tup=(1,2,3,4,5)
print("Initial Tuple:",tup)
print("Double values:",double(tup))

Output:

Initial Tuple: (1, 2, 3, 4, 5)


Double values: [2, 4, 6, 8, 10]
Dr. Shiladitya Chowdhury
Ph.D(Computer Science & Engineering)(JU)
13
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

Variable length Argument Tuples

Variable length arguments are especially useful in defining functions that are applicable to
a large variety of arguments.

Any arguments that starts with a ‘*’ symbol is known as gather and specifies a variable-
length arguments.

Example 14

def display(*args):
print(args)

t1=(11,22,33,44,55)
display(t1)

t2=(10,20,30,40,50)
display(t2)

Output:

((11, 22, 33, 44, 55),) Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
((10, 20, 30, 40, 50),) Assistant Professor, Dept. of MCA
14
Techno Main Saltlake, Kolkata 700091
The opposite of gather is scatter.

If a function accepts multiple arguments but not a tuple, then the tuple is
scattered to pass individual elements.

Example 15A

t=(11,3)
q,r=divmod(t)
print("Result=",q,"Remainder=",r)

Output:
Traceback (most recent call last):
File "C:/Users/admin/PycharmProject/Tuples/Example15A.py", line 2, in
<module>
q,r=divmod(t)
TypeError: divmod expected 2 arguments, got 1

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
15
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

Example 15B

t=(11,3)
q,r=divmod(*t)
print("Result=",q,"Remainder=",r)

Output:

Result= 3 Remainder= 2

In Example 15A, only tuple was passed (as a single argument) but the divmod()
accepts two arguments, therefore the error occurs.

While in Example 15B, the symbol ‘*’ denotes that there may be more than one
argument.

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
16
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
The zip() function

The zip() is a built-in function that takes two or more sequence and zips them.

The new sequence thus formed has one element from each sequence.

Example 16A

t1=(1,2,3,4,5)
t2=('a','b','c','d','e')

tup=tuple(zip(t1,t2))
print(tup)

Output:
((1, 'a'), (2, 'b'), (3, 'c'), (4, 'd'), (5, 'e'))

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
17
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

If the two sequences have different length, then the result has the length of
the shorter one.

Example 16A

t1=(1,2,3,4,5)
t2=('a','b','c')

tup=tuple(zip(t1,t2))
print(tup)

Output:

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

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
18
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
The sorted() function

Tuples are immutable, so they don’t support sort() function.

Python has a built-in function sorted() which takes any sequence as a


parameter and returns a new list with the same elements but sorted
order.

Example 17

t=(20,50,30,10,40)
print(sorted(t))
print(t)

Output:

[10, 20, 30, 40, 50]


(20, 50, 30, 10, 40)
Dr. Shiladitya Chowdhury
Ph.D(Computer Science & Engineering)(JU)
19
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

String
Built-in string functions in Python

capitalize()

str="hello"
print(str.capitalize())

Output:

Hello

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
1
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
center()
str="hello"
print(str.center(10,'*'))

Output:

**hello***

count()

str="hello”
msg="hello world hello India"
print(msg.count(str,0,len(msg)))

Output:

Dr. Shiladitya Chowdhury


2 Ph.D(Computer Science & Engineering)(JU)
2
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

endswith()

str="hello"
msg="hello world hello India"

print(msg.endswith(str,0,len(msg)))
print(msg.endswith("dia",0,len(msg)))

Output:

False
True

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
3
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
startswith()

str="hello"
msg="hello world hello India"

print(msg.startswith(str,0,len(msg)))
print(msg.startswith("dia",0,len(msg)))

Output:

True
False

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
4
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

find() and rfind()

s=“abcd pqr xyz abcd"

print(s.find(“abcd",0,len(s)))
print(s.find(“mnop",0,len(s)))

print(s.rfind(“abcd",0,len(s)))
print(s.rfind(“mnop",0,len(s)))

Output:

0
-1
13
-1

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
5
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
index() and rindex()
s=“abcd pqr xyz abcd"

print(s.index(“abcd",0,len(s)))
print(s.rindex(“abcd",0,len(s)))

Output:

0
13

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
6
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

isalnum()

msg="MCA2021"
print(msg.isalnum())

msg="MCA 2021"
print(msg.isalnum())

Output:

True
False

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
7
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
isalpha()
msg="Mca"
print(msg.isalpha())

msg="MCA2021"
print(msg.isalpha())

Output:

True
False

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
8
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

isdigit()

msg="2021"
print(msg.isdigit())

msg="MCA2021"
print(msg.isdigit())

Output:

True
False

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
9
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
islower()

msg="MCA"
print(msg.islower())

msg="mca"
print(msg.islower())

Output:

False
True

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
10
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

isupper()

msg="MCA"
print(msg.isupper())

msg="mca"
print(msg.isupper())

Output:

True
False

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
11
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
isspace()

msg="MCA 2021"
print(msg.isspace())

msg=" "
print(msg.isspace())

Output:

False
True

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
12
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

ljust() and rjust()

str="Hello"
print(str.ljust(10,'*'))
print(str.rjust(10,'*'))

Output:

Hello*****

*****Hello

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
13
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
zfill()

str="Hello"
print(str.zfill(10))

Output:

00000Hello

upper() and lower()

str="Hello"
print(str.upper())
print(str)
print(str.lower())

Output:

HELLO
Hello Dr. Shiladitya Chowdhury
Ph.D(Computer Science & Engineering)(JU)
hello Assistant Professor, Dept. of MCA
14
Techno Main Saltlake, Kolkata 700091

lstrip(), rstrip() and strip()

str=" Hello"
print(str.lstrip())

print(str)

str=" Hello "


print(str.rstrip())

print(str)
print(str.strip())

Output:

Hello
Hello
Hello
Hello Dr. Shiladitya Chowdhury
Ph.D(Computer Science & Engineering)(JU)
Hello Assistant Professor, Dept. of MCA
15
Techno Main Saltlake, Kolkata 700091
max() and min()

str="Have a nice day"


print(max(str))
print(min(str))

str="hello"
print(max(str))
print(min(str))

Output:
y

o
e

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
16
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

replace()
str="He is a good boy"
print(str.replace("good","bad"))
print(str)

Output:

He is a bad boy
He is a good boy

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
17
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
title()
str="He is a good boy"
print(str.title())
print(str)

Output:

He Is A Good Boy
He is a good boy

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
18
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

swapcase()
str="AaBbCcDd"
print(str.swapcase())
print(str)

Output:

aAbBcCdD
AaBbCcDd

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
19
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Sets
Sets are very similar to lists, but we cannot store duplicate elements in sets.
Set is a mutable and an unordered collection of items.
A set is created by placing all the elements inside curly brackets {}, separated by comma
or by using the built-in function set().

Example 1
s={10,3.14,"abcd"}
print(s)

Output:
{3.14, 10, 'abcd'}

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
1
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

Example 2

lst=[1,2,3]
print(set(lst))

t=(10,20,30)
print(set(t))

s="xyz"
print(set(s))

Output:

{1, 2, 3}
{10, 20, 30}
{'z', 'y', 'x'}

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
2
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
We can perform union, intersection, set difference operations on sets.

Example 3

A={10,20,30,40,50}
B={30,50,70,90}

print("A UNION B:",A.union(B))


print("A INTERSECTION B:",A.intersection(B))
print("A DIFFERENCE B:",A.difference(B))

Output:

A UNION B: {70, 40, 10, 50, 20, 90, 30}


A INTERSECTION B: {50, 30}
A DIFFERENCE B: {40, 10, 20}

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
3
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

A set cannot contain other mutable objects.

Example 4

s={10,20,30,{11,22}}
print(s)

Output:

Traceback (most recent call last):


File "C:/Users/admin/PycharmProject/Set/Example4.py", line 1, in
<module>
s={10,20,30,{11,22}}
TypeError: unhashable type: 'set'

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
4
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
To make an empty set, you cannot write s={}, because python will make this
as a directory.

Therefore, to create an empty set, we have to use set().

Example 5

s=set()
print(s)
print(type(s))

t={}
print(t)
print(type(t))

Output:

set()
<class 'set'>
{} Dr. Shiladitya Chowdhury
Ph.D(Computer Science & Engineering)(JU)
<class 'dict'> Assistant Professor, Dept. of MCA
5
Techno Main Saltlake, Kolkata 700091

Sets are unordered, so indexing have no meaning.

Set operations do not allow users to access or change an element using indexing or
slicing.

Example 6

s={10,20,30,40,50}
print(s[0])

Output:

Traceback (most recent call last):


File "C:/Users/admin/PycharmProject/Set/Example6.py", line 2, in <module>
print(s[0])
TypeError: 'set' object does not support indexing

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
6
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
We can iterate through each item in the set using for loop.

Example 7

s={11,22,33,44}
for i in s:
print(i)

Output:

33
11
44
22

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
7
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

Selection Sort

In selection sort, the smallest value among the unsorted elements of the array is
selected in every pass and inserted to its appropriate position into the array.

First, find the smallest element of the array and place it on the first position.

Then, find the second smallest element of the array and place it on the second
position.

The process continues until we get the sorted array.

The array with n elements is sorted by using n-1 pass of selection sort algorithm.
Example:

#include<stdio.h>
#include<conio.h>
#include<alloc.h>

void main()
{ int i,n,*p;
void selection_sort(int *,int );

clrscr();

printf("\n Enter how many elements :");


scanf("%d",&n);

p=(int *)malloc(n*sizeof(int));
if(p==NULL)
{ printf("\n Memory allocation unsuccessful");
return;
}
printf("\n Create array :");
for(i=0;i< n;i++)
{ printf("\n Enter %d th Element:",i+1);
scanf("%d",&p[i]);
}

printf("\n Before Sorting : \n");


for(i=0;i<n;i++)
{ printf(" %d ",p[i]);
}

selection_sort(p,n);

printf("\n After Sorting : \n");


for(i=0;i<n;i++)
{ printf(" %d ",p[i]);
}

getch();
}

void selection_sort(int *p, int n)


{ int i,j,min,temp;

for (i=0;i<n-1;i++)
{ min=i;
for(j=i+1;j<n;j++)
{ if(p[j] < p[min])
{ min=j;
}
}

temp=p[i];
p[i]=p[min];
p[min]=temp;
}

}
from array import *

def SelectionSort(a,n):
for i in range(0,n,1):
min=i
for j in range(i+1,n,1):
if(a[j] < a[min]):
min=j

a[i],a[min]=a[min],a[i]

a=array('i',[])
n=int(input("Enter how many elements:"))
for i in range(n):
x=int(input("Enter Data:"))
a.append(x)

print("Before Sorting:")
for i in range(n):
print(a[i],end=' ')

SelectionSort(a,n)

print("\nAfter Sorting:")
for i in range(n):
print(a[i],end=' ')
Module

Module allows us to reuse one or more functions in a program, even in the


program in which those functions have not been defined.

A module may contain definition for many variable and functions.

When we import a module, we can use any variable or function defined in that
module.

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
1
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

Example 1

from math import sqrt

n=int(input("Enter No:"))
r=sqrt(n)
print("Result=",r)

Output:

Enter No:81
Result= 9.0

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
2
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Example 2

from math import sqrt as square_root

n=int(input("Enter No:"))
r=square_root(n)
print("Result=",r)

Output:

Enter No:90
Result= 9.486832980505138

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
3
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

Example 3

from math import *

n=int(input("Enter No:"))
r=sqrt(n)
print("Result=",r)

n=int(input("Enter No:"))
e=int(input("Enter exponent:"))

r=pow(n,e)
print("Result=",r)

print("PI=",pi)

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
4
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Output:

Enter No:70
Result= 8.366600265340756
Enter No:2
Enter exponent:5
Result= 32.0
PI= 3.141592653589793

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
5
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

Name of Module
Every module has a name.

We can find the name of a module by using the __name__ attribute of the module.

Example 4

def display():
print("In Function:Name of Module is:",__name__)

print("Hello")
print("Name of Module is:",__name__)
display()

Output:

Hello
Name of Module is: __main__
In Function:Name of Module is: __main__
Dr. Shiladitya Chowdhury
Ph.D(Computer Science & Engineering)(JU)
6
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Command line arguments

Python allows us to pass command line arguments to a program.


This can be done using sys module.

Example 5

import sys

a=int(sys.argv[1])
b=int(sys.argv[2])

r=a+b
print("Result=",r)

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
7
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

Output:

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
8
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Making own Module
We can create as many modules as we want.
Every Python program is a module, i.e., every file we save as .py extension is a
module.
Example 6

calc1.py

def add(x,y):
return x+y

def sub(x,y):
return x-y

def mult(x,y):
return x*y

def div(x,y):
Dr. Shiladitya Chowdhury
return x/y Ph.D(Computer Science & Engineering)(JU)
9
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

Example6.py

from calc1 import *

a=int(input("Enter 1st No:"))


b=int(input("Enter 2nd No:"))

r=add(a,b)
print(a,"+",b,"=",r)

r=sub(a,b)
print(a,"-",b,"=",r)

r=mult(a,b)
print(a,"*",b,"=",r)

r=div(a,b)
print(a,"/",b,"=",r)
Dr. Shiladitya Chowdhury
Ph.D(Computer Science & Engineering)(JU)
10
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Output:

Enter 1st No:10


Enter 2nd No:3
10 + 3 = 13
10 - 3 = 7
10 * 3 = 30
10 / 3 = 3.3333333333333335

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
11
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

Example 7

MyModule1.py

def display():
print("Hello")
print("In Called function:")
print("Name of Module is:", __name__)

Example7.py

from MyModule1 import *

print("Welcome")
print("Name of the Calling Module is:",__name__)
display()

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
12
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Output:

Welcome
Name of the Calling Module is: __main__
Hello
In Called function:
Name of Module is: MyModule1

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
13
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

Example 8

MyModule1.py

def display():
print("Hello")
print("In Called function:")
print("Name of Module is:", __name__)

MyModule2.py

def display():
print("Hi")
print("In Called function:")
print("Name of Module is:", __name__)

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
14
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Example8.py

from MyModule1 import *


from MyModule2 import *

print("Welcome")
print("Name of the Calling Module is:",__name__)
display()

Output:

Welcome
Name of the Calling Module is: __main__
Hi
In Called function:
Name of Module is: MyModule2

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
15
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

Example 9

from MyModule1 import *


from MyModule2 import *

print("Welcome")
print("Name of the Calling Module is:",__name__)
MyModule1.display()
MyModule2.display()

Output:

Traceback (most recent call last):


File "C:/Users/Admin/PycharmProjects/Module/Example9.py", line 6, in
<module>
MyModule1.display()
NameError: name 'MyModule1' is not defined
Welcome
Name of the Calling Module is: __main__
Dr. Shiladitya Chowdhury
Ph.D(Computer Science & Engineering)(JU)
16
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Example 10

import MyModule1
import MyModule2

print("Welcome")
print("Name of the Calling Module is:",__name__)
MyModule1.display()
MyModule2.display()

Output:

Welcome
Name of the Calling Module is: __main__
Hello
In Called function:
Name of Module is: MyModule1
Hi
In Called function:
Dr. Shiladitya Chowdhury
Name of Module is: MyModule2
Ph.D(Computer Science & Engineering)(JU)
17
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

Example 11

Generate 10 Random numbers between 1 to 100

import random

for i in range(10):
value=random.randint(1,100)
print(value,end=" ")

Output:

48 20 50 15 22 30 2 12 42 24

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
18
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Local, Global and Built-in Namespaces

When the python interpreter sees an identifier, it first searches the local
namespace, then the global namespace and finally the built-in namespace.

If two identifier with the same name are defined in more than one of these
namespace, then it will follow the above mentioned rule.

Example 12.1

num=[2,5,10,7]
print("Sum of the numbers=",sum(num))
print("Max numbers=",max(num))
print("Min numbers=",min(num))

Output:

Sum of the numbers= 24


Max numbers= 10
Min numbers= 2 Dr. Shiladitya Chowdhury
Ph.D(Computer Science & Engineering)(JU)
19
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

Example 12.2

def sum(n):
print("Now in USER DEFINED sum function")
s=0
for i in n:
s=s+i
return s

num=[2,5,10,7]
print("Sum of the numbers=",sum(num))
print("Max numbers=",max(num))
print("Min numbers=",min(num))

Output:

Now in USER DEFINED sum function


Sum of the numbers= 24
Max numbers= 10 Dr. Shiladitya Chowdhury
Min numbers= 2 Ph.D(Computer Science & Engineering)(JU)
20
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Example 13

import calendar
import time

print(calendar.month(2021,3))
print(time.asctime(time.localtime(time.time())))

Output:

March 2021
Mo Tu We Th Fr Sa Su
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31

Mon Mar 29 12:44:55 2021


Dr. Shiladitya Chowdhury
Ph.D(Computer Science & Engineering)(JU)
21
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

You might also like