0% found this document useful (0 votes)
2 views41 pages

Python Practical Practice Questions

The document contains a comprehensive list of Python programming experiments covering basic concepts, loops, functions, lists, tuples, dictionaries, and libraries like Numpy and Pandas. Each experiment includes multiple programs with code examples and expected outputs to illustrate various programming concepts. The content is structured to facilitate learning and understanding of Python programming through practical exercises.

Uploaded by

Sanchita Yadav
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)
2 views41 pages

Python Practical Practice Questions

The document contains a comprehensive list of Python programming experiments covering basic concepts, loops, functions, lists, tuples, dictionaries, and libraries like Numpy and Pandas. Each experiment includes multiple programs with code examples and expected outputs to illustrate various programming concepts. The content is structured to facilitate learning and understanding of Python programming through practical exercises.

Uploaded by

Sanchita Yadav
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/ 41

INDEX

S. Experiment
No.
1 Programs on the Basic Concepts of Python

2 Programs illustrating the Concept of Loops

3 Programs to print the various Patterns

4 Programs demonstrating the Concept of Functions

5 Programs illustrating the Concept of Lists

6 Programs illustrating the Concept of Tuples

7 Programs illustrating the Concept of Dictionary

8 Programs to print the various Sequences

9 Programs illustrating the Concept of Numpy

10 Programs illustrating the Concept of Pandas

11 Programs illustrating the Concept of GUI (Tkinter)


Experiment 1 : Programs on the Basic Concepts of
Python

Program 1 -There are 5280 feet in a mile. Write a Python


statement that calculates and prints the number of feet in
13
miles.
In [19]: feet=13*5280
print("Total feet is "+str(feet))

Total feet is 68640

Program 2 - Write a Python statement that calculates and


