Python HOD GAR
Python HOD GAR
Output:
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:
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: []
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:
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
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
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))
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))
list8=sorted(list5)
print(list8)
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:
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:
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)
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:
Note:
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:
List Comprehensions
Example 12
cubes=[]
for i in range(6):
cubes.append(i**3)
print("Cubes:",cubes)
Output:
Python also supports computed lists called list comprehensions having the following
syntax:
Output:
Example 13
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]
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
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
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
Functional programming
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)
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:
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.
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]
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:
Example 17
import functools
def add(x,y):
return x+y
num_list=[10,20,30,40,50]
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.
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.
Syntax:
Example 1
print("Result=",add(a,b))
Output:
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.
Example 2
def max(x,y):
if x>y:
return x
else:
return y
add=lambda x,y:x+y
sub=lambda x,y:x-y
print("Result=",max(add(a,b),sub(a,b)))
Output:
def increment(x):
return (lambda a:a+1)(x)
n=int(input("Enter No:"))
print("Result=",increment(n))
Output:
Enter No:10
Result= 11
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
x=lambda: sum(range(1,11))
print("Result=",x())
Output:
Result= 55
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
While loop
Syntax:
while condition:
statement block
Example 1
i=1
while i<=5:
print("Techno India")
i=i+1
Output:
Techno India
Techno India
Techno India
Techno India
Techno India
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
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:
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
for i in t:
print(i)
Output:
P
XYZ
10.22
11
d={"A":1,"B":2,"C":3,"D":4}
for i in d:
print(i)
Output:
A
B
C
D
Example 4D
x="abcde"
for i in x:
print(i)
Output:
a
b
c
d
e
The range() is a built-in function in Python that used to iterate over a sequence
of numbers.
Example 5A
for i in range(11,21,3):
print(i)
Output:
11
14
17
20
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:
n=int(input("Enter No:"))
f=1
if n>=0:
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 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
Example 10:
for i in range(1,11):
if(i%2==0):
pass
else:
print(i)
1
3
5
7
9
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
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
Example 2
def add(x,y):
r=x+y
print("Result",r)
add(a,b)
Output:
def add(x,y):
s=x+y
return s
r=add(a,b)
print("Result=",r)
Output:
Example 4.1
def add(x,y):
s=x+y
return s
addition=add
r=addition(a,b)
print("Result=",r)
Output:
def display():
print("ABCD")
return
print("XYZ")
display()
Output:
ABCD
Example 4.3
def display():
print("Hello")
return
display()
print(display())
Output:
Hello
Hello
None
Example 5
def add_sub(x,y):
c=x+y
d=x-y
return c,d
r1,r2=add_sub(a,b)
print("Result of Addition=",r1)
print("Result of Subtraction=",r2)
Output:
def swap(x,y):
return y,x
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:
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:
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
update(lst)
Output:
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
update(tup)
Output:
Global variables are those variables which are defined in the main body of the
program file.
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:
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:
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:
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
def add(x,y):
r=x+y
print("Result",r)
add(a,b)
Output:
Example 3
def add(x,y):
s=x+y
return s
r=add(a,b)
print("Result=",r)
Output:
def add(x,y):
s=x+y
return s
addition=add
r=addition(a,b)
print("Result=",r)
Output:
Example 4.2
def display():
print("ABCD")
return
print("XYZ")
display()
Output:
ABCD
def display():
print("Hello")
return
display()
print(display())
Output:
Hello
Hello
None
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
r1,r2=add_sub(a,b)
print("Result of Addition=",r1)
print("Result of Subtraction=",r2)
Example 6
def swap(x,y):
return y,x
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:
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:
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
update(lst)
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
update(tup)
Global variables are those variables which are defined in the main body of the
program file.
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:
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:
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:
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
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()
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:
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:
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:
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
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
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")
Output:
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")
Output:
a= 5
b: (10, 20, 30)
10
20
30
a= Arun Dutta
b: ('Biology', 'Mathematics', 'Physics', 'Chemistry')
Biology
Mathematics
Physics
Chemistry
Recursion one can solve problems in easy way while its iterative solution
is very big and complex.
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")
Enter No:6
Result= 720
Enter No:-4
Wrong Input
Function redefinition
We can redefine function in Python programming language.
Example 1
def add(x,y):
s=x+y
return s
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)
Output:
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.
Types of File
Python supports two types of files: text files and binary files.
Text file
As text files can process characters, they can only read or write data one
character at a time.
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.
Opening a file
Example 1
f=open("F1.txt","w")
f.write("Techno India")
f.close()
Example 2
f=open("F2.txt","w")
f.writelines(lines)
f.close()
Example 3
f=open("F3.txt","w")
f.write("Grade:A")
f.close()
f=open("F1.txt","r")
print("File is closed:",f.closed)
f.close()
print("File is closed:",f.closed)
Output:
Example 5
f=open("F2.txt","r")
print(f.read(16))
f.close()
Output:
Name:Raja Roy
De
f=open("F2.txt","r")
print(f.read())
f.close()
Output:
Name:Raja Roy
Dept: B.Tech (CSE)
Roll No: 10
Grade:A
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
f=open("F2.txt","r")
print(f.readlines())
f.close()
Output:
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:
f=open("F1.txt","a")
f.write("\nDept: MCA")
f.close()
Example 11a
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.
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
Example 12
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
Output:
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)
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:
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")
Directory
Example 1:
import os
print("Present Directory:",os.getcwd())
Output:
Present Directory: C:\Users\Admin\PycharmProjects\Directory1
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
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:
Example 4:
import os
print("Present Directory:",os.getcwd())
os.rmdir("NewDir1")
print("Directory removed")
print("Present Directory:",os.getcwd())
Output:
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'>
d={"Name":"Raja Roy","Roll":11,"course":"MCA"}
print(d)
Output:
Example 3
d=dict([("Name","Raja Roy"),("Roll",11),("course","MCA")])
print(d)
Output:
Example 4
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:
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}
Example 7
d={"Name":"Raja Roy","Roll":11,"course":"MCA"}
print(d)
d["course"]="BCA"
print(d)
Output:
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:
Example 8B
d={"Name":"Raja Roy","Roll":11,"course":"MCA"}
print(d)
d.clear()
print(d)
Output:
d={"Name":"Raja Roy","Roll":11,"course":"MCA"}
print(d)
del d
print(d)
Output:
{'Name': 'Raja Roy', 'Roll': 11, 'course': 'MCA'}
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.
Output:
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"])
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='; ')
Nested Dictionaries
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)
if statement
if-else statement
if-elif-else statement
Nested if statement
Syntax of if statement
if test_expression:
statement block
Example:
if-else statement
if test_expression:
statement block 1
else:
statement block 2
Example:
if (age>=18):
print("You are Adult")
else:
print("You are Not Adult")
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
Example:
m=int(input("Enter Marks:"))
If statement can be nested, i.e., can be placed one inside the another.
Example:
m=int(input("Enter Marks:"))
Bubble Sort
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();
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]);
}
bubble_sort(p,n);
getch();
}
}
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
Numbers
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
Example:
3.14
>>> type(3.14)
<class 'float'>
Example:
2+4j
>>> type(2+4j)
<class 'complex'>
>>> 'hello'
'hello'
>>> "hello"
'hello'
>>> print("hello")
hello
Python concatenates two string literals that are placed side by side.
Example:
Example:
Escape sequences
Some characters (like ‘, “”,\) connot be directly included into the string.
Example:
>>> 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")
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")
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:
String formatting
The built-in function format() can be used to control the display of the string.
Example:
>>> format('hello','<10')
'hello '
>>> format('hello','>10')
' hello'
>>> format('hello','^10')
' hello '
>>> format("hello",">10")
' hello'
>>> format("hello","^10")
' hello '
Data Type
Number
String
List
Tuple
Dictionary
ii) Rest of the character name can be underscore(‘_’), letter (upper or lower
case) and digits( 0 to 9).
Prog. 1:
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:
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
Example
>>> a=b=c=d=0
>>> print("a=",a,"b=",b,"c=",c,"d=",d)
a= 0 b= 0 c= 0 d= 0
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
In python we can specify more than one statements in a single line using
semicolon (;).
Example
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
>>> 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
Operators
Arithmetic Operators
Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
// Floor Division
** Exponent
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
>>> 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'>
Example 2
t=("Raja Roy","CSE",10,80.75)
print(t)
Output:
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
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
Example 5
t1=(1,2,3,4,5)
t2=(10,20,30,40,50)
t3=t1+t2
print("t3:",t3)
Output:
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:
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:
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
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
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:
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:
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
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.
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'))
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:
Example 17
t=(20,50,30,10,40)
print(sorted(t))
print(t)
Output:
String
Built-in string functions in Python
capitalize()
str="hello"
print(str.capitalize())
Output:
Hello
Output:
**hello***
count()
str="hello”
msg="hello world hello India"
print(msg.count(str,0,len(msg)))
Output:
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
str="hello"
msg="hello world hello India"
print(msg.startswith(str,0,len(msg)))
print(msg.startswith("dia",0,len(msg)))
Output:
True
False
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
print(s.index(“abcd",0,len(s)))
print(s.rindex(“abcd",0,len(s)))
Output:
0
13
isalnum()
msg="MCA2021"
print(msg.isalnum())
msg="MCA 2021"
print(msg.isalnum())
Output:
True
False
msg="MCA2021"
print(msg.isalpha())
Output:
True
False
isdigit()
msg="2021"
print(msg.isdigit())
msg="MCA2021"
print(msg.isdigit())
Output:
True
False
msg="MCA"
print(msg.islower())
msg="mca"
print(msg.islower())
Output:
False
True
isupper()
msg="MCA"
print(msg.isupper())
msg="mca"
print(msg.isupper())
Output:
True
False
msg="MCA 2021"
print(msg.isspace())
msg=" "
print(msg.isspace())
Output:
False
True
str="Hello"
print(str.ljust(10,'*'))
print(str.rjust(10,'*'))
Output:
Hello*****
*****Hello
str="Hello"
print(str.zfill(10))
Output:
00000Hello
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
str=" Hello"
print(str.lstrip())
print(str)
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="hello"
print(max(str))
print(min(str))
Output:
y
o
e
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
Output:
He Is A Good Boy
He is a good boy
swapcase()
str="AaBbCcDd"
print(str.swapcase())
print(str)
Output:
aAbBcCdD
AaBbCcDd
Example 1
s={10,3.14,"abcd"}
print(s)
Output:
{3.14, 10, 'abcd'}
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'}
Example 3
A={10,20,30,40,50}
B={30,50,70,90}
Output:
Example 4
s={10,20,30,{11,22}}
print(s)
Output:
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
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:
Example 7
s={11,22,33,44}
for i in s:
print(i)
Output:
33
11
44
22
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 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();
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]);
}
selection_sort(p,n);
getch();
}
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
When we import a module, we can use any variable or function defined in that
module.
Example 1
n=int(input("Enter No:"))
r=sqrt(n)
print("Result=",r)
Output:
Enter No:81
Result= 9.0
n=int(input("Enter No:"))
r=square_root(n)
print("Result=",r)
Output:
Enter No:90
Result= 9.486832980505138
Example 3
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)
Enter No:70
Result= 8.366600265340756
Enter No:2
Enter exponent:5
Result= 32.0
PI= 3.141592653589793
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
Example 5
import sys
a=int(sys.argv[1])
b=int(sys.argv[2])
r=a+b
print("Result=",r)
Output:
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
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:
Example 7
MyModule1.py
def display():
print("Hello")
print("In Called function:")
print("Name of Module is:", __name__)
Example7.py
print("Welcome")
print("Name of the Calling Module is:",__name__)
display()
Welcome
Name of the Calling Module is: __main__
Hello
In Called function:
Name of Module is: MyModule1
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__)
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
Example 9
print("Welcome")
print("Name of the Calling Module is:",__name__)
MyModule1.display()
MyModule2.display()
Output:
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
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
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:
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:
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