PYTHON

 PYTHON LAB MANUAL


DATA ANALYTICS WITH PYTHON PROGRAMMING LAB

 

PROGRAM 1:  Printing Numbers

 

PROBLEM:

 Write a program to print number from 1 to n using for loop and while loop.

 (Input consists of an integer n. The numbers in the output are separated by a   single space. This is a trailing space at the end.)

  

Input

5

Output

1 2 3 4 5

  

AIM:

 To write a program to print number from 1 to n using for loop and while loop. 

 

ALGORITHM:

 

Step 1:   Start the program.

Step 2:   Read an integer number using input () function.

Step 3:   Repeat the loop until i=number reached.

Step 4:   Increment the i value.

Step 5:   Print the number.

Step 6:   Stop the process.

 

PROGRAM:

print("Printing Natural Numbers")

print("\nUsing for loop" )

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

for i in range (n+1):

    if (i==0):

        continue

    print (i, end=" ")

print("\nUsing while loop")

i=1

while(i<=n):

    print(i, end=" ")

    i+=1

 

OUTPUT:

Printing Natural Numbers

Using for loop

Enter n:10

1 2 3 4 5 6 7 8 9 10

Using while loop

1 2 3 4 5 6 7 8 9 10

  

PROGRAM 2:  Pattern Generation

 

PROBLEM:

    Write a Program to generate the given pattern. (Input consists of a single integer, n)

Input

4

Output

CSK
CCSSKK
CCCSSSKKK

CCCCSSSSKKKK

 

AIM:

To write a program to generate the given pattern:

CSK

CCSSKK

CCCSSSKKK

CCCCSSSSKKKK

 

ALGORITHM:

Step 1 : Start the process.

Step 2 : Get an input as a positive number.

Step 3 : Use two for loops to generate the given pattern :

                    CSK

                    CCSSKK

                    CCCSSSKKK

                    CCCCSSSSKKKK

Step 4 : Print the pattern.

Step 5 : End the process.

 

 

PROGRAM:

n=int (input("Enter a Positive Number:"))

s="CSK"

t=len(s)

c=1

for i in range(n):

    for j in range(t):

        print(s[j]*c,end=" ")

    c+=1

    print()

OUTPUT:

Enter a Positive Number:4

CSK

CCSSKK

CCCSSSKKK

CCCCSSSSKKKK

 

PROGRAM 3: GENERATE THE SERIES

PROBLEM:   

    Write a program to generate the first n terms the series ---20,19,17,…,10,5.

 (Note): Input consists of a single integer which corresponds to n output consists of the terms in the series separated by a blank space.

Input

6

4

Output

20 19 17 14 10 5

20 19 17 14

  

AIM:

    To write a program to generate the first n terms the series ---20,19,17,…,10,5.

ALGORITHM :   

     Step 1:   Start the process.

     Step 2:   Get an integers n as input.

     Step 3:   Use a while loop to n number from the series 20,19,17,14,10,5....

     Step 4:   Print the results.

     Step 5:   End the process.

 

PROGRAM:

n=int(input("Enter an integer:"))

i=1

s=20

print("Output series…")

while(i<=n):

    print(s,end=" ")

    s=s-i

    i+=1

print()

OUTPUT:

Enter an integer

6

Output series…

20 19 17 14 10 5


 

PROGRAM 4:  Anagram

PROBLEM:

        Write a program to find whether the 2 given  strings are anagrams or not. Anagrams are words or phrases made by mixing up the letters of other words or phrases.    (Note: Input consists of  2 string. Assume that all characters  in the string are lowercase letters or spaces and the maximum length of the string is 100.)

 ALGORITHM:

 

Step 1: Start the python tool  

Step 2: Get two input string from user

Step 3: Traverse list of string 

Step 4: Sort each string in ascending order.

Step 5: Check whether two stored string are equal.

Step 6: If the condition is equal, print it is an anagram or else not an anagram.

Step 7: Stop the process

 

PROGRAM

str1=input("Enter the first string\n")

str2=input("Enter the second string\n")

lstr1=list(str1)

lstr2=list(str2)

lstr1.sort()

lstr2.sort()

if  lstr1==lstr2:

     print("%s and %s are anagrams"%(str1,str2))

else:

      print("%s and %s are not anagrams"%(str1,str2))

OUTPUT:

Enter the first string

the eyes

Enter the second string