prints the number of seconds in 7 hours, 21 minutes and
37
seconds.
# 1 hour=3600sec and 1 minute=60sec
In [20]: print("total no of seconds in 7hrs 21mins 37sec
are"+str((7*60*60)+(21*6
total no of seconds in 7hrs 21mins 37sec are26497

Program 3 - The perimeter of a rectangle is 2w+2h, where


w and h are the lengths of its sides. Write a Python
statement that calculates and prints the length in inches of
the perimeter of a rectangle with sides of length 4 and 7
inches.
In [21]:
w=4 h=7 perimeter=2*w+2*h print("the perimeter
of rectangle is "+str(perimeter))

the perimeter of rectangle is 22

Program 4 - The circumference of a circle is 2πr where r is


the radius of the circle. Write a Python statement that
calculates and prints the circumference in inches of a circle
whose radius is 8 inches. Assume that the constant
π=3.14.
In [22]: r=8
circumference=2*3.14*r print("the circumference of
circle is "+str(circumference))

the circumference of circle is 50.24


Program 5 - Given p dollars, the future value of this money
when compounded yearly at a rate of r percent interest for
y years is p(1+0.01r)y. Write a Python statement that
calculates and prints the value of 1000 dollars
compounded at 7 percent interest for 10 years.
In [23]: p=1000
r=7
y=1
value=p*(1.0+0.01*r)*y
print("the value is
"+str(value))

the value is 1070.0

Program 6 -Write a Python expression that combines the


string "Joe Warren is 52 years old." from the string "Joe
Warren" and the number 52 and then prints the result
(Hint:
Use the function str to convert the number into a string.)
In [24]: a='joe warren' b=52 print(a +' is
'+ str(b)+' year old')

joe warren is 52 year old

Program 7 -Write a single Python statement that combines


the three strings "My name is", "Joe" and "Warren" (plus a
couple of other small strings) into one larger string "My
name is Joe Warren." and prints the result.
In [25]: a='My name is' b='
Joe' c='
Warren' d=' '
e='.'
print(a+b+c+d+
e)

My name is Joe Warren .

Program 8 - The distance between two points (x0,y0) and


(x1,y1) is (x0−x1)2+(y0−y1)2. Write a Python statement
that calculates and prints the distance between the points
(2,2) and (5,6).
In [28]: x0,y0,x1,y1=input().split() distance=((int(x0)-
int(x1))**2 + (int(y0)-int(y1))**2)**0.5
print('distance is '+str(distance))
2 6 5 2
distance is
5.0

Program 9 - Write a program to check whether a year is


leap year or not.
year=int(input())
In [34]:
if (year)%4==0:
print('year is an leap year')
elif(year%400==0):
print('year is an leap year')
elif(year%100==0):
print('year is not an leap year')
else:
print('year is not an leap year')
2400 year is an
leap year

Program 10 - Write a program to output the grade of


student based on the percentage entered by the student.
In [36]: percentage=input()

if int(percentage)>=90:
print('your grade is A') elif
int(percentage)>=80 and
int(percentage)<=90:
print('your grade is B') elif
int(percentage)>=70 and
int(percentage)<=80:
print('your grade is C') elif
int(percentage)>=60 and
int(percentage)<=70:
print('your grade is D') elif
int(percentage)>=50 and
int(percentage)<=60:
print('your grade is E') elif
int(percentage)>=40 and
int(percentage)<=50:
print('your grade is F')
else:
print('you are fail')
40 your grade
is F

Program 11 - Write a Python program to check whether an


alphabet is a vowel or consonant.
In [38]: a=input("Enter the Alphabet ") if (a=='a'or a=='e'or a=='i' or
a=='o'or a=='u' or a=='A' or a=='E' or a= print("Alphabet
entered is a vowel") else: print("Alphabet entered is not a
vowel")
Enter the Alphabet a
Alphabet entered is a vowel

Program 12 - Write a python function that receive one


number and print it is even number or odd number.
a=input("enter the
In [39]:
no.") if int(a)%2==0:
print('no is an even no.')
else:
print('no is an odd no.')
enter the no.23
no is an odd no.

Program 13 - Write a python program that receive 5


numbers by user and print sum and average of these
numbers.
In [40]: a,b,c,d,e=input("enter the numbers ").split()
sum=int(a)+int(b)+int(c)+int(d)+int(e)
average=sum//5 print('sum of five number
is '+str(sum)) print('average of five
number is '+str(average))

enter the numbers 2 2 2 2 2


sum of five number is 10
average of five number is 2

Program 14 - Write code that prints Hello if 1 is stored in


spam, prints Howdy if 2 is stored in spam, and prints
Greetings! if anything else is stored in spam.
In [41]: spam=input("enter the value of spam ")
if
int(spam)==1:
print('hello')
elif int(spam)==2:
print('Howdy') else:
print('Greetings')

enter the value of spam 2


Howdy
2 : Programs illustrating the Concept of Loops

Program 1 - First 5 natural no.s .


In [56]: n=1 while
n<6:
print(n)
n=n+1

1 2 3
4
5

Program 2 - First 5 natural no. in same row.


n=1
In [47]:
while
n<6:
print(n,end=' ')
n=n+1
1
2 3 4 5

Program 3 - Write a python function that accepts one no.


and calculates its factorial.
In [57]:
i=1
fac=1
a=input('Enter the number') a=int(a)
while i<=a: fac=fac*i i=i+1
print("factorial of " +str(a), "is
"+str(fac))

Enter the number4


factorial of 4 is 24

Program 4.1 - Write a program that prints the number 1 to


10
using a for loop.
In [58]: for i in range(1,11,1):
print(i)

1
2
3 4
5
6
7
8
9
10

Program 4.2 - Write a program that prints the number 1 to


10 using while loop.
In [15]: i=1 while
i<11:
print(i)
i=i+1

1
2 3 4
5
6
7
8
9
10

Program 5.1 - Count number of digits in a Number.


In [1]:
Number=int(input('Enter the
number')) c=0 while(Number!=0):
c=c+1
Number=Number//10 print('The Total
Number of digits is : '+str(c))
Enter the number231
The Total Number of digits is : 3

Program 5.2 - Count number of digits in a Number. Print


the digits of Number.
In [4]: Number=int(input('Enter the number')) c=0
while(Number!=0): c=c+1 r=Number%10
print(r,end=' ') Number=Number//10
print('\nThe Total Number of digits is : '+str(c))

Enter the number2314


4 1 3 2
The Total Number of digits is : 4

Program 6 - Print maximum of five numbers using a function.


In [32]: a,b,c,d,e=input().split()
a,b,c,d,e=int(a),int(b),int(c),int(d),int(e)
print(max(a,b,c,d,e))

21 3 2 4 123
123

Program 7 - Print maximum of five numbers without using


a function.
In [1]: a,b,c,d,e=input().split()
a,b,c,d,e=int(a),int(b),int(c),int(d),int(e)
if a >= b and a >= c and a >= d and a >= e:
print("The maximum number is a = ", a) elif b >= a and
b >= c and b >= d and b >= e: print("The maximum
number is b = ", b) elif c >= a and c >= b and c >= d
and c >= e: print("The maximum number is c =", c)
elif d >= a and d >= b and d >= c and d >= e:
print("The maximum number is d = ", d) else:
print("The maximum number is e = ", e)

12 34 21 32 1
The maximum number is b = 34

Program 8 - Print minimum of the five numbers, using a


function.
In [2]: a, b, c, d, e = input().split() a, b, c, d, e =
int(a), int(b), int(c), int(d), int(e)
print(min(a, b, c, d, e))

12 32 1 -2 3
-2

Program 9 - Print minimum of the five numbers, without


using a function.
a, b, c, d, e = input().split() a, b, c, d, e
In [4]:
= int(a), int(b), int(c), int(d), int(e) if a
<= b and a <= c and a <= d and a <= e:
print("The minimum number is a = ", a) elif b
<= a and b <= c and b <= d and b <= e:
print("The minimum number is b = ", b) elif c
<= a and c <= b and c <= d and c <= e:
print("The minimum number is c =", c)
elif d <= a and d <= b and d <= c and d
<= e: print("The minimum number is d
= ", d) else:
print("The minimum number is e = ", e)
12 45 23 41 21
The minimum number is a = 12

Program 10 -Write a python program to find those numbers


which are divisible by 7 and multiple of 5 between 1500
and 2700(both included)
In [2]: for i in range(1500,2701):
if(i%5==0 and i%7==0):
print(i)

1505
1540
1575
1610
1645
1680
1715
1750
1785
1820
1855
1890
1925
1960
1995
2030
2065
2100
2135
2170
2205
2240
2275
2310
2345
2380
2415
2450
2485
2520
2555
2590
2625
2660
2695

Program 11 - write a python program to convert celsius to


fahrenheit and fahrenheit to celsius.
In [3]: # c=60 f=45 fahrenheit=(c*1.8)+32
celsius=(f-32)/1.8 print( c,
"is",fahrenheit ,"in fahrenheit")
print( f, "is",celsius ,"in celsius")

3 is 37.4 in fahrenheit
45 is 7.222222222222222 in celsius

Program 12 - Write a python program that accept a word


from the user and reverse it
In [4]: a=input('Enter a word here : ') a b=a [::-1]
print('Revesed word is : '+str(b))

Enter a word here : nancy


Revesed word is : ycnan

Program 13 - write a python program that print all the


number from 0 to 6 except 3 and 6 , using continue
statement
In [5]: for i in range(0,7):
if(i==3 or i==6):
continue
print(i)

0
1
2
4
5

Program 14 - Print the fibonacci series between 0 to 50


In [6]: s=0 n=1 c=0
while(s<40):
print(n)
a=s+n
s=n
n=a
c+=1

1
1
2
3
5
8
13
21
34
55

Program 15 -write a python program to find number btw


100 to 400 where each digit of a number is an even
number . the number obtained should be printed in a
comma-seperated sequence
for i in
In [7]:
range(100,401):
if(i%2==0):
b=i//10
c=b%10
if(c%2==0):
a=i//100
if(a%2==0):
print(i,",",end="
")
200 , 202 , 204 , 206 , 208 , 220 , 222 , 224 , 226 , 228 , 240 ,
242 , 2 44 , 246 , 248 , 260 , 262 , 264 , 266 , 268 , 280 , 282
, 284 , 286 , 28 8 , 400 ,

Program 16 -write a python program to calculates a dogs


age in human year NOTE:for first two year dog age is 10.5
human year and is 4 times for so on years
In [8]: year=int(input()) s=0
if(year>=2):
d=year-2
s=s+(4*d)+(2.0*10.5)
print(s)
elif(year==2):
c=2*10.5
print(c)
else:
a=10.5
print(a)

4
29.0

Program 17 - Write a python program to check whether a


triangle is equilateral,isosceles or scalene
In [9]: x=input('Enter the First side :')
y=input('Enter the Second side:')
z=input('Enter the Third side :')
if(x==y and x==z):
print('It is an equilateral triangle')
elif(x==y and x!=z):
print(' It is an isosceles triangle')
elif(x!=y and x==z):
print('It is an isosceles triangle')
elif(x!=y and y==z):
print('It is an isosceles triangle')
else: print('It is an
scalene triangle')

Enter the First side :1


Enter the Second side:2
Enter the Third side :3
It is an scalene triangle

Program 18 - Accept the input from user and calculate the


sum of all the number between 1 and given number
a=int(input('Enter the
In [14]:
number')) s=0 for i in
range(1,a+1):
if(i<=a):
s=s+i print('Sum is
'+str(s))
Enter the number10
Sum is 55

Experiment 3 : Programs to print the various


Patterns
Question 1 - Print the following pattern

11 Error! Bookmark not defined.


1 2 Error! Bookmark not defined.
1 2 3 7
1 2 3 4 7

12

123

1234

12345
In [11]: for i in range (1,6):
for j in range (1, i+1):
print(j, end=' ')
print()

1
Question 2: Print the Following patterns

45

345

2345

12345
In [12]: for i in range(5, 0, -1):
for j in range(i, 6):
print(j, end=' ' )
print()

5
4 5
3 4 5
2 3 4 5
1 2 3 4 5

Question 3: Print the Following patterns.

5
54

543

5432

54321
In [26]: for i in range (5, 0, -1):
for j in range (5, i-1, -1):
print(j, end=' ') print()

5
5 4
5 4 3
5 4 3 2
5 4 3 2 1

Question 4: Print the following pattern.

22

333

4444

55555
for i in range(1, 6):
In [24]:
for j in range(i):
print(i, end=' ')
print()
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5

Question 5: Print the following pattern using a for loop ----1

---12

--123

-1234

12345
In [29]: for i in range(1,6):
print(' '* (5-i), end= ' ')
for j in range(1, i+1):
print(j, end ='')
print()

1
12
123
1234
12345

Question 6: Print the following pattern using a while loop

----1

---121

---12321

-1234321

123454321
In [27]:
i = 1 while i<6:
print(" "* (5-i), end = '')
j = 1 while j<(i+1):
print(j, end =
'') j += 1
k = 1 while k < i:
print(i-k, end = '')
k += 1 print()
i += 1

1
121
12321
1234321
123454321

In [30]: for i in range(1,6):


print(' '* (5-i), end = '')
for j in range(1, i+1):
print(j, end ='') for
k in range(1, i):
print(i-k, end ='')
print()

1
121
12321
1234321
123454321

Question 7: Print the following code using While Loop

123454321

-1234321

--12321

---121

----1
In [31]: i = 6
while
(i>0):
print(" "* (6-i),
end='') j = 1
while j<i:
print(j, end = "")
j += 1
k = 1
while k<(i-1):
print(i-k-1, end =
"") k += 1
print() i -= 1
123454321
1234321
12321
121
1

In [32]: for i in range(6, 0, -1):


print(' '* (6-i), end='')
for j in range(1,i):
print(j, end='') for
k in range(1,(i-1)):
print(i-k-1, end='')
print()

123454321
1234321
12321
121
1

Question 8: Write a python program to print alphabet


pattern A
AB

ABC

ABCD

ABCDE
from string import *
In [33]:
for i in range(0, 5):
for j in range(0, i+1):
print(ascii_uppercase[j], end= " ")
print()
A
A B
A B C
A B C D
A B C D E

In [ ]:

4. Programs demonstrating the Concept of


Functions
Program 1: Function to find the max of three numbers
def max_num(a, b, c):
if (a >= b):
if (a >= c):
print("a =", a, "is the greatest")
else:
print("c =", c, "is the
greatest") elif (b > a):
if (b >= c):
print("b =", b, "is the greatest")
else:
print("c =", c, "is the greatest")
else:
print("Something went
wrong!") max_num(4,56,12) print()
max_num(0,12,2) print() max_num(-
2,-5,-12)
b = 56 is the greatest

b = 12 is the greatest

a = -2 is the greatest

Program 2: Function to find the sum of all the numbers in a list


In [33]:

def sum(m):
if (type(m) == list):
sum = 0 for i in m: sum
+= i print("The sum of the elements in this
list is:", sum) else:
print("Wrong Input! Enter a
list.") a = list(range(10)) b = 5
sum(b) print() sum(a)

Wrong Input! Enter a list.

The sum of the elements in this list is: 45

Program 3: Function to find the product of all the numbers in a


list
def list_prod(x):
if (type(x) == list):
product = 1
for i in x:
product *= i
print("The product of the elements in the list
is:", product) else:
print("Wrong Input! Enter a
list.") a1 = [8,2,4,5] b1 = 60
list_prod(a1) print() list_prod(b1)
In [34]:

The product of the elements in the list is: 320


Wrong Input! Enter a list.

Program 4: Function to reverse a string


In [41]:
def rev(a):
if (type(a) == str):
a1 = "" for i in
range(len(a)-1, -1, -1):
a1 += a[i]
a = a1
print("On reversing the string we get:", a)
else:
print("Wrong Input! Enter a String.")
n= "Nancy
RANI" b =
1441
rev(n)
print()
rev(b)
On reversing the string we get: INAR ycnaN

Wrong Input! Enter a String.

Program 5: Function to find the factorial of a non-negative


number.
def fact(m):
if (type(m) == int):
if (m > 0):
factorial = 1 # factorial
for i in range(1, m + 1):
factorial *= i
print("The factorial of", m, "is:", factorial)
elif (m
== 0):
print("0! = 1")
else:
print(m, "is not a Positive Integer!\nEnter a
Positive Intege else:
print("Argument Type Not supported!\nEnter a Positive
Integer.") a = 4 b = 0 c = -40 d = "N" fact(a) print()
In [47]: fact(b) print() fact(c) print() fact(d)

The factorial of 4 is: 24

0! = 1

-40 is not a Positive Integer!


Enter a Positive Integer
Argument Type Not supported!
Enter a Positive Integer.

Program 6: Function to check whether a number is in a


given range.
def test_range(m): if
In [55]:
(type(m) == int): if
m in range(-15, 15):
print("Number %s is in the range"%str(m))
else:
print("Number %s is not in the range"%str(m))
else: print("Argument Type not supported!\nEnter
an Integer.")
a
= "Hello"
test_range(5)
print()
test_range(-6)
print()
test_range(a)
print()
test_range(19)
Number 5 is in the range

Number -6 is in the range


Argument Type not supported!
Enter an Integer.

Number 19 is not in the range

Program 7: Function that takes a number as a parameter


and check whether a number is Prime or not.
In [57]: def test_prime(m):
if (type(m) == int):
for i in range(2,m):
if (m%i == 0):
print("Number %s is not a Prime
Number."%str(m)) break
else:
print("Number %s is a Prime
Number."%str(m)) break else:
print("Argument Type not supported!\nEnter an Integer.")
test_prime(10)
print()
test_prime(18)

Number 10 is not a Prime Number.

Number 18 is not a Prime Number.

Program 8: Function to check whether a number is


Palindrome or not.
In [58]: def pdm(a): p = 0 m = a

while (a != 0):
rem = a%10 p =
(p * 10) + rem
a = a//10
if (p
== m):
print("Number %s is a
Palindrome."%str(p)) else:
print("Number %s is not a
Palindrome."%str(p
)) pdm(12321) print() pdm(123) print()
pdm(0)

Number 12321 is a Palindrome.

Number 321 is not a Palindrome.

Number 0 is a Palindrome.

Program 9: Function to check whether a number is Perfect


or not.
Perfect Number: A Positive integer, that is equal to the sum
of its proper positive divisors,i.e. the sum of its positive
divisors excluding the number itself. Or we can say, A
perfect Number is half the sum of all of its positive divisors
(including itself).

eg. Perfect Number 6, 1+2+3 = 6, (1+2+3+6)/2 = 6;

eg. Perfect Number 28, (1+2+4+7+14) = 28,

(1+2+4+7+14+28)/2 = 28
In [61]: def test_perfect(a):
sum = 0 for i
in range(1, a):
if (a%i == 0):
sum += i if (sum ==
a):
print("Number %s is a Perfect Number."%str(a))
else:
print("Number %s is not a Perfect Number."%str(a))
test_perfect(6)
print()
test_perfect(496)
print()
test_perfect(8128)
print()
test_perfect(7)

Number 6 is a Perfect Number.

Number 496 is a Perfect Number.


Number 8128 is a Perfect Number.

Number 7 is not a Perfect Number.

In [ ]:
Experiment 5 : Programs demonstrating the
Concept of Lists

Program 1: Create list, change one element, display length


of list.
In [62]: a = [13,12,42,16,18] a[0] = 12 print("a
=", a) print()
print("length of list a is :", len(a))

a = [12, 12, 42, 16, 18]

length of list a is : 5

Program 2: Create a list, append two elements in it.


In [63]: a = [5, 10, 15]
a.append(20)
a.append(25) print("a
=", a)

a = [5, 10, 15, 20, 25]

Program 3: Create a list and sort it.


In [64]: a = [2, 1, 6]
a.sort()
print(a)

[1, 2, 6]

Program 4: Create a list of numbers and print the sum of all


elements.
a1 = [1, 3, 5,
In [65]:
7] sum = 0
for i in a1:
sum += i
print("The sum of the elements
is:", sum)
The sum of the elements is: 16

Program 5: Compare the elements of two lists


a1 = ['hi', "apple",
3] a2 = ['hie', 4,
3] if (len(a1) ==
len(a2)):
for i in range(len(a2)):
if (a1[i] is a2[i]):
print("Elements with index value", i, "are same in
In [67]: both the
else:
print("Elements with index
value", i, "are not same in both t else:
print("Lengths of the lists are not
equal.")

Elements with index value 0 are not same in both the lists
Elements with index value 1 are not same in both the lists
Elements with index value 2 are same in both the lists

Program 6: Find the maximum and minimum from


elements of
list
a2 = [5, 3, 2, 5, 6, 1,
In [68]:
0, 5] element = a2[0]
element1 = element for i
in a2:
if (i >= element):
element = i
for i
in a2:
if (i <= element1):
element1 = i

print("The maximum value in this list is: %s\n"%str(element))


print("The minimum value in this list is: %s"%str(element1))
The maximum value in this list is: 6

The minimum value in this list is: 0

Program 7: Count occurence of an element in the list.


In [70]: a3 = [1, 2, 2, 4, 6, 7, 2, 5] x =
a3.count(2)
print("2 occurs %s times"%str(x))

2 occurs 3 times

Program 8: Reverse a List


In [71]: def rev_list(a):
x = [] for i in
range(len(a)-1, -1, -1):
x.append(a[i])
return x
m = ["Python", "Java", "C++"] print("The
reverse of given list is:", rev_list(m))

The reverse of given list is: ['C++', 'Java', 'Python']

Program 9: Write a loop that traverses the previous list and


prints the length of each element.
Ques. What happens when you send an integer to len()?
Ans.
We will get an error, as object of type "int" has no len()
In [75]: def len_element(a):
for i in a:
print("length of %s is:"%str(i),
len(i), "\n") x = ["Codeblocks", "Jupyter"]
n = ["JS", 1, "Android"]
len_element(x)
len_element(n)

length of Codeblocks is: 10


length of Jupyter is: 7
length of JS is: 2
----------------------------------------------------------------
----------
TypeError Traceback (most recent
call las t)
<ipython-input-75-57b2145c2d44> in <module>
5 n = ["JS", 1, "Android"]
6 len_element(x) ----> 7 len_element(n)
8

<ipython-input-75-57b2145c2d44> in len_element(a)
1 def len_element(a):
2 for i in a:
----> 3 print("length of %s is:"%str(i), len(i), "\n")
4 x = ["Codeblocks", "Jupyter"]
5 n = ["JS", 1, "Android"]

TypeError: object of type 'int' has no len()


Program 10: Describe the relationship b/w
split.join(split.string(song)) and song. (Where song is a
string) Are they the same for all strings?

When would they be different?

ANSWER: The relationship between

string.join(string.split(song)) and songs is that: the former


first takes every word in the variable song and splits it in a
list with each word as a separate element.

Next, the string.join function takes every letter in each word


and separates it with a single space character but takes it
out of the list. Song essentially uses a string and the
string.join function uses the string in a list.

Yes, they are the same for all strings. The function doesn't
work for integers and float values.
import string a = "africa"

string.join(string.split(a)) ==

a
In [5]: song = "Africa"
song.join(song.split()) == song
Out[5]:
True

Program 11.1 : Program that reads in numbers seperated


by a space in one line and display distinct numbers.

For example:

Input: 1 1 1 1 1 2 2 2

Output: 1 2
In [79]: a = input("Enter numbers here, seperated by a space:
").split() lst_new = [] for i in a: if i not in
lst_new: lst_new.append(i)
print("The distinct numbers from the input are:", "
".join([str(i)])) print(lst_new)

Enter numbers here, seperated by a space: 1 2 3 4


The distinct numbers from the input are: 4
['1', '2', '3', '4']

Program 11.2 : Program that reads in numbers seperated


by a space in one line and display distinct numbers.
In [81]: a = input("Enter numbers here, seperated by a space:
").split() a = list(set(a)) str1 = "" for i in a:
str1 += i
print("The distinct numbers from the input are:", "
".join(str1))

Enter numbers here, seperated by a space: 1 2 5 8


The distinct numbers from the input are: 1 8 2 5

Program 12: Write a User defined function to find the index


of the smallest element in a list of integers.

If number of such element is greater than 1, then return the


smallest index value.
In [83]: def indexOfSmallestElement(lst):
if (type(lst) ==
list): element =
lst[1] for i in
lst:
if i < element:
element = i return
lst.index(element) else:
print("Wrong Input! Enter a
list.") a = [2, 1, 1, -1, 3, -1] b =
1
print("Index of the smallest element in the List is:",
indexOfSmallestEle indexOfSmallestElement(b)
Index of the smallest element in the List is: 3
Wrong Input! Enter a list.
Program 13: User defined function that reads some
integers b/w

1 to 20 and counts the occurences of each.

SAMPLE:

Input: 2 5 2 5 8 8 10 8 2 4 4 5 2

Output: 2 occurs 4 times

5 occurs 3 times

8 occurs 3 times 3

10 occurs 1 times

4 occurs 2 times
In [85]:
def counter(): a = input("Enter numbers
between 1 to 20: ").split() lst = [] for
i in a: if i not in lst:
lst.append(i)
for i in lst:
count = 0 for j
in a: if (j
== i):
count += 1
print(i, "occurs %s times"%str(count))
counter()

Enter numbers between 1 to 20: 1 2 12 15 13


1 occurs 1 times
2 occurs 1 times
12 occurs 1 times
15 occurs 1 times
13 occurs 1 times

Program 14: Compute the standard deviation and mean of


numbers in a list
In [87]:from math import
sqrt a =
input().split()
lst = [] for i in
a:
lst.append(int(i))
s,std = 0, 0 for m
in lst:
s+= m
Mean = sum/(len(lst))
for n in lst:
std += (n - Mean)**2
Std_dev = sqrt(std/(len(lst)))
print("The Mean of elements of the list is:", Mean)
print("The Standard Deviation of the elements of the list is:", Std_dev)
2 3 6 5
The Mean of elements of the list is: 4.0
The Standard Deviation of the elements of the list is:
1.5811388300841898

In [ ]:

Experiment 6 : Programs illustrating the


Concept of Tuples

1 - Create a tuple and try to changing the value of any


oneelement,also display the length of list
In [17]: a=(1,2,3,4,5)

In [ ]: a=(2,)+a[1:] a
In [ ]: print(len(a))

2 - Create a tuple having single element and append two


tuple
In [ ]: b=('A',)
c=('D',)

In [ ]: b+c

3 - Create a tuple and sort it


In [8]: t=(2,0,1,4)
r=sorted(t)
print(r)

[0, 1, 2, 4]

In [11]: r=tuple(r) print(r)

(0, 1, 2, 4)

4 - Create a tuple and print the sum of all the element


In [ ]: t1=(12,3,5,2) s=0 for i
in range(0,len(t1)):
s=s+t1[i]
print(s)

5 - Programs to compare the element of tuple


In [ ]: t3=(1,2,3,4,5,6)
t4=(1,2,3,4,5,6) for i
in range(0,len(t3)):
s=t3[i] for j in
range(0,len(t4)):
r=t4[j]
if(s==r):
print('same')
else:
print('not same')
6 -Program to find maximum and minimum of tuple
In [ ]: t5=(-2,-3,4,21) max=t5[0] for i in
range(0,len(t5)): if(max<t5[i]):
max=t5[i] print('max number is '+str(max))
min=t5[0] for i in range(0,len(t5)):
if(min>t5[i]): min=t5[i]
print('min number is '+str(min))
7 - Count the occurrence of element in tuple in a
specificrange
In [ ]: t6=(1,2,1,1,3,4)
r=t6[1:].count(1)
print(r)

8 - Reverse a tuple
In [ ]: t7=(1,2,3,4,'nancy')
l7=list(t7)
l7.reverse()
b=tuple(l7)
print(b)

9 - Write a loop that traverses the previous tuple and prints


thelength of each element
In [14]:
t7=('Daddy','mummy','anshul','nancy')
l=list(t7) print(l)

['Daddy', 'mummy', 'anshul', 'nancy']

In [ ]: for i in range(0,len(t7)): p=len(t7[i])


print("length of",t7[i],"is",p)

In [ ]:

7 : Programs illustrating the Concept of


Dictionary

Program 1 - Write a python script to add a key to a


dictionary
In [13]: d1={0:10,1:20}
d2={2:30}
d1.update(d2)
d1

Out[13]: {0: 10, 1: 20, 2: 30}


Program 2.1 - Write a python script to concatenate
dictionaries to create a new one.
In [14]: dic1={1:10,2:20}
dic2={3:30,4:40}
dic3={5:50,6:60}
dic1.update(dic2)
dic1.update(dic3)
dic1

Out[14]: {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}

Program 3 - Write a python script to check if a given key


already exists in a dictionary
In [15]: d={1: 10, 2: 20, 3: 30, 4: 40, 5: 50,
6: 60} def present(x): if x in
d.keys():
print('key is present')
else: print('key is not
present')
present(5)
present(7)

key is present
key is not
present

Program 4 - Write a python script to print dictionary where


the keys are numbers between 1 to 15 (both included) and
the values are square of keys.
In [16]: d={} for x in
range(1,16):
d[x]=x*x
print(d)

{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10:


100, 11:
121, 12: 144, 13: 169, 14: 196, 15: 225}

Program 5 - Write a python script to merge two python


dictionaries
d1 = {'a': 100, 'b':
In [17]:
200} d2 = {'x': 300,
'y': 200} d=d1.copy()
d.update(d2)
print(d)
{'a': 100, 'b': 200, 'x': 300, 'y': 200}
Program 5.2 - Write a python script to merge two python
dictionaries.

using **(kwargs) in python


In [18]: a={1:'one',2:'two'} b={3:'three',4:'four'}
c={**a,**b}
print('final merged dictionary is:',c)

final merged dictionary is: {1: 'one', 2: 'two', 3: 'three', 4:


'four'}

Experiment 8 : Programs to print the


various Sequences

Program 1 - Write the python program the print the given


series : 7,10,8,11,9,12............... print the given series from
7 to
50
In [18]: for i in range(7,48): print(i,end=" , ")
print(i+3,end=" , ")
7 , 10 , 8 , 11 , 9 , 12 , 10 , 13 , 11 , 14 , 12 , 15 , 13 , 16
, 14 , 1
7 , 15 , 18 , 16 , 19 , 17 , 20 , 18 , 21 , 19 , 22 , 20 , 23 ,
21 , 24 ,
22 , 25 , 23 , 26 , 24 , 27 , 25 , 28 , 26 , 29 , 27 , 30 , 28 ,
31 , 29 , 32 , 30 , 33 , 31 , 34 , 32 , 35 , 33 , 36 , 34 , 37 ,
35 , 38 , 36 , 3
9 , 37 , 40 , 38 , 41 , 39 , 42 , 40 , 43 , 41 , 44 , 42 , 45 ,
43 , 46 ,
44 , 47 , 45 , 48 , 46 , 49 , 47 , 50 ,

Program 2 - Write the python program the print the given


series : 22,21,23,22,24,23............... print the given series
from 20 to 80
In [19]: for i in range(21,80): print(i+1,end=" ,
") print(i,end=" , ")

22 , 21 , 23 , 22 , 24 , 23 , 25 , 24 , 26 , 25 , 27 , 26 , 28 ,
27 , 29
, 28 , 30 , 29 , 31 , 30 , 32 , 31 , 33 , 32 , 34 , 33 , 35 , 34
, 36 , 3
5 , 37 , 36 , 38 , 37 , 39 , 38 , 40 , 39 , 41 , 40 , 42 , 41 ,
43 , 42 ,
44 , 43 , 45 , 44 , 46 , 45 , 47 , 46 , 48 , 47 , 49 , 48 , 50 ,
49 , 51 , 50 , 52 , 51 , 53 , 52 , 54 , 53 , 55 , 54 , 56 , 55 ,
57 , 56 , 58 , 5
7 , 59 , 58 , 60 , 59 , 61 , 60 , 62 , 61 , 63 , 62 , 64 , 63 ,
65 , 64 ,
66 , 65 , 67 , 66 , 68 , 67 , 69 , 68 , 70 , 69 , 71 , 70 , 72 ,
71 , 73 , 72 , 74 , 73 , 75 , 74 , 76 , 75 , 77 , 76 , 78 , 77 ,
79 , 78 , 80 , 7 9 ,

Program 3 - Write the python program the print the given


series : 53,53,40,40,27,27............... print the given series
from 53 to 100
In [20]: n=53 for i in
range(53,100):
print(str(n)+",",n,e
nd=", ") n=n-13

53, 53, 40, 40, 27, 27, 14, 14, 1, 1, -12, -12, -25, -25, -38, -
38, -51, -51, -64, -64, -77, -77, -90, -90, -103, -103, -116, -
116, -129, -129, -1
42, -142, -155, -155, -168, -168, -181, -181, -194, -194, -207, -
207, -22
0, -220, -233, -233, -246, -246, -259, -259, -272, -272, -285, -
285, -29
8, -298, -311, -311, -324, -324, -337, -337, -350, -350, -363, -
363, -37
6, -376, -389, -389, -402, -402, -415, -415, -428, -428, -441, -
441, -45
4, -454, -467, -467, -480, -480, -493, -493, -506, -506, -519, -
519, -53 2, -532, -545, -545,

Program 4 - Write the python program the print the given


series : 14,28,20,40,32,64............... print the given series
from 14 to 100
In [21]:
n=1 j=14 for i
in range(4):
print(j,",",j*2,end='
, ') j=j+6*n n=n+1

14 , 28 , 20 , 40 , 32 , 64 , 50 , 100 ,

Program 5 - Write the python program the print the given


series : 2,6,12,20,30,42............... print the given series
from 2 to 100
In [22]:
n=100 i=2
j=4
while(i<=n):
print(i,end="
") i=i+j
j=j+2
2 6 12 20 30 42 56 72 90

In [ ]:

9. Programs illustrating the concept of Numpy


1) Write a program that creates two arrays and performs a)
Addition

b) Multiplication

c) Transpose
In [36]: import numpy as np #Creating Arrays r1 =
int(input("Enter row number of array1 : "))
c1 = int(input("Enter column number of array1
: ")) print()
a1 = np.zeros([r1, c1], dtype
= int) for i in range(r1):
for j in range(c1):
a1[i, j] = int(input("Enter value here: "))

r2 = int(input("\nEnter row number of array2 :


")) c2 = int(input("Enter column number of
array2 : ")) print()
a2 = np.zeros([r2, c2], dtype = int)
for i in range(r2):
for j in range(c2):
a2[i, j] = int(input("Enter value here: "))
print("\nThese are your two arrays :-", "\na1:\n", a1,
"\na2:\n", a2)

#Adding the Arrays if


(a1.shape ==
a2.shape):
a3 = np.zeros_like(a1, dtype=int)
for i in range(r1): # or r2 and c2, same
thing, for j in range(c1):
a3[i, j] = a1[i, j] + a2[i, j]
print("\nThe sum of these arrays is \n:", a3)
else:
print("\nAddition not Possible.")
print("----- The dimensions of array1 and array2 are not
equal.")

#Multiplying the Arrays


if (c1 == r2):
a4 = np.zeros([r1, c2], dtype =
int) for i in range(r1):
for j in range(c2):
for k in range(r2):
a4[i, j] += a1[i, k] * a2[k, j]
print("\nThe product of these arrays is
:\n", a4) else:
print("\nMultiplication not possible.")
print("----- The number of columns of array1 is not equal to
the numb
#Transpose a1t =
np.zeros([c1, r1], dtype = int)
for i in range(r1):
for j in range(c1):
a1t[j, i] = a1[i, j]
print("\nThe transpose of array1
is:\n", a1t) a2t = np.zeros([c2, r2],
dtype = int) for i in range(r2):
for j in range(c2):
a2t[j, i] = a2[i, j]
print("\nThe transpose of array2
is:\n", a2t)
Enter row number of array1 : 2
Enter column number of array1 : 2

Enter value here: 1


Enter value here: 2
Enter value here: 3
Enter value here: 4

Enter row number of array2 : 2


Enter column number of array2 : 2
Enter value here: 5
Enter value here: 6
Enter value here: 7
Enter value here: 8

These are your two arrays :-


a1:
[[1 2]
[3 4]]
a2:
[[5 6]
[7 8]]

The sum of these arrays is


: [[ 6 8]
[10 12]]

The product of these arrays is :


[[19 22]
[43 50]]

The transpose of array1 is:


[[1 3]
[2 4]]

The transpose of array2 is:


[[5 7]
[6 8]]

2) Write a program to perform linear search in an array.


import numpy as np
In [3]:
def keySearch(arr,
k):
j = "Key %d is not found"%k for i
in range(len(arr)): if arr[i] == k:
n ="Key %d is found at index %d"%(k,i)
return n return j
a = np.array([1, 2,
4]) print("Array is
", a) m =
keySearch(a, 2) n =
keySearch(a, 6)
print(m) print(n)

Array is [1 2 4]
Key 2 is found at index 1
Key 6 is not found

3) Write a program to perform Binary search in an array.


import numpy as np
def Search(a, key, l,
r):
mid = l + r // 2
if r >= l: if
(key == a[mid]):
return "Key %d is found at index %d"%(key,
mid) elif (key >= a[mid]):
In [37]: return Search(a, key, mid+l, r)
elif (key < a[mid]):
return Search(a, key, l, mid)
return "Key %d is not Found"%key
# array should always be SORTED for BINARY
SEARCH a = np.array([1, 6, 4, 2, 0, 4, 9,
5, 56, 53])
a.sort() # or
np.sort(a) print(a)
print(type(a))
print(Search(a, 70, 0,
len(a)-1)) print(Search(a,
4, 0, len(a)-1))

[ 0 1 2 4 4 5 6 9 53 56]
<class 'numpy.ndarray'>
Key 70 is not Found
Key 4 is found at index 4

In [ ]:

Experiment 10 : Programs illustrating the


Concept of Pandas
Question 1: Create a dictionary on your own with following
mentioned columns

Rollno

Name

Subjects(to almost 4 subjects)

Marks

Make for 10 students.columns (subjects and marks)must


contain null and repeated values

1 John PWP 20

2 Mark OOPS 45 03 Clark PWP Null

and so on...

Then convert it into dataframe and do the analysis


import pandas as pd
In [7]:
import numpy as np
dict1 = {
'StudentName':['s0', 's1', 's2', 's3', 's4', 's5', 's6', 's7',
'OO 's8', '
'Subject':['PWP', 'PWP', 'OOC', 'OOC', 'PWP', 'PWP', 'MATH',
'PWP',
'Marks':[99, 95, 94, 92.5, 99, np.nan, 92, 94, 95, 97, 96]}
In [8]:
df = pd.DataFrame(dict1)

In [9]: df

Out[9]: StudentName Subject Marks


0 s0 PWP 99.0

1 s1 PWP 95.0
2 s2 OOC 94.0
3 s3 OOC 92.5
4 s4 PWP 99.0
5 s5 PWP NaN
6 s6 MATH 92.0
7 s7 PWP 94.0
8 s8 OOC 95.0
9 s9 OOC 97.0
10 s10 IIS 96.0
In [10]: df = df.drop(0)

In [11]: df
Out[11]: StudentName Subject Marks

1 s1 PWP 95.0
2 s2 OOC 94.0
3 s3 OOC 92.5
4 s4 PWP 99.0
5 s5 PWP NaN
6 s6 MATH 92.0
7 s7 PWP 94.0
8 s8 OOC 95.0
9 s9 OOC 97.0
10 s10 IIS 96.0
In [13]:
# Maximum Marks
column =
df["Marks"]
maxMarks = column.max()
maxIndex = column.idxmax()
name =
df['StudentName'][maxIndex]
print("Maximum Marks obtained are:", maxMarks, "of Roll No.
%d"%maxIndex
# Minimum Marks column = df["Marks"] minMarks = column.min()
minIndex = column.idxmin() name = df['StudentName'][minIndex]
print("\n\nMinimum Marks obtained are:", minMarks, "of Roll No.
%d"%minIn

Maximum Marks obtained are: 99.0 of Roll


No. 4

Minimum Marks obtained are: 92.0 of Roll


No. 6

In [14]: # No of students opting for a certain object


column = df['Subject']
column1 = column.unique()
# print(column)
for i in
column1:
count = 0 for j in column: if
(i == j): count += 1 print("No. of
Students opting for %s is %d"%(i, count))
No. of Students opting for IIS is 1

In [15]: df
Out[15]: StudentName Subject Marks

1 s1 PWP 95.0
2 s2 OOC 94.0
3 s3 OOC 92.5
4 s4 PWP 99.0
5 s5 PWP NaN
6 s6 MATH 92.0
7 s7 PWP 94.0
8 s8 OOC 95.0
9 s9 OOC 97.0
10 s10 IIS 96.0
In [16]: # Students who got A+ Grade i.e, more than 95
marks temp = df[df['Marks'] > 95]
print("Students who got A+ grade are: ")
print(temp.StudentName)

Students who got A+ grade are:


4 s4
9 s9
10 s10
Name: StudentName, dtype: object

In [18]: # Average Marks in PWP, OOC and MATH Respectively


temp1 = df[df['Subject'] == 'PWP'] temp2 =
df[df['Subject'] == 'OOC'] temp3 =
df[df['Subject'] == 'MATH'] print("Average
Marks in PWP are: %.2f"%temp1.mean())
print("Average Marks in OOC are:
%.2f"%temp2.mean()) print("Average Marks in
MATH are: %.2f"%temp3.mean())

Average Marks in PWP are: 96.00


Average Marks in OOC are: 94.62
Average Marks in MATH are: 92.00

In [19]: # Counting how many students got same marks


df['Marks'].value_counts()
# Or pd.value_counts(df['Marks'])

Out[19]: 94.0 2
95.0 2
96.0 1
97.0 1
92.0 1
99.0 1
92.5 1
Name: Marks, dtype: int64

In [20]: # Removing the marks of Absent Students


df.dropna()
Out[20]: StudentName Subject Marks

1 s1 PWP 95.0
2 s2 OOC 94.0
3 s3 OOC 92.5
4 s4 PWP 99.0
6 s6 MATH 92.0
7 s7 PWP 94.0
8 s8 OOC 95.0
9 s9 OOC 97.0
10 s10 IIS 96.0
Question 2:-
In [23]: import pandas as pd
deli=pd.read_csv('C:/deliveries.csv')

1 : find the player who has taken maximum catches


In [24]: b = deli[['dismissal_kind',
'fielder']] b = b.dropna() c =
b.drop_duplicates('fielder')
maxr = 0 for j in
c['fielder']:
count = 0 for k
in b['fielder']:
if (j == k):
count += 1 if
(count >= maxr):
maxr = count
player = j

In [25]: print(player, ":", maxr)


MS Dhoni : 159

2 : display the columns of the table


In [26]: deli.columns

Out[26]: Index(['match_id', 'inning', 'batting_team', 'bowling_team',


'over', 'bal l',
'batsman', 'non_striker', 'bowler', 'is_super_over',
'wide_runs',
'bye_runs', 'legbye_runs', 'noball_runs', 'penalty_runs',
'batsman_runs', 'extra_runs', 'total_runs',
'player_dismissed',
'dismissal_kind', 'fielder'],
dtype='object')
3 : Display the match id, bowler,batsman,batsman runs
andtotal runs.
In [27]: b = deli[['match_id', 'bowler', 'batsman', 'batsman_runs',
'total_runs'] print(b)

match_id bowler batsman batsman_runs


total_runs 0 1 TS Mills DA Warner
0 0
1 1 TS Mills DA Warner 0 0
2 1 TS Mills DA Warner 4 4
3 1 TS Mills DA Warner 0 0
4 1 TS Mills DA Warner 0 2
... ... ... ...
... ...
179073 11415 SL Malinga RA Jadeja 1 1
179074 11415 SL Malinga SR Watson 2 2
179075 11415 SL Malinga SR Watson 1 1
179076 11415 SL Malinga SN Thakur 2 2
179077 11415 SL Malinga SN Thakur 0 0

[179078 rows x 5 columns]

4 : Find the player who has scored maximum run


In [28]:
deli.groupby(['match_id','batsman'])['batsman_runs'].sum().sort_values(a

Out[28]: match_id batsman


411 CH Gayle 175
60 BB McCullum 158
562 AB de Villiers 133
7935 RR Pant 130
620 AB de Villiers 129
Name: batsman_runs, dtype: int64

5 : Print the top 5 batsman in descending order as per the


total run scored by them
In [29]:
deli.groupby('batsman')['batsman_runs'].sum().sort_values(ascending=False

Out[29]: batsman
V Kohli 5434
SK Raina 5415
RG Sharma 4914
DA Warner 4741
S Dhawan 4632
Name: batsman_runs, dtype: int64

In [ ]:

You might also like