1.
Compute sum, subtraction, multiplication, division and exponent of given
variables input by the user.
a=int(input(“enter first number”))
b=int(input(“second number”))
add = a+b
sub =a-b
mult = a*b
div = a/b
exp = a**b
print(“\n sum is :”, sum, “\n difference is :”, sub, “\n product is:”,mult, “\n quoitent is :”,div, “\n
exponent is :”,exp)
Output:
Enter first number 3
second number 2
sum is 5
difference is 1
product is 6
quotient is 1.5
exponent is 9
2. Compute area of following shapes: circle, rectangle, triangle, square,
trapezoid and parallelogram.
def calculate_area(name):
name = name.lower()
if name == "rectangle":
l = int(input("Enter rectangle's length: "))
b = int(input("Enter rectangle's breadth: "))
rect_area = l * b
print("The area of rectangle is {rect_area}.")
elif name == "square":
s = int(input("Enter square's side length: "))
sqt_area = s * s
print("The area of square is {sqt_area}.")
elif name == "triangle":
h = int(input("Enter triangle's height length: "))
b = int(input("Enter triangle's breadth length: "))
tri_area = 0.5 * b * h
print("The area of triangle is {tri_area}.")
elif name == "circle":
r = int(input("Enter circle's radius length: "))
pi = 3.14
circ_area = pi * r * r
print("The area of triangle is {circ_area}")
elif name == 'parallelogram':
b = int(input("Enter parallelogram's base length: "))
h = int(input("Enter parallelogram's height length: "))
para_area = b * h
print("The area of parallelogram is {para_area}")
else:
print("Sorry! This shape is not available)
print("Calculate Shape Area")
shape_name = input("Enter the name of shape whose area you want to find: ")
calculate_area(shape_name)
Output:
Enter the name of shape whose area you want to find:
Rectangle
Enter rectangle's length:5
Enter rectangle's breadth:6
The area of rectangle is 30
3. Compute volume of following 3D shapes: cube, cylinder, cone and sphere.
a = int(input(“enter the side of cube:”)
print (“volume of cube is :”a*a*a)
r = int (input (“enter the radius”)
b=int(input(“enter the height”)
print (“volume of cylinder is “,3.14*r*r*h)
r = int (input (“enter the radius”)
b=int(input(“enter the height”)
print (“volume of cone is “,3.14*r*r*h/3)
r = int (input (“enter the radius”)
print(“ volume of sphere is “4/3*r*r*r*3.14)
Output:
enter the side of cube: 4
volume of cube is :64
enter the radius 4
enter the height 8
volume of cylinder is 402.12
enter the radius 2
enter the height 5
volume of cone is 20.94
enter the radius 5
volume of sphere is 523.6
4. Compute and print roots of quadratic equation ax2+bx+c=0, where the
values of a, b, and c are input by the user.
import cmath
a=1
b=5
c=6
# calculate the discriminant
d = (b**2) - (4*a*c)
# find two solutions
sol1 = (-b-cmath.sqrt(d))/(2*a)
sol2 = (-b+cmath.sqrt(d))/(2*a)
print('The solution are {0} and {1}'.format(sol1,sol2))
Output:
Enter a: 1
Enter b: 5
Enter c: 6
The solutions are (-3+0j) and (-2+0j)
5. Print numbers up to N which are not divisible by 3, 6, 9,, e.g., 1, 2, 4, 5, 7,….
L=int(input("enter lower range limit"))
U=int(input("enter upper range limit"))
for i in range(L,U+1):
if(i%3!=0) and (i%6!=0) and (i%9!=0):
print(i)
Output:
enter lower range limit 1
enter upper range limit 15
NOS NOT DIVISIBLE ARE: 1 2 4 5 7 10 11 13 14
6. Write a program to determine whether a triangle is isosceles or not?
print("Input lengths of the triangle sides: ")
x = int(input("x: "))
y = int(input("y: "))
z = int(input("z: "))
if x == y == z:
print("Equilateral triangle")
elif x==y or y==z or z==x:
print("isosceles triangle")
else:
print("Scalene triangle")
Output:
Input lengths of the triangle sides:
x: 6
y: 6
z: 10
isosceles triangle
7. Print multiplication table of a number input by the user.
N=int(input("enter the number"))
for i in range (1,11):
print(N, "*",i , "=",N*i)
Output:
enter the number 5
5*1=5
5*2=10
5* 3=15
5*4=20
5*5=25
5*6=30
5*7=35
5*8=40
5*9=45
5*10=50
8. Compute sum of natural numbers from one to n number.
num = int(input("Enter the value of n: "))
a = num
sum = 0
if num <= 0:
print("Enter a whole positive number!")
else:
while num > 0:
sum = sum + num
num = num - 1;
print(sum)
Output:
Enter the value of n: 6
Sum of first 6 natural numbers is: 21
9. Print Fibonacci series up to n numbers e.g. 0 1 1 2 3 5 8 13…..n
nterms = int(input("How many terms? "))
# first two terms
n1, n2 = 0, 1
count = 0
if nterms <= 0:
print("Please enter a positive integer")
elif nterms == 1:
print("Fibonacci sequence upto",nterms,":")
print(n1)
else:
print("Fibonacci sequence:")
while count < nterms:
print(n1)
nth = n1 + n2
# update values
n1 = n2
n2 = nth
count += 1
Output:
How many terms? 10
Fibonacci sequence:
0 1 1 2 3 5 8 13 21 34
10. Compute factorial of a given number.
n = input("Enter a number: ")
factorial = 1
if int(n) >= 1:
for i in range (1,int(n)+1):
factorial = factorial * i
print("Factorial of ",n , " is : ",factorial)
Output:
Enter a number: 5
Factorial of 5 is : 120
11.Count occurrence of a digit 5 in a given integer number input by the users.
n=inter(input ('Enter a number:'))
Count =0
While (num>0) :
temp=num%10
If (temp==5):
Count = Count +1
num=num/10
print(Count)
Output:
Enter a number:2356515
12. Print Geometric & Harmonic means of a series input by the users.
from scipy. Stats import g mean
data = int(input ('Enter the elements:'))
result= g mean (data)
print (' geometric mean :% 3f '%result)
from scipy. Stats import h mean
data= int(input ('Enter the elements:'))
result=h mean (data)
print ('harmonic mean :% 3f'%result)
Output:
Enter the element:1 2 3 40 50 60 0.70 88 0.9 1000
geometric mean:7.2456
Enter the element: 0.11 0.22 0.33 0.44 0.55 0.66 0.77 0.88 0.99
harmonic mean:0.350
13. Evaluate the following expressions:
a. x-x2/2!+x3/3!- x4/4!+…xn/n!
b. x-x3/3!+x5/5!- x7/7!+…xn/n!
def fact(m):
if m-=0:
return 1
else:
return m*fact(m-1)
s=0
x=int(input('enter x:'))
n=int(input('enter n:'))
for i in range(1,n+1):
s=s+((-1)*(i+1))((x**i)/fact(i))
print (s)
Output:
Enter x:1
Enter n:3
1.0
0.5
0.66666666666666666
b) def fact(m):
if m==0:
return 1
else:
return m*fact(m-1)
s=0
x=int(input('enter x :'))
n=int(input('enter n:'))
for i in range (1,n+1)):
k=2*i-1
s=s+((-1)*(i+1)((x**k)/fact(k))
print("sum of all the series:",round(3,3))
Output:
enter x:1
enter n:4
sum of series:0.841
14. Print all possible combinations of 4,5,&6
def comb(L) :
for i in range (3) :
for j in range (3) :
for k in range (3) :
If (i! = j and j! =k and i! =k) :
Print (L[i], L[j], L[k])
Comb([4,5,6])
Output:
456
465
546
564
645
654
15. Determine prime numbers within range.
lower=int (input ('Enter lower range:'))
upper=int (input ('Enter upper range:'))
for num in range (lower, upper +1) :
if num>1:
for i in range (2, num)
if (num%i) ==0:
break
else:
print (num)
Output:
Enter lower range:10
Enter upper range:50
11 13 17 19 23 29 31 37 41 43 47
16. Count number of person of age above 60 & below 90.
L= [21,42,51,61,90,10197,61]
C=0
for x in L:
if x > = 60 and x < = 90:
C=C+1
Print ('Number of persons above 60 and below 90 are:')
Print (C)
Output:
Number of persons above 60 and below 90:
17. Compute transpose of a matrix.
M=3
N=4
def transpose(A, B):
for i in range(N):
for j in range(M):
B[i][j] = A[j][i]
A = [ [1, 1, 1, 1],
[2, 2, 2, 2],
[3, 3, 3, 3]]
# To store result
B = [[0 for x in range(M)] for y in range(N)]
transpose(A, B)
print("Result matrix is")
for i in range(N):
for j in range(M):
print(B[i][j], " ", end='')
print()
Output:
Result matrix is
1 2 3
1 2 3
1 2 3
1 2 3
18. Perform following operations on two matrices.
1) Addition
X = [[1,2,3],
[4 ,5,6],
[7 ,8,9]]
Y = [[9,8,7],
[6,5,4],
[3,2,1]]
result = [[0,0,0],
[0,0,0],
[0,0,0]]
# iterate through rows
for i in range(len(X)):
# iterate through columns
for j in range(len(X[0])):
result[i][j] = X[i][j] + Y[i][j]
for r in result:
print(r)
2) Subtraction
X = [[1,2,3],
[4 ,5,6],
[7 ,8,9]]
Y = [[9,8,7],
[6,5,4],
[3,2,1]]
result = [[0,0,0],
[0,0,0],
[0,0,0]]
# iterate through rows
for i in range(len(X)):
# iterate through columns
for j in range(len(X[0])):
result[i][j] = X[i][j] - Y[i][j]
for r in result:
print(r)
3) Multiplication
X = [[12,7,3],
[4 ,5,6],
[7 ,8,9]]
# 3x4 matrix
Y = [[5,8,1,2],
[6,7,3,0],
[4,5,9,1]]
# result is 3x4
result = [[0,0,0,0],
[0,0,0,0],
[0,0,0,0]]
for i in range(len(X)):
# iterate through columns of Y
for j in range(len(Y[0])):
# iterate through rows of Y
for k in range(len(Y)):
result[i][j] += X[i][k] * Y[k][j]
for r in result:
print(r)
19. Count occurrence of vowels.
vowels = 'aeiou'
ip_str = 'We all from CGC Landran'
ip_str = ip_str.casefold()
count = {}.fromkeys(vowels,0)
for char in ip_str:
if char in count:
count[char] += 1
print(count)
Output:
{'a': 3, 'e': 1, 'i': 0, 'o': 1, 'u': 0}
20. Count total number of vowels in a word.
def Check_Vow(string, vowels):
final = [each for each in string if each in vowels]
print(len(final))
print(final)
string = "We are studying Python from Dr. Rupinder Singh"
vowels = "AaEeIiOoUu"
Check_Vow(string, vowels);
Output:
11
['e', 'a', 'e', 'u', 'i', 'o', 'o', 'u', 'i', 'e', 'i']
21. Determine whether a string is palindrome or not.
my_str = 'nitin'
my_str = my_str.casefold()
rev_str = reversed(my_str)
if list(my_str) == list(rev_str):
print("The string is a palindrome.")
else:
print("The string is not a palindrome.")
Output:
The string is a palindrome.
22. Perform following operations on a list of numbers:
1) Insert an element
list1 = [ 1, 2, 3, 4, 5, 6, 7 ]
list1.insert(4, 10)
print(list1)
Output:
[1, 2, 3, 4, 10, 5, 6, 7]
2) delete an element
lis = [2, 1, 3, 5, 4, 3, 8]
del lis[2 : 5]
print(lis)
Output:
[2, 1, 3, 8]
3) sort the list
cars = ['Ford', 'BMW', 'Volvo']
cars.sort()
print(cars)
Output:
['BMW', 'Ford', 'Volvo']
4) delete entire list
cars = ['Ford', 'BMW', 'Volvo']
cars.sort()
del(cars)
print(cars)
23. Display word after Sorting in alphabetical order.
my_str = "We all are from CGC Landran"
words = [word.lower() for word in my_str.split()]
words.sort()
print("The sorted words are:")
for word in words:
print(word)
Output:
The sorted words are:
all
are
cgc
from
landran
we
24. Perform sequential search on a list of given numbers.
def ls(arr, x):
for i in range(len(arr)):
if arr[i] == x:
return i
return -1
arr = ['t','u','t','o','r','i','a','l']
x = input("Enter an element to be searched")
print("element found at index "+str(ls(arr,x)))
Output:
Enter an element to be searched ‘o’
element found at index 3
25. Perform sequential search on ordered list of given numbers.
def ls(arr, x):
for i in range(len(arr)):
if arr[i] == x:
return i
return -1
arr = [1,2,3,4,5,6,7]
x = int(input("Enter an element to be searched"))
print("element found at index "+str(ls(arr,x)))
Output:
Enter an element to be searched 5
element found at index 4
26. Maintain practical note book as per their serial numbers in library
using Python dictionary.
class notebook:
def fun(self):
self.dic={1:"Computer Networks",2:"Python",3:"Data Structure",4:"PC Assembly"}
def disp(self):
print(self.dic)
ob=notebook()
ob.fun()
ob.disp()
Output:
{1: 'Computer Networks', 2: 'Python', 3: 'Data Structure', 4: 'PC Assembly'}
27. Perform following operations on dictionary
1) Insert
dic = { "Col" : "CGC" , "Loc" : "Landran" , "City" : "Mohali" }
dic['Country']='India’
print(dic)
Output:
{'Col': 'CGC', 'Loc': 'Landran', 'City': 'Mohali', 'Country': 'India'}
2) delete
dic = {'Col': 'CGC', 'Loc': 'Landran', 'City': 'Mohali', 'Country': 'England’}
del dic['Col']
print(dic)
Output :
{'Loc': 'Landran', 'City': 'Mohali', 'Country': 'England'}
3) change
dic = {'Col': 'CGC', 'Loc': 'Landran', 'City': 'Mohali', 'Country': 'India'}
dic['Country']='England’
print(dic)
Output:
{'Col': 'CGC', 'Loc': 'Landran', 'City': 'Mohali', 'Country': ‘England'}
28. Check whether a number is in a given range using functions.
X=1
Y = 50
def checkRange(num):
if X <= num <= Y:
print('The number {} is in range ({}, {})'.format(num, X, Y))
else:
print('The number {} is not in range ({}, {})'.format(num, X, Y))
# Test Input List
testInput = [X-1, X, X+1, Y+1, Y, Y-1]
for eachItem in testInput:
checkRange(eachItem)
Output:
The number 0 is not in range (1, 50)
The number 1 is in range (1, 50)
The number 2 is in range (1, 50)
The number 51 is not in range (1, 50)
The number 50 is in range (1, 50)
The number 49 is in range (1, 50)
29. Write a Python function that accepts a string and calculates number of
upper case letters and lower case letters available in that string.
def fun():
str=input("Enter a string: ")
upper=0
lower=0
for i in range(len(str)):
if(str[i]>='a' and str[i]<='z'):
lower+=1
elif(str[i]>='A' and str[i]<='Z'):
upper+=1
print('Lower case letters= ',lower)
print('Upper case letters=' ,upper)
fun()
Output:
Enter a string: Rupinder
Lower case letters= 7
Upper case letters= 1
30. To find the Max of three numbers using functions.
def maximum(a, b, c):
if (a >= b) and (a >= c):
largest = a
elif (b >= a) and (b >= c):
largest = b
else:
largest = c
return largest
a = 10
b = 14
c = 12
print(maximum(a, b, c))
Output:
14
31. Multiply all the numbers in a list using functions.
def multiplyList(myList) :
result = 1
for x in myList:
result = result * x
return result
list1 = [1, 2, 3]
print(multiplyList(list1))
Output:
32. Solve the Fibonacci sequence using recursion.
def recur_fibo(n):
if n <= 1:
return n
else:
return(recur_fibo(n-1) + recur_fibo(n-2))
nterms = 10
if nterms <= 0:
print("Plese enter a positive integer")
else:
print("Fibonacci sequence:")
for i in range(nterms):
print(recur_fibo(i))
Output:
Fibonacci sequence:
0 1 1 2 3 5 8 13 21 34
33. Get the factorial of a non-negative integer using recursion.
def recur_factorial(n):
if n == 1:
return n
else:
return n*recur_factorial(n-1)
num=int(input("Enter a positive number"))
# check if the number is negative
if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
print("The factorial of", num, "is", recur_factorial(num))
Output:
Enter a positive number 6
The factorial of 6 is 720
34. Write a program to create a module of factorial in Python.
#findfact.py function to find factorial
def fact(n):
""" Function to find factorial """
if n == 1:
return 1
else:
return (n * fact(n-1))
def check_num(a):
if a > 0:
print (a ," is a positive number.")
elif a == 0:
print ("Number is zero.")
else:
print (a ," is negative number.")
Ouput:
import findfact
findfact.fact(5)
120
35. Design a Python class named Rectangle, constructed by a length &
width, also design a method which will compute the area of a rectangle.
class Rectangle():
def __init__(self, l, w):
self.length = l
self.width = w
def rectangle_area(self):
return self.length*self.width
newRectangle = Rectangle(12, 10)
print(newRectangle.rectangle_area())
Output:
120
36. Design a Python class named Circle constructed by a radius and two
methods which will compute the area and the perimeter of a circle.
import math
class circle():
def __init__(self,radius):
self.radius=radius
def area(self):
return math.pi*(self.radius**2)
def perimeter(self):
return 2*math.pi*self.radius
r=int(input("Enter radius of circle: "))
obj=circle(r)
print("Area of circle:",round(obj.area(),2))
print("Perimeter of circle:",round(obj.perimeter(),2))
Output:
Enter radius of circle: 10
Area of circle: 314.16
Perimeter of circle: 62.83
37. Design a Python class to reverse a string ‘word by word’.
def reverseWordSentence(Sentence):
words = Sentence.split(" ")
newWords = [word[::-1] for word in words]
newSentence = " ".join(newWords)
return newSentence
Sentence = "We are doing python"
print(reverseWordSentence(Sentence))
Output:
eW era gniod nohtyp
38. Write a Python program to read an entire text file.
def file_read(fname):
txt = open(fname)
print(txt.read())
file_read('test.txt')
Output:
We are from CGC
Studying python
39. Design a Python program to read first n lines of a text file.
def file_read_from_head(fname, nlines):
from itertools import islice
with open(fname) as f:
for line in islice(f, nlines):
print(line)
file_read_from_head('test.txt',2)
40. Construct a Python program to write and append text to a file and
display the text.
file1 = open("myfile.txt", "w")
L = ["We are from \n", "CGC \n", "LANDRAN"]
file1.writelines(L)
file1.close()
# Append-adds at last
file1 = open("myfile.txt", "a") # append mode
file1.write("\nMOHALI PUNJAB \n")
file1 = open("myfile.txt", "r")
print("Output of Readlines after appending")
print(file1.read())
print()
file1.close()
Output:
Output of Read lines after appending
We are from
CGC
LANDRAN
MOHALI PUNJAB