Page 1 :
SEMESTER 1 LAB MANUAL, 1. Write a python program to:, 1) Read three numbers., 2) Add the numbers and print the result., 3) Print whether the numbers are positive/negative using if-else., 4) Find largest among them., n=int(input('enter the first number')), m=int(input('enter the second number')), s=int(input('enter the third number')), print('first number is',n), print('second number is',m), print('third number is',s), q=n+m+s, print("sum is",q), if n>0:, print('the first number is +ve'), elif n<0:, print('the first number is -ve'), else:, print('the number is zero'), if m>0:, print(' the second number is +ve'), elif m<0:, print('the second number is -ve'), if s>0:, print('the third number is +ve'), elif s<0:, print( 'the third number is -ve'), else:, print('the numbers are zero'), if n>m and n>s:, print('the first number is greater'), elif m>n and m>s:, print('the second number is greater'), elif s>m and s>n:, print('the third number is greater'), else:, print('the numbers are same'), Output:, enter the first number3, enter the second number4, enter the third number5, first number is 3, second number is 4, third number is 5, sum is 12, the first number is +ve, the second number is +ve, the third number is +ve, the third number is greater
Page 2 :
2. Write a python program to find factorial of a number read from the user., n=int(input("enter number: ")), factorial=1, if n<0:, print("factorial does not exist"), elif n==0:, print("factorial is 1"), else:, for i in range(1,n+1):, factorial=factorial*i, print("factorial of number=",factorial), Output:, enter number: 3, output: factorial of number=6, 3. Input five integers (+ve and −ve). Write Python code to find the sum of negative numbers and, positive numbers separately and print them. Also, find the average of all the numbers., 4. Write a Python program to print the Multiplication table of a number?, n=int(input("enter a number")), i=1, while i<=10:, p=n*i, print(n,"×",i,"=",p), i=i+1, Output:, enter a number4, 4×1=4, 4×2=8, 4 × 3 = 12, 4 × 4 = 16, 4 × 5 = 20, 4 × 6 = 24, 4 × 7 = 28, 4 × 8 = 32, 4 × 9 = 36, 4× 10 = 40, 5. Write a Python program to check whether the last digit divisible by 3 or not?, num=float(input("Enter a number: ")), rem=num%10, if rem%3==0:, print("The last digit of",num,"is divisible by 3"), else:, print("The last digit of",num,"is not divisible by 3"), Sample Output:, Enter a number: 343, The last digit of 343.0 is divisible by 3
Page 3 :
6. Write a Python program to read a number from the user and check whether it is Palindrome or, not., n=int(input("Enter number:")), temp=n, rev=0, while(n>0):, dig=n%10, rev=rev*10+dig, n=n//10, if(temp==rev):, print("The number is a palindrome!"), else:, print("The number isn't a palindrome!"), Output:, Enter number:121, The number is a palindrome!, 7. Write Python Program to reverse a number and also find the Sum of digits in the reversed, number. Prompt the user for input., n=int(input("Enter number: ")), rev=0, tot=0, while(n>0):, dig=n%10, rev=rev*10+dig, n=n//10, print("Reverse of the number:",rev), while(rev>0):, digit=rev%10, tot=tot+digit, rev=rev//10, print("The total sum of digits is:",tot), sample output, Enter number: 27, Reverse of the number: 72, The total sum of digits is: 9, 8. Write a Python program to check if a 3 digit number is Armstrong number or not., # take input from the user, num = int(input("Enter a number: ")), # initialize sum, sum = 0, # find the sum of the cube of each digit, temp = num, while temp > 0:, digit = temp % 10, sum += digit ** 3, temp //= 10, # display the result, if num == sum:
Page 4 :
print(num,"is an Armstrong number"), else:, print(num,"is not an Armstrong number"), sanple output, Enter a number: 407, 407 is an Armstrong number, 9. Write a Python program to print Fibonnacci series?, n=int(input('Enter the number of terms')), n1=0, n2=1, count=0, while(count<n):, print(n1), n3=n1+n2, n1=n2, n2=n3, count+=1, Sample Output:, Enter the number of terms 10, 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 10. Write a Python program to display number pyramid?, rows=int(input("Enter the rows")), for i in range(0,rows+1):, for j in range(i):, print(i,end = ''), print(), Sample Output:, Enter the rows3, 1, 22, 333, 11. Write a Python program to display pattern pyramid?, # User input for number of rows, rows = int(input("Enter the rows:")), # Outer loop will print number of rows, for i in range(0,rows+1):, # Inner loop will print number of Astrisk, for j in range(i):
Page 5 :
print("*",end = ''), print(), Sample Output :, Enter the rows:3, *, **, ***, 12. Write a Python program to check whether the year is leap year or not?, n=int(input("enter the year:")), if n%400==0 or n%100!=0 and n%4==0:, print("This year is a leap year"), else:, print("This year is not a leap year"), , Sample Output:, enter the year:2016, This year is a leap year, enter the year:2022, This year is not a leap year, 13. Start with the list L = []. Do the following using list functions., 1) Add items 8, 9 and 10 one-by-one., 2) Set the second entry to 17., 3) Add 4, 5 and 6 to the end of the list together., 4) Remove the first entry from the list., 5) Double the list., 6) Insert 25 at index 3., 7) Delete the last item in the list., 8) Print the list on a single line., 9) Print the list with each element on a new line., 10) Delete all the elements of the list., #1, L=[], L.append(8), L.append(9), L.append(10), print(L), #2, L[1] = 17, print("after entering 17",L), #3, L.extend([4, 5, 6]), print("after entering 4,5,6 together",L), #4, L.pop(0), print("after removing first entry",L), #5, L=L* 2, print("DOUBLE THE LIST",L), #6
Page 6 :
L[3]=25, print(L), #7, L.pop(-1), print("DELETED LAST VALUE",L), #8, print(L), #9, print(*L,sep="\n"), #10, print("deletion"), L.clear(), print(L), Sample output, [8, 9, 10], after entering 17 [8, 17, 10], after entering 4,5,6 together [8, 17, 10, 4, 5, 6], after removing first entry [17, 10, 4, 5, 6], DOUBLE THE LIST [17, 10, 4, 5, 6, 17, 10, 4, 5, 6], [17, 10, 4, 25, 6, 17, 10, 4, 5, 6], DELETED LAST VALUE [17, 10, 4, 25, 6, 17, 10, 4, 5], [17, 10, 4, 25, 6, 17, 10, 4, 5], 17, 10, 4, 25, 6, 17, 10, 4, 5, deletion, [], 14. Create a dictionary and perform the following:, 1) Print the dictionary items, 2) access items, 3) change values, 4) use len(), d={1:'a', 2:'b', 3:'c'}, print("print dictionary"), print(d), print("access items"), print(d[1]), print(d[2]), print(d[3])
Page 7 :
print("change values"), d[1]='e', print(d), print("length"), print(len(d)), Output:, print dictionary, {1: 'a', 2: 'b', 3: 'c'}, access items, a, b, c, chnage values, {1: 'e', 2: 'b', 3: 'c'}, length, 3, 15. Write Python program to generate a dictionary that contains (i: i*i) such that i is a number, ranging from 1 to n., n=int(input("Enter a number:")), d={x:x*x for x in range(1,n+1)}, print(d), sample output, Enter a number:6, {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36}, 16. Create a dictionary and perform the following operations:, print dictionary items,access items,update(),change value, my_dict={'name':'Jack','course':'computer','age':26}, print("dictionary items"), print(my_dict), print("access items"), print(my_dict['name']), print("update"), new={'course':'maths'}, my_dict.update(new), print(my_dict), print("change value"), my_dict['age']=27, print(my_dict), Sample Output:, dictionary items, {'name': 'Jack', 'course': 'computer', 'age': 26}, access items, Jack, update, {'name': 'Jack', 'course': 'maths', 'age': 26}, change value, {'name': 'Jack', 'course': 'maths', 'age': 27}, 17. Create a list and perform the following methods?, insert(),remove(),append(),pop(),clear(), L=[1,2,3,4]
Page 8 :
print(L), L.insert(2,8), print(L), L.remove(4), print(L), L.append(10), print(L), L.pop(0), print(L), L.clear(), print(L), Output:, [1, 2, 3, 4], [1, 2, 8, 3, 4], [1, 2, 8, 3], [1, 2, 8, 3, 10], [2, 8, 3, 10], [], 18. Write a Python program to demonstarte inheritance?, class person:, def __init__(self,name,age):, self.name=name, self.age=age, def display(self):, print('name:',self.name), print('age:',self.age), class student(person):, def __init__(self,rollno,name,age,per):, self.rollno=rollno, person.__init__(self,name,age), self.per=per, def display(self):, print('rollno:',self.rollno), person.display(self), print('percentage:',self.per), s1=student(25,'Pallavi',20,87), print('student details:'), s1.display(), Sample Output:, student details:, rollno: 25, name: Pallavi, age: 20, percentage: 87, 19. Write a Python program to create a menu to perform all mathematical operations of a, calculator. Accept user input and perform the operations accordingly. Use functions with, arguments to perform each operation., def add(x,y):, return x + y
Page 9 :
def subtract(x,y):, return x-y, def multiply(x,y):, return x* y, def divide (x,y):, return x / y, print("select operation"), print("1.add"), print("2.subtract"), print("3.multiply"), print("4.divide"), while True :, choice = input("enter choice (1/2/3/4):"), if choice in ('1','2','3','4') :, n1= float(input("enter first number:")), n2=float(input("enter second number")), if choice == '1':, print(n1, "+", n2, "=", add(n1,n2)), elif choice == '2':, print(n1, "-", n2, "=", subtract(n1,n2)), elif choice == '3':, print(n1, "*", n2, "=", multiply(n1,n2) ), elif choice == '4':, print (n1, "/", n2, "=",divide(n1,n2)), else:, print("invalid input"), Output:, select operation, 1.add, 2.subtract, 3.multiply, 4.divide, enter choice (1/2/3/4):1, enter first number:3, enter second number:4, 3.0 + 4.0 = 7.0, 20. Write a program to read 3 subject marks and display passed or failed using class and object., class mark:, def firstmark(self):, n1=int(input('Enter the first mark')), if(n1>=30):, print('passed'), else:, print('failed')
Page 10 :
def secondmark(self):, n2=int(input('Enter the second mark')), if(n2>=30):, print('passed'), else:, print('failed'), def thirdmark(self):, n3=int(input('Enter the third mark')), if(n3>=30):, print('passed'), else:, print('failed'), obj=mark(), print(obj.firstmark()), print(obj.secondmark()), print(obj.thirdmark()), OUTPUT, Enter the first mark 97, passed, None, Enter the second mark 89, passed, None, Enter the third mark 25, failed, None, 21. Write a Python program to read a string and use re module to, 1) Check whether the string matches a string that has an a followed by zero or more b's., 2) Check whether the string matches a string that matches a string that has an a followed by, one or more b's., 3) Check whether the string matches the sequences of one upper case letter followed by lower, case letters., Use functions to perform the checking., 22. Write a Python program to check whether a number is prime or not. Use a function that takes a, number as a parameter for the checking., def isprime(num):, if num> 1:, for n in range(2,num):, if (num % n) == 0:, return False, return True, else:, return False, print(isprime(49)), print(isprime(13)), Output:, False, True
Page 11 :
23. Write Python Program to simulate a Bank Account with support for depositMoney,, withdrawMoney and showBalance Operations. Use the concept of classes and objects., class bankaccount:, bal=10000, def deposit(self):, amount1=int(input("Enter the amount to deposit")), baln=bankaccount.bal+amount1, print("Your current balance:",baln), def withdraw(self):, amount2=int(input("Enter the amount to withdraw")), if amount2>bankaccount.bal:, print("The amount cannot be withdrawed"), return, baln=bankaccount.bal-amount2, print("Your current balance:",baln), def balance(self):, baln=bankaccount.bal, print("Your current balance:",baln), print("1.Deposit"), print("2.Withdraw"), print("3.Balance"), choice=int(input("Enter your input:")), obj=bankaccount(), if choice==1:, obj.deposit(), elif choice==2:, obj.withdraw(), elif choice==3:, obj.balance(), else:, print("Wrong Choice"), output:, 1.Deposit, 2.Withdraw, 3.Balance, Enter your input:1, Enter the amount to deposit300, Your current balance: 10300, 24. Using NumPy module, perform the following:, 1. Create a 2D numpy array with 3 columns and 10 rows filled with random numbers, 2. Find the mean of the first column, 3. Find the median of the second column, 4. Find the standard deviation of the third column, import numpy as np
Page 12 :
np.random.seed(0), x=np.random.randint(0,10,(10,3)), print(x), print("MEAN OF FIRST COLUMN"), print(np.mean(x[:,0])), print("MEDIAN OF SECOND COLUMN"), print(np.mean(x[:,1])), print("STANDARD DEVIATION OF THIRD COUMN"), print(np.std(x[:,2])), OUTPUT, [[5 0 3], [3 7 9], [3 5 2], [4 7 6], [8 8 1], [6 7 7], [8 1 5], [9 8 9], [4 3 0], [3 5 0]], MEAN OF FIRST COLUMN, 5.3, MEDIAN OF SECOND COLUMN, 5.1, STANDARD DEVIATION OF THIRD COUMN, 3.3105890714493698, 25. Write a Python program to create numpy array and find the following aggregation in numpy?, sum,product,mean,median,minimum,maximum, import numpy as np, arr = np.array ([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]), print(arr), sum = np.sum(arr), print("sum is=",sum), product = np.prod(arr), print("product is=",product), mean = np.mean(arr), print("mean is=",mean), median = np.median(arr), print("median is=",median), minimum = np.min(arr), print("minimun is=",minimum), maximum =np.max(arr), print("maximum is=",maximum), Sample Output:, [ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15], sum is= 120, product is= 1307674368000, mean is= 8.0, median is= 8.0, minimun is= 1, maximum is= 15
Page 13 :
26. Write a Python program to create numpy array and find the following aggregation in numpy?, standard deviation,variance,mean of each row,sumof each column, import numpy as np, arr = np.array([1,2,3,4,5,6,7,8,9,10,11,12]), array = arr.reshape(4,3), print(array), SD = np.std(array), print("standard deviation=",SD), variance=np.var(array), print("variance=", variance), row_mean = np.mean(array,axis=1), print("row_mean=",row_mean), column_sum=np.sum(array,axis=0), print("column_sum=",column_sum ), Sample Output:, [[ 1 2 3], [ 4 5 6], [ 7 8 9], [10 11 12]], standard deviation= 3.452052529534663, variance= 11.916666666666666, row_mean= [ 2. 5. 8. 11.], column_sum= [22 26 30], 27. Write a Python program to create 2D numpy array and perform the following : access first row, elements,access second column elements,access first row second column boolean indexing,fancy, indexing, import numpy as np, twoD=np.array([[1,2,3],[4,5,6]]), print("2D ARRAY"), print(twoD), print("firstrow elements"), print(twoD[0]), print("secondcolumn elements"), print(twoD[:,1]), print("first row second column element"), print(twoD[0,1]), print("boolean indexing"), print(np.count_nonzero(twoD<6)), print("fancy indexing"), row=np.array([0,1]), col=np.array([2,1]), print(twoD[row,col]), Sample Output:, 2D ARRAY, [[1 2 3], [4 5 6]], firstrow elements, [1 2 3]
Page 14 :
secondcolumn elements, [2 5], first row second column element, 2, boolean indexing, 5, fancy indexing, [3 5], 28. Write a Python program to sort a 2D numpy array elements along horizontal and vertical?, import numpy as np, x=np.array([[7,5,3],[4,8,6]]), print(x), print("along column"), y=np.sort(x,axis=0), print(y), print("along row"), z=np.sort(x,axis=1), print(z), Sample Output:, [[7 5 3], [4 8 6]], along column, [[4 5 3], [7 8 6]], along row, [[3 5 7], [4 6 8]], 29. Write a Python program to handle missing values in pandas using a single value, previous value, and next value?, import pandas as pd, import numpy as np, data=pd.Series([1,np.nan,2,None,3]), print(data), print("using a value"), print(data.fillna(0)), print("using previous value"), print(data.fillna(method='ffill')), print("using next value"), print(data.fillna(method='bfill')), Sample Output:, 0 1.0, 1 NaN, 2 2.0, 3 NaN, 4 3.0, dtype: float64, using a value, 0 1.0, 1 0.0, 2 2.0, 3 0.0, 4 3.0
Page 15 :
dtype: float64, using previous value, 0 1.0, 1 1.0, 2 2.0, 3 2.0, 4 3.0, dtype: float64, using next value, 0 1.0, 1 2.0, 2 2.0, 3 3.0, 4 3.0, dtype: float64, 30. Write a Python program to demonstarte hierarchial indexing in pandas and perform the, following: access single elements,partial indexing, import pandas as pd, mi=pd.MultiIndex(levels=[[1,2,3],['red','blue','green']],codes=[[0,0,0,1,1,1,2,2,2],[0,1,2,0,1,2,, 0,1,2]]), values=[100,101,102,200,201,202,300,301,302], df=pd.Series(values,mi), print(df), print("accessing single elements"), print(df[1,'red']), print("partial indexing"), print(df[1]), Sample Output:, 1 red, 100, blue 101, green 102, 2 red, 200, blue 201, green 202, 3 red, 300, blue 301, green 302, dtype: int64, accessing single elements, 100, partial indexing, red, 100, blue 101, green 102, dtype: int64, 31. Given a dataset, Churn_Modelling.csv, perform the following visualization using Matplotlib., 1) Read the dataset into a dataframe, 2) Print first five rows of the dataset
Page 17 :
32. Given a dataset, company_sales_data.csv, perform the following visualization using Matplotlib., 1) Read Total profit of all months and show it using a line plot, 2) Get total profit of all months and show line plot with the following Style properties:, (i) Line Style dotted and Line-color should be red, (ii) Show legend at the lower right location., (iii) X label name = Month Number, (iv) Y label name = Sold units number, (v) Add a circle marker., (vi) Line marker color as read, (vii) Line width should be 3, 3) Read all product sales data and show it using a multiline plot, 4) Read sales data of bathing soap of all months and show it using a bar chart., 1) import pandas as pd, import matplotlib.pyplot as plt, , df = pd.read_csv("company_sales_data.csv"), profitList = df ['total_profit'].tolist(), monthList = df ['month_number'].tolist(), , plt.plot(monthList, profitList, label = 'Month-wise Profit data of last year'), plt.xlabel('Month number'), plt.ylabel('Profit in dollar'), plt.xticks(monthList), plt.title('Company profit per month')