they see

 the eyes and they see are anagrams

 


PROGRAM 5:  SORTING THE MARK STATEMENT

PROBLEM:

Write a program to sort each list of student's marks and sort the whole mark list is ascending order. Use tuple( ) to sort each student's marks.

 Input format : The first line of input is the the number of students (n) . Second line consist of number of subject (m). Next line will be n*m subject marks.

 Output format : List of the subject marks in sorted order of individual student marks. List  in sorted order of  the  marks of n student .

 

AIM  :

    To write a program to sort each list of students   marks and sort the whole mark list in ascending order. Use tuple ()  to store each student marks.

 

ALGORITHM :

STEP 1 : Start the process

STEP 2 : Define the variable n,m

STEP 3 : Create the empty list l, s1

STEP 4 : Use for loop to print  n & m

STEP 5 : Get the values number of students & number of subjects

STEP 6 : Print the values

STEP 7 : Stop the process.

 

PROGRAM :

 

def std(n,m):

    l=[]

    sl=[]

    for i in range(n):

        l=[]

        for j in range(m):

            l=l+list(map(int,input().split('\n')))

        sl.append(tuple(sorted(l)))

        slres=sorted(sl)

    return slres

n=int(input("Enter the number of students: "))

m=int(input("Enter the number of subjects: "))

res=std(n,m)

print("Marks of the subject are stored in tuples: ")

print(res)

 

 

OUTPUT :

 

Enter the number of students: 3

Enter the number of subjects: 3

56

76

98

76

67

84

99

76

76

Marks of the subject are stored in tuples:

[(56, 76, 98), (67, 76, 84), (76, 76, 99)]

 


PROGRAM 6:  SYMMETRIC DIFFERENCE

PROBLEM:

Write a program to find symmetric difference between two sets.

              The symmetric difference of two sets A and B is the set of elements that are in either of the sets A or B but not in both.

AIM:

           To  Write a program to find symmetric difference between two sets.

             The symmetric difference of two sets A and B is the set of elements that are in either of the sets A or B but not in both.

 

ALGORITHM

Step1:  Start the process

Step2:  This program is  used to find out the symmetric difference between two sets

Step3:   Create a set of elements by using the map() function

Step4:   Get the two input list from users.

Step5:    If the condition is unequal then the output is invalid Else print the symmetric difference between two sets

Step6:    Stop the Process.                

 

PROGRAM:

set1=set(map(int,input(“Enter first set elements separated by comma:”).split(‘,’)))                              

set2=set(map(int,input(“Enter second set elements  separated by  comma:”).split(‘,’)))

if set1==set2:

       print(“Invalid set”)

else:

       print(“Symmetric difference between two sets = :”,set1^set2)

OUTPUT:

Enter first set element separated by comma: 1,2,4,6

Enter second set elements separated by comma: 3,4,5,6,7,8

Symmetric difference between two sets: {1,2,3,5,7,8}


 

PROGRAM 7:  PRINTING MOBILE APPS DETAILS

PROBLEM:

Write a python program to collect the required attributes from the user about apps installed in their mobile. Use class object and print the data in neat format

 Aim :

To create a python program to collect the required attributes from the user about apps installed in their mobile. Use class object and print the data in neat format

 Algorithm:

Step 1 : start the process.

 Step 2 : This program is used to collect  the required attributes from the user installed in their mobile.

 Step 3 : Use the self function to access the attributes and method of the class.

 Step 4 : Return the character from an integer by using ch1.

 Step 5 : Giving the two values using the flag variables and it toggles the result . In flag function we access the values as zero,it indicates false.

 Step 6 : If flag value is one it indicates true, elif character is zero then print the output such as app is not installed.

 Step 7 : Append function is used to add the items to the existing list such as L2.

 Step 8 : If the character is greater than zero then starts the for loop it creates a new collection as with range() immediately for the for.loop to act upon.

 Step 9 : List the values by using for loop j

 Step 10 : End the process.

PROGRAM:

 class Apps:

    def __init__(self,aid,aname,lat,pcp,dc,asz):

        self.appId=aid

        self.appName=aname

        self.lastAccessTime=lat

        self.powerConsumptionPercent=pcp

        self.dataConsumption=dc

        self.appSize=asz

ch1=input("Enter the number of apps installed in your mobile:").strip(' ')

l2=[]

flag=0

ch=int(ch1)

if ch>0:

    for i in range(0,ch):

        print("\nEnter the App %d details "%(i+1))

        aid=int(input("Enter the app id:(int) \n").strip(' '))

        aname=input("Enter the app name : (str) \n").strip(' ')

        lat=input("Enter the last access time of app in 24 hour(HH:MM:SS)format(str) \n").strip(' ')

        pcp=int(input("Enter the power consumption percent of application : (int) \n").strip(' '))

        dc=float(input("Enter the the data consumption  of application in MB:(float)  \n").strip(' '))

        asz=float(input("Enter the app size in MB(float)").strip(' '))

        p1=Apps(aid,aname,lat,pcp,dc,asz)

        l2.append(p1)

        flag=1

elif ch==0 or ch=='o':

   print("\nNo  app installed")

if(flag==1):

    print("\n%-15s %-15s %-15s %-15s %-15s %-15s"%("AppId","AppName","LastAccessTime","PowerConsumption(%)","DataConsumption","AppSize"))

    for j in l2:

        print("%-15s %-15s %-15s %-15s %-15s %-15s"%(str(j.appId),str(j.appName)

 

OUTPUT:

Enter the number of apps installed in your mobile:2

 Enter the App 1 details

Enter the app id:(int)

101

Enter the app name : (str)

whatsapp

Enter the last access time of app in 24 hour(HH:MM:SS)format(str)

12:03:11

Enter the power consumption percent of application : (int)

40

Enter the the data consumption  of application in MB:(float) 

35.6

Enter the app size in MB(float)32.4

 Enter the App 2 details

Enter the app id:(int)

10004

Enter the app name : (str)

instagram

Enter the last access time of app in 24 hour(HH:MM:SS)format(str)

04:12:17

Enter the power consumption percent of application : (int)

30

Enter the the data consumption  of application in MB:(float) 

35.2

Enter the app size in MB(float)40.1

 

 AppId           AppName         LastAccessTime  PowerConsumption(%) DataConsumption AppSize       

101               whatsapp         12:03:11                       40                                35.6                   32.4          

10004           instagram         04:12:17                       30                                35.2                    40.1          

 


PROGRAM  8: ARRAY

PROBLEM:

Write a program to slice an Array, assign the value 60 to all values in the sliced array and display the array.         

 Aim :

To write a program to slice an Array, assign the value 60 to all values in the sliced array and display the array

 Algorithm:

Step 1 : Start the process.

Step 2: Import numpy

Step3: Create Two Dimentional Array and print an array

Step 4:  Create One Dimentional array using arange  function and print an array

Step 5:. Slicing  an array and assign 60 to the sliced array

Step 6: Print the sliced array

Step 7: Print the sliced array

Step 8: End the process

  PROGRAM:

 import numpy as np

print("Two Dimentional Array")

arr=np.array([[1,2,3],[4,5,6]])

print(arr)

print("One Dimentional Array")

arr1=np.arange(10)

print(arr1)

print("Slicing an Array")

arr1_slice = arr1[5:8]

print(arr1_slice)

print("Assign 60 to the Sliced Array")

arr1[5:8]=60

print(arr1_slice)

 

OUTPUT:

 Two Dimentional Array

 [[1 2 3]

 [4 5 6]]

One Dimentional Array

[0 1 2 3 4 5 6 7 8 9]

Slicing an Array

[5 6 7]

Assign 60 to the Sliced Array

[60 60 60]

 

 PROGRAM  9: DOT  PRODUCT AND TRANSPOSE OF THE MATRIX

PROBLEM:

 Write a program to compute the dot product of Matrix X with its  transpose X.T

 Aim :

To write a program to compute the dot product of Matrix X with its  transpose X.T

 Algorithm:

Step 1 : Start the process.

Step 2: Import numpy

Step 3: Create Two Dimentional Array and print an array

Step 4: Find the transpose of the matrix (X.T)

Step 5: Compute  the dot product of Matrix X with its  transpose X.T

Step 6: Print the result

Step7: End the process

 PROGRAM:

import numpy as np

arr = np.random.randn(6, 3)

print("ARRAY")

print(arr)

arr_t=arr.T

print("TRANSPOSE OF AN ARRAY")

print(arr_t)

print("DOT PRODUCT OF MATRIX X WITH ITS TRANSPOSE X.T")

arr1=np.dot(arr.T,arr)

print(arr1)

 

OUTPUT:

 

ARRAY

[[ 0.33990025  0.49659955 -0.81006085]

 [ 0.45005282  2.03727583  1.41131844]

 [-0.57288364  0.83679545 -1.26986388]

 [ 0.05691252  1.75241469  1.22832815]

 [ 0.25091295 -1.0072836  -1.09662999]

 [-0.31806362 -0.22297319  1.09820424]]

TRANSPOSE OF AN ARRAY

[[ 0.33990025  0.45005282 -0.57288364  0.05691252  0.25091295 -0.31806362]

 [ 0.49659955  2.03727583  0.83679545  1.75241469 -1.0072836  -0.22297319]

 [-0.81006085  1.41131844 -1.26986388  1.22832815 -1.09662999  1.09820424]]

DOT PRODUCT OF MATRIX X WITH ITS TRANSPOSE X.T

[[0.81363619 0.52420311 0.53276197]

 [0.52420311 9.23262508 4.42264037]

 [0.53276197 4.42264037 8.17801251]]

  

PROGRAM  10:  BAR CHART WITH COLOR

PROBLEM:

 Write a Python program to display a bar chart of the popularity of programming Languages. Use different color for each bar.

Aim :

To write a Python program to display a bar chart of the popularity of programming Languages. Use different color for each bar.

  Algorithm:

STEP 1: Start the process.

STEP 2: Import matplotlib to display bar chart

STEP 3 : Create the following lists (i) programming language (Ii)  popularity and  (iii) bar colour.

STEP 4 : Using plt.bar() method to create a bar chart.

STEP 5 : Using plt.title(),pltxlabel() & plt.ylabel() methods print the title and labels for the chart

STEP 6 : plt.show() method is used to display the bar chart.

PROGRAM:

import matplotlib.pyplot as plt

labels=["C Prog","C++ Prog","Java","Python","C#"]

c = ['red', 'yellow', 'green', 'blue', 'orange']

popularity=[75,80,85,97,60]

y_positions=range(len(labels))

plt.bar(y_positions,popularity,color=c)

plt.xticks(y_positions,labels)

plt.ylabel("Popularity")

plt.xlabel("Programming Languages")

plt.title("Popularity of Programming Languages")

plt.show()

 OUTPUT:

 


PROGRAM  11: PIE CHART

PROBLEM:

Write a Python program to draw pie chart to compile the work done during a day into categories, say sleeping, eating, working and playing.

Aim :

To write a Python program to draw pie chart to compile the work done during a day into categories, say sleeping, eating, working and playing.

 

ALGORITHM:

STEP 1: Start the process.

STEP 2: Import matplotlib to display pie chart

STEP 3 : Create the following lists (i) activity , (ii) duration and (iii) colour.

STEP 4 : Using plt.pie() method to create a pie chart.

STEP 5 : Using plt.title() method print the title for the pie chart

STEP 6 : plt.show() method is used to display the pie char 


PROGRAM

import matplotlib.pyplot as plt

activity=["Sleeping","Eating","Working","Playing"]

c = ['red', 'yellow', 'blue', 'orange']

duration=[100,30,140,80]

plt.pie(duration,labels=activity,autopct="%0.1f%%")

plt.title("Work done during a day")

plt.show()


OUTPUT



PROGRAM  12: LINE GRAPH

PROBLEM:

Write a Python Program to draw Line graph for year Vs Population of India.

Aim :

To write a Python Program to draw Line graph for year Vs Population of India.

ALGORITHM

STEP 1: Start the process.

STEP 2: Import matplotlib to display line graph

STEP 3 : Create the following lists (i) years  and  (ii) population

STEP 4 : Using plt.plot() method to create a line graph.

STEP 5 : Using plt.grid() create grid lines for the graph .

STEP 6 : Using plt.title(),pltxlabel() & plt.ylabel() methods print the title and labels for the line graph.

STEP 7 : plt.show() method is used to display the  line graph.

 

PROGRAM

import matplotlib.pyplot as plt

years=[2017,2018,2019,2020,2021]

population=[9939007,9954518,9960387,9956741,9943721]

plt.plot(years,population,marker='o')

plt.grid()

plt.title("YEAR vs POPULATION OF INDIA")

plt.xlabel("YEAR")

plt.ylabel("Total Population")

plt.show()

 

OUTPUT




 

Popular posts from this blog