Python Lab Manual Saranya_modified
Python Lab Manual Saranya_modified
(Regulation - 2021)
PROGRAMME : UG
SEMESTER : I
BY,
Mrs.E.SATHIANARAYANI M.E.,
Mrs.T.SARANYA M.E.,
Ms.R.KOWSALYA M.E.,
Mrs.K.SARIKA M.E.,
(Assistant Professors/CSE)
Aim:
Algorithm:
1. start
2. Declare variables unit and usage.
3. Process the following,
4. When the unit is less than or equal to 100 units,calculate usage=unit*5
5. When the unit is between 100 to 200 units.calculate usage=(100*5)+((unit-100)*7)
6. When the unit is between 200 to 300 units,calculate usage=(100*5)+(100*7)+((unit-
200*10)
7. When the unit is above 300 unit,calculate usage=(100*5)+(100*7)+(100*10)=((unit-
300)*15)
8. For further,no additional change will be calculated
9. Display the amount”usage”to the user.
10. Stop.
Result:
Thus the Flow chart for electricity billing was developed successfully.
EXNO1B) Identification and solving of simple real life or scientific or Technical problems
and developing flow chart for Retail Shop Billing.
Aim:
Algorithm:
1. start
2. Declare the variable unit and usage.
3. Process Assign the values for a1,a2 and a3,a1=15,a2=120,a3=85.
4. Process the following amount=(item 1*a1)+(item 2*a2)+(item 3*a3)>
5. Display the values of “amount”.
6. Stop
RESULT:
Thus the flow chart for Retail Shop Billing was developed successfully.
EXNO1C) Identification and solving of simple real life or scientific or Technical problems
and developing flow chart for Sin Series.
Aim:
ALGORITHM:
1. Start
2. Declare the variables which are required to process.
3. Read the input like the value of x in radians and n where n is a number up to which want
to print the sun of series.
4. For first item,
Sum=x;
Power=1
Num=num *(-*2);
Power=Power+2;
Result:
Thus the flow chart for Sin Series was developed successfully.
EXNO1D) Identification and solving of simple real life or scientific or technical problems
and developing flow charts for weight of a Motorbike
AIM:
Alogorithom:
1. start
2. Declare variables weight motar,pr ,eoff and weight
3. Read the values of weightmotar,pr and eoff.
6. Stop
Result:
AIM:
Algorithm:
1. start
2. declare the variables d, length and weight.
3. weight=(d2/162)*length
4. Read the value d and length.
5. Display the value of weight
6. stop
Result:
Thus the flowchart for weight of a steel bar was developed successfully.
EXNO1F) Identification and solving of simple real life or scientific or technical problems
and developing flow charts for weight of a compute electrical current in three –phase AC
circuit
AIM:
Algorithm:
1. start
2. Declare variables pf,I ,v and p.
3. Read the values of pf I and v.
4. p=v3*pf*I*v
5. Display “The result is p”.
6. stop
Result:
Thus the Flowchart for compute electrical current in three-phase AC circuit was
developed successfully.
EX:NO:2A) PYTHON PROGRAMMING USING SIMPLE STATEMENTS AND
EXPRESSIONS (Exchange two variables)
AIM:
To write a python program for distance between two points using conditional and
iterative loops.
ALGORITHM:
1. Get X and Y from console using input() function
2. Assign temp =x
3. Copy the value from y to x by x=y
4. Copy the value from temp to y by y=temp
5. Print the values
PROGRAM/SOURCE CODE:
x = input('Enter value of x: ')
y = input('Enter value of y: ')
temp = x
x=y
y = temp
print('The value of x after swapping: {}'.format(x))
print('The value of y after swapping: {}'.format(y))
OUTPUT:
Enter value of x: 10
Enter value of y: 5
The value of x after swapping: 5
The value of y after swapping: 10
RESULT:
Thus the python program for distance between two points was written and executed
successfully.
EX:NO:2B) PYTHON PROGRAMMING USING SIMPLE STATEMENTS AND
EXPRESSIONS (Distance Between Two Points)
AIM:
To write a python program for distance between two points using conditional and
iterative loops.
ALGORITHM:
1. Get x1 from console using input() function
2. Get x2
3. Get y1
4. Get y2
5. Calculate result using ((((x2 - x1 )**2) + ((y2-y1)**2) )**0.5)
6. Print the result inside print() function
PROGRAM/SOURCE CODE:
x1=int(input("enter x1 : "))
x2=int(input("enter x2 : "))
y1=int(input("enter y1 : "))
y2=int(input("enter y2 : "))
result= ((((x2 - x1 )**2) + ((y2-y1)**2) )**0.5)
print("distance between",(x1,x2),"and",(y1,y2),"is : ",result)
OUTPUT:
enter x1 : 4
enter x2 : 0
enter y1 : 6
enter y2 : 6
distance between (4, 0) and (6, 6) is : 4.0
RESULT:
Thus the python program for distance between two points was written and executed
successfully.
EX:NO:2C) PYTHON PROGRAMMING USING SIMPLE STATEMENTS AND
EXPRESSIONS (Circulate the values of n variables)
AIM:
To write a python program for distance between two points using conditional and
iterative loops.
ALGORITHM:
1. Start.
2. Initialize list as 1,2,3,4,5.
3. Deque the element from list and stored in d.
4. Rotate the first three values in d.
5. Print d.
6. Stop.
PROGRAM/SOURCE CODE:
no_of_terms = int(input("Enter number of values : "))
#Read values
list1 = []
for val in range(0,no_of_terms,1):
ele = int(input("Enter integer : "))
list1.append(ele)
print("Circulating the elements of list ", list1)
for val in range(0,no_of_terms,1):
ele = list1.pop(0)
list1.append(ele)
print(list1)
OUTPUT:
Enter number of values : 3
Enter integer : 10
Enter integer : 20
Enter integer : 30
Circulating the elements of list [10, 20, 30]
[20, 30, 10]
[30, 10, 20]
[10, 20, 30]
RESULT:
Thus the program for circulating n variables was written and executed successfully.
EX:NO:3A) Scientific Problems Using Conditional And Iterative Loops
(Pyramid Number Pattern)
AIM:
To write a python program for pyramid number pattern using conditional and iterative
loops.
ALGORITHM:
1. Start
2. Initialize n=5
3. For i in range upto n
4. In another loop upto n-i-1
5. Inside print leave spaces
6. For k in range upto 2*i+1
7. Print the k+1 and space
PROGRAM/SOURCE CODE:
n=5
for i in range(n):
for j in range(n-i-1):
print(' ',end=' ')
for k in range(2*i+1):
print(k+1,end=' ')
print()
OUTPUT:
1
123
12345
1234567
123456789
RESULT:
Thus the program for pyramid number pattern using conditional and iterative loops was
written and executed successfully.
EX:NO:3B) Scientific Problems Using Conditional And Iterative Loops
(Simple Number Pattern)
AIM:
To write a python program for simple number pattern using conditional and iterative
loops.
ALGORITHM:
1. Start
2. define the function name as pattern with the parameter n.
3. a) Initialize x with 0.
b) for i in range 0 to n.
c) x increased by 1.
d) for j in range 0 to i+1.
e) print(x,and=' ')
f) print(“\n)
4. call the parameter of the function pattern with parameter 5.
5. stop.
PROGRAM/SOURCE CODE:
def pattern(n):
x=0
for i in range(0,n):
x+=1
for j in range(0,i+1):
print(x,end=" ")
print("\r")
pattern(5)
OUTPUT:
1
22
333
4444
55555
RESULT:
Thus the program for simple number pattern using conditional and iterative loops was
written and executed successfully.
EX:NO:3C) Scientific Problems Using Conditional And Iterative Loops
(Number Series)
AIM:
To write a python program for number series using conditional and iterative loops.
ALGORITHM:
1. Start
2. input the value of n.
3. for i in range 0 to n.
a) for j in range 0 to i.
b) square the sum I and j anf stored in m.
c) square.append(m).
4. print(square).
PROGRAM/SOURCE CODE:
square=[]
n=int(input("Enter the value:"))
for i in range(0,n):
for j in range(0,i):
m=(i+j)**2
square.append(m)
print(square)
OUTPUT:
Enter the value:7
[1, 4, 9, 9, 16, 25, 16, 25, 36, 49, 25, 36, 49, 64, 81, 36, 49, 64, 81, 100, 121]
RESULT:
Thus the program for number series using conditional and iterative loops was written and
executed successfully.
EX:NO:4A) Implementing Real Time Application Using List
(Components Of A Car)
AIM:
To write a python program for items present in components of a car using list
ALGORITHM:
1. Define a list with components present in car
2. Nesting of list inside list
3. Use slice function in various ways
4. Using length function to identify length of the lists
5. Printing items present in a car using for loop
6. Append the values in the list
7. Inserting elements in the given index using insert function
8. Remove the given element from list using remove
9. Pop the element from the list 10.
10. Delete the list.
11. Sorting the list using sort function.
Program/Source Code:
comp_cars=['Engine','Transmission','Alternator','Radiator','FrontAxle','FrontStreeringAndSuspen
sion','Brakes','CatalyticConverter','Muffler','TailPipe','FuelTank','RearAxle','RearSuspension','Fro
ntAxle']
print(comp_cars)
comp_cars1 =
list(('Engine','Transmission','Alternator','Radiator','FrontAxle','FrontStreeringAndSuspension','Br
akes','CatalyticConverter','Muffler','TailPipe','FuelTank','RearAxle','RearSuspension','FrontAxle')
)
List = [['Engine', 'Brake'] , ['Clutch’]]
print(List)
SList = comp_cars[:-6]
print(SList)
Sliced_List = comp_cars[3:8]
print(Sliced_List)
SList = comp_cars[5:]
print(SList)
SList = comp_cars[:]
print(SList)
Sliced_List = comp_cars[::-1]
print(Sliced_List)
print(comp_cars1)
print(comp_cars[0])
print(comp_cars.index('Transmission'))
print(len(comp_cars))
for item incomp_cars:
print(item)
comp_cars[1]='Eng'
print(comp_cars)
comp_cars.append('BMW')
print(comp_cars)
comp_cars.insert(2,'Mercedes-Benz')
print(comp_cars)
comp_cars.remove('BMW')
print(comp_cars)
comp_cars.pop(1)
print(comp_cars)
delcomp_cars[1]
print(comp_cars)
carsNew=comp_cars.copy()
print(carsNew)
carsNewUpdated= list(comp_cars)
print(carsNewUpdated)
comp_cars.sort()
print("After sorting: ",comp_cars)
comp_cars.sort(reverse=True)
print("After sorting in descending order: ",comp_cars)
comp_cars.reverse()
print('Reversed list: ',comp_cars)
OUTPUT:
['Engine', 'Transmission', 'Alternator', ['Engine', 'Transmission', 'Alternator',
'Radiator', 'FrontAxle', 'Radiator', 'FrontAxle',
'FrontStreeringAndSuspension', 'Brakes', 'FrontStreeringAndSuspension', 'Brakes',
'CatalyticConverter', 'Muffler', 'CatalyticConverter']
'TailPipe', 'FuelTank', 'RearAxle', ['Radiator', 'FrontAxle',
'RearSuspension', 'FrontAxle'] 'FrontStreeringAndSuspension', 'Brakes',
[['Engine', 'Brake'], ['Clutch']] 'CatalyticConverter']
['FrontStreeringAndSuspension', 'Brakes', Brakes
'CatalyticConverter', 'Muffler', 'TailPipe', CatalyticConverter
'FuelTank', 'RearAxle', 'RearSuspension', Muffler
'FrontAxle'] TailPipe
['Engine', 'Transmission', 'Alternator', FuelTank
'Radiator', 'FrontAxle', RearAxle
'FrontStreeringAndSuspension', 'Brakes', RearSuspension
'CatalyticConverter', 'Muffler', 'TailPipe', FrontAxle
'FuelTank', 'RearAxle', 'RearSuspension', ['Engine', 'Eng', 'Alternator', 'Radiator',
'FrontAxle'] 'FrontAxle', 'FrontStreeringAndSuspension',
['FrontAxle', 'RearSuspension', 'RearAxle', 'Brakes', 'CatalyticConverter', 'Muffler',
'FuelTank', 'TailPipe', 'Muffler', 'TailPipe', 'FuelTank', 'RearAxle',
'CatalyticConverter', 'Brakes', 'RearSuspension', 'FrontAxle']
'FrontStreeringAndSuspension', 'FrontAxle', ['Engine', 'Eng', 'Alternator', 'Radiator',
'Radiator', 'Alternator', 'Transmission', 'FrontAxle', 'FrontStreeringAndSuspension',
'Engine'] 'Brakes', 'CatalyticConverter', 'Muffler',
['Engine', 'Transmission', 'Alternator', 'TailPipe', 'FuelTank', 'RearAxle',
'Radiator', 'FrontAxle', 'RearSuspension', 'FrontAxle', 'BMW']
'FrontStreeringAndSuspension', 'Brakes', ['Engine', 'Eng', 'Mercedes-Benz',
'CatalyticConverter', 'Muffler', 'TailPipe', 'Alternator', 'Radiator', 'FrontAxle',
'FuelTank', 'RearAxle', 'RearSuspension', 'FrontStreeringAndSuspension', 'Brakes',
'FrontAxle'] 'CatalyticConverter', 'Muffler', 'TailPipe',
Engine 'FuelTank', 'RearAxle', 'RearSuspension',
1 'FrontAxle', 'BMW']
14 ['Engine', 'Eng', 'Mercedes-Benz',
Engine 'Alternator', 'Radiator', 'FrontAxle',
Transmission 'FrontStreeringAndSuspension', 'Brakes',
Alternator 'CatalyticConverter', 'Muffler', 'TailPipe',
Radiator 'FuelTank', 'RearAxle', 'RearSuspension',
FrontAxle 'FrontAxle']
FrontStreeringAndSuspension
['Engine', 'Mercedes-Benz', 'Alternator', 'FuelTank', 'Muffler', 'Radiator', 'RearAxle',
'Radiator', 'FrontAxle', 'RearSuspension', 'TailPipe']
'FrontStreeringAndSuspension', 'Brakes', After sorting in descending order:
'CatalyticConverter', 'Muffler', 'TailPipe', ['TailPipe', 'RearSuspension', 'RearAxle',
'FuelTank', 'RearAxle', 'RearSuspension', 'Radiator', 'Muffler', 'FuelTank',
'FrontAxle'] 'FrontStreeringAndSuspension', 'FrontAxle',
['Engine', 'Alternator', 'Radiator', 'FrontAxle', 'Engine', 'CatalyticConverter',
'FrontAxle', 'FrontStreeringAndSuspension', 'Brakes', 'Alternator']
'Brakes', 'CatalyticConverter', 'Muffler', Reversed list: ['Alternator', 'Brakes',
'TailPipe', 'FuelTank', 'RearAxle', 'CatalyticConverter', 'Engine', 'FrontAxle',
'RearSuspension', 'FrontAxle'] 'FrontAxle', 'FrontStreeringAndSuspension',
['Engine', 'Alternator', 'Radiator', 'FuelTank', 'Muffler', 'Radiator', 'RearAxle',
'FrontAxle', 'FrontStreeringAndSuspension', 'RearSuspension', 'TailPipe']
'Brakes', 'CatalyticConverter', 'Muffler',
'TailPipe', 'FuelTank', 'RearAxle',
'RearSuspension', 'FrontAxle']
['Engine', 'Alternator', 'Radiator',
'FrontAxle', 'FrontStreeringAndSuspension',
'Brakes', 'CatalyticConverter', 'Muffler',
'TailPipe', 'FuelTank', 'RearAxle',
'RearSuspension', 'FrontAxle']
After sorting: ['Alternator', 'Brakes',
'CatalyticConverter', 'Engine', 'FrontAxle',
'FrontAxle', 'FrontStreeringAndSuspension',
RESULT:
Thus the python program for components of a car using list was successfully executed.
EX:NO:4B) Implementing Real Time Application Using Tuples
(Components Of a Car)
AIM:
To write a python program for components of a car using tuples
ALGORITHM:
1. Define Tuples using tuple function or using ()
2. Accessing tuple elements using its index position
3. Getting length of a tuple using len function
4. Printing items present in tuples using for loop
5. Count the no of times item present in a list using count function
6. Append the element in list using append function
7. Delete the tuple using del function
PROGRAM/SOURCE CODE:
comp_cars=('Engine','Transmission','Alternator','Radiator','FrontAxle','FrontStreeringAndSuspen
sion','Brakes','CatalyticConverter','Muffler','TailPipe','FuelTank','RearAxle','RearSuspension','Fro
ntAxle')
print('Component of cars is: ',comp_cars)
comp_cars1 =
tuple(('Engine','Transmission','Alternator','Radiator','FrontAxle','FrontStreeringAndSuspension','
Brakes','CatalyticConverter','Muffler','TailPipe','FuelTank','RearAxle','RearSuspension','FrontAxl
e'))
print(''Component of cars is: ', comp_cars1)
print('Item in the first position is: ',comp_cars[0])
indexOfTransmission=comp_cars.index('Transmission')
print('Index of Transmission is: ',indexOfTransmission)
lengthCars=len(comp_cars)
print('Length of the component of car is: ',lengthCars)
for item incomp_cars:
print(item)
if "Engine"in comp_cars:
print("Engine is available in the Cars tuple")
else:
print("Engine is not available in the Cars tuple")
numTime=comp_cars.count('Engine')
print('Number of times Engine available in the tuple is: ',numTime)
comp_cars.append('BMW')
print(comp_cars)
del comp_cars1
print(comp_cars1)
OUTPUT:
Component of cars is: ('Engine', Transmission
'Transmission', 'Alternator', 'Radiator', Alternator
'FrontAxle', Radiator
'FrontStreeringAndSuspension', 'Brakes', FrontAxle
'CatalyticConverter', 'Muffler', FrontStreeringAndSuspension
'TailPipe', 'FuelTank', 'RearAxle', Brakes
'RearSuspension', 'FrontAxle') CatalyticConverter
Component of cars is: ('Engine', Muffler
'Transmission', 'Alternator', 'Radiator', TailPipe
'FrontAxle', 'FrontStreeringAndSuspension', FuelTank
'Brakes', 'CatalyticConverter', 'Muffler', RearAxle
'TailPipe', 'FuelTank', 'RearAxle', RearSuspension
'RearSuspension', 'FrontAxle') FrontAxle
Item in the first position is: Engine Engine is available in the Cars tuple
Index of Transmission is: 1 Number of times Engine available in the
Length of the component of car is: 14 tuple is: 1
Engine
RESULT:
Thus the program for components of a car using tuples was written and executed
successfully.
EX:NO:5A) Implementing Real Time/Technical Application Using Sets
(Components Of Automobile)
AIM:
To write a python program for languages using sets
ALGORITHM:
1. Define sets using by giving values inside {}
2. Printing values by directly accessing it by its name or using for loop
3. Add the elements using add function
4. Discard elements using its value
5. Perfor union of sets using |
6. Perform intersection using &
7. Perform difference using –
8. Perform comparison using >= or <=
PROGRAM/SOURCE CODE:
Amob = {'The Suspension system', 'Axles', 'Wheels', 'Tyres', 'Power Plant', 'Transmission
System', 'Auxiliaries'}
print('Approach #1= ', Amob)
print('==========')
print('Approach #2')
for Amob in Amob:
print('Component = {}'.format(Amob))
print('==========')
Amob.add('controls')
print('New Automobile set = {}'.format(Amob))
Amob.discard('Axles')
print('discard() method = {}'.format(Amob))
set1 = {'The Suspension system', 'Axles', 'Wheels', 'Tyres'}
set2 = {'The Suspension system', 'Axles', 'Power Plant', 'Transmission System', 'Auxiliaries'
'Power Plant', 'Transmission System', 'Auxiliaries'}
union = set1 | set2
print("Union of sets = {}".format(union))
print('==========')
intersection = set1 & set2
print("Intersection of sets = {}".format(intersection))
print('==========')
# 5(c). Difference of sets
difference = set1 - set2
print("Difference of sets = {}".format(difference))
print('==========')
subset = set1 <= set2
superset = set2 >= set1
print("Subset result = {}".format(subset))
print("Superset result = {}".format(superset))
OUTPUT:
Approach #1= {'Axles', 'The Suspension discard() method = {'The Suspension
system', 'Power Plant', 'Tyres', 'Wheels', system', 'Power Plant', 'controls', 'Tyres',
'Transmission System', 'Auxiliaries'} 'Wheels', 'Transmission System',
========== 'Auxiliaries'}
Approach #2 Union of sets = {'Axles', 'The Suspension
Component = Axles system', 'AuxiliariesPower Plant', 'Power
Component = The Suspension system Plant', 'Tyres', 'Wheels', 'Transmission
Component = Power Plant System', 'Auxiliaries'}
Component = Tyres ==========
Component = Wheels Intersection of sets = {'Axles', 'The
Component = Transmission System Suspension system'}
Component = Auxiliaries ==========
========== Difference of sets = {'Tyres', 'Wheels'}
New Automobile set = {'Axles', 'The ==========
Suspension system', 'Power Plant', 'controls', Subset result = False
'Tyres', 'Wheels', 'Transmission System', Superset result = False
'Auxiliaries'}
RESULT:
Thus the python program for components of automobiles using sets was written and
executed successfully.
ALGORITHM:
1. Define dictionaries by giving key and value pairs
2. Copy elements from one dictionary to another using copy command
3. Update values using update function
4. Access elements from dictionary using items() function
5. Getting length of dictionary from len function
6. Accessing data type of element using type() function
7. Delete element by using pop function
8. Remove all elements using clear() function
9. Creating dictionary by using dict() and zip() function
10. Creating dictionary element with squares using squares = {x: x*x for x in range(5)}
11. Getting element using get() function.
PROGRAM/SOURCE CODE:
Amob = {'Component#1':'Axles','Component#2':'Wheels',
'Component#3':'Tyres','Component#4':'Transmission
System','Component#5':'Auxiliaries','Component#6':'Power Plant' }
Vehicles = Amob.copy()
print("All Components in Automobile : ", Vehicles)
Amob.update({'Componen#7' : 'The Suspension system'})
print("All Components in Automobile : ", Amob)
print("!------------------------------------------------!")
Amob.update( {'Component#4' : 'Transmission_System'})
print("All Components in Automobile : ", Amob)
print('All Components in Automobile :',Amob.items())
print('Total components in the Automobile',len(Amob))
print(' Amobdatatype format ',type(Amob))
Amob_str = str(Amob)
print(' Automobile datatype format ',type(Amob_str))
Amob1 = {1:'Axles',2:'Wheels', 3:'Tyres',4:'Transmission System',5:'Auxiliaries',6:'Power
Plant' }
print( " ITEM DELETION ")
print(Amob1.pop(3))
print(" ")
print(" Dictionary after deletion " )
print(Amob1)
print(" ")
print(Amob1.popitem())
print(" ")
print(" Dictionary after deletion " )
print(Amob1)
print(" ")
print(" Dictionary after removing all items " )
Amob1.clear()
print(Amob1)
dict_tuples = dict([("Axles",1), ("Wheels",2), ("Tyres",3)])
dict_tuples
dict_keys = ["Axles", "Wheels", "Tyres"]
dict_values = [1, 2, 3]
dict_zipped = dict(zip(dict_keys, dict_values))
dict_zipped
squares = {x: x*x for x in range(5)}
squares
integers = [1, 2, 3, 4, 5]
odds_squares = {x: x*x for x in integers if x%2 == 1}
odds_squares
Amob["Component#1"]
Amob_id = Amob.get("Component#2", -1)
Amob_id
for item in Amob:
print(item)
for item in Amob.values():
print(item)
for key, value in Amob.items():
print(f"Key: {key}; Value: {value}")
OUTPUT:
All Components in Automobile : 'Component#6': 'Power Plant',
{'Component#1': 'Axles', 'Component#2': 'Componen#7': 'The Suspension system'}
'Wheels', 'Component#3': 'Tyres', All Components in
'Component#4': 'Transmission System', Automobile :dict_items([('Component#1',
'Component#5': 'Auxiliaries', 'Axles'), ('Component#2', 'Wheels'),
'Component#6': 'Power Plant'} ('Component#3', 'Tyres'), ('Component#4',
All Components in Automobile : 'Transmission_System'), ('Component#5',
{'Component#1': 'Axles', 'Component#2': 'Auxiliaries'), ('Component#6', 'Power
'Wheels', 'Component#3': 'Tyres', Plant'), ('Componen#7', 'The Suspension
'Component#4': 'Transmission System', system')])
'Component#5': 'Auxiliaries', Total components in the Automobile 7
'Component#6': 'Power Plant', Amobdatatypeformat <class 'dict'>
'Componen#7': 'The Suspension system'} Automobile datatypeformat <class 'str'>
!------------------------------------------------! ITEM DELETION
All Components in Automobile : Tyres
{'Component#1': 'Axles', 'Component#2': Dictionary after deletion
'Wheels', 'Component#3': 'Tyres', {1: 'Axles', 2: 'Wheels', 4: 'Transmission
'Component#4': 'Transmission_System', System', 5: 'Auxiliaries', 6: 'Power Plant'}
'Component#5': 'Auxiliaries', (6, 'Power Plant')
Dictionary after deletion
{1: 'Axles', 2: 'Wheels', 4: 'Transmission Transmission_System
System', 5: 'Auxiliaries'} Auxiliaries
Dictionary after removing all items Power Plant
{} The Suspension system
Component#1 Key: Component#1; Value: Axles
Component#2 Key: Component#2; Value: Wheels
Component#3 Key: Component#3; Value: Tyres
Component#4 Key: Component#4; Value:
Component#5 Transmission_System
Component#6 Key: Component#5; Value: Auxiliaries
Componen#7 Key: Component#6; Value: Power Plant
Axles Key: Componen#7; Value: The Suspension
system
Wheels
Tyres
RESULT:
Thus the program for components of car using dictionaries was written and executed
successfully.
ALGORITHM:
1. Define sets using by giving values inside {}
2. Printing values by directly accessing it by its name or using for loop
3. Add the elements using add function
4. Discard elements using its value
5. Perform union of sets using |
6. Perform intersection using &
7. Perform difference using –
8. Perform comparison using >= or <=
PROGRAM/SOURCE CODE:
Lang = {'Python', 'R', 'JAVA', 'C', 'CPP'}
# 2. Accessing the values from the set
print('Approach #1= ', Lang)
print('==========')
print('Approach #2')
for item in Lang:
print('Language = {}'.format(item))
print('==========')
Lang.add('JavaScript')
print('New Language set = {}'.format(Lang))
Lang.discard('C')
print('discard() method = {}'.format(Lang))
set1 = {'Python', 'R','CPP','JAVA'}
set2 = {'C', 'CPP', 'JAVA', 'JavaScript'}
union = set1 | set2
print("Union of sets = {}".format(union))
print('==========')
# Intersection operation produces a new set containing only common elements from both the sets
intersection = set1 & set2
print("Intersection of sets = {}".format(intersection))
print('==========')
difference = set1 - set2
print("Difference of sets = {}".format(difference))
print('==========')
subset = set1 <= set2
superset = set2 >= set1
print("Subset result = {}".format(subset))
print("Superset result = {}".format(superset))
OUTPUT:
Approach #1= {'JAVA', 'C', 'CPP', 'R', discard() method = {'JAVA', 'JavaScript',
'Python'} 'CPP', 'R', 'Python'}
========== Union of sets = {'JAVA', 'JavaScript', 'CPP',
Approach #2 'C', 'R', 'Python'}
Language = JAVA ==========
Language = C Intersection of sets = {'CPP', 'JAVA'}
Language = CPP ==========
Language = R Difference of sets = {'R', 'Python'}
Language = Python ==========
========== Subset result = False
New Language set = {'JAVA', 'JavaScript', Superset result = False
'C', 'CPP', 'R', 'Python'}
RESULT:
Thus the python program for language using sets was written and executed successfully.
ALGORITHM:
1. Define dictionaries by giving key and value pairs
2. Copy elements from one dictionary to another using copy command
3. Update values using update function
4. Access elements from dictionary using items() function
5. Getting length of dictionary from len function
6. Accessing datatype of element using type() function
7. Delete element by using pop function
8. Remove all elements using clear() function
9. Creating dictionary by using dict() and zip() function.
10. Creating dictionary element with squares using squares = {x: x*x for x in range(5)}
11. Getting element using get() function
PROGRAM/SOURCE CODE:
Lang = {'Language#1':'Python','Language#2':'R',
'Language#3':'C','Language#4':'CPP','Language#5':'JAVA' }
Lang_new = Lang.copy()
print("All Languages in Computer Programming : ", Lang_new)
Lang.update({'Language#6' : 'Java script'})
print("All Languages : ", Lang)
Lang.update( {'Language#6' : 'Java_Script'})
print("All Languages : ", Lang)
print('All Languages :',Lang.items())
print('Total Languages',len(Lang))
print(' Language datatype format ',type(Lang))
Lang_str = str(Lang)
print(' Language datatype format ',type(Lang_str))
Lang1 = {1:'Python',2:'R', 3:'C',4:'CPP',5:'JAVA',6:'Java Script' }
print( " ITEM DELETION ")
print(Lang1.pop(3))
print(" ")
print(" Dictionary after deletion " )
print(Lang1)
print(" ")
print(Lang1.popitem())
print(" ")
print(" Dictionary after deletion " )
print(Lang1)
print(" ")
print(" Dictionary after removing all items " )
Lang1.clear()
print(Lang1)
dict_tuples = dict([("Python",1), ("R",2), ("C",3)])
dict_tuples
dict_keys = ["Python", "R", "C"]
dict_values = [1, 2, 3]
dict_zipped = dict(zip(dict_keys, dict_values))
dict_zipped
Lang["Language#1"]
Lang_id = Lang.get("Language#2", -1)
Lang_id
for item in Lang:
print(item)
for item in Lang.values():
print(item)
for key, value in Lang.items():
print(f"Key: {key}; Value: {value}")
OUTPUT:
All Languages in Computer Programming : (6, 'Java Script')
{'Language#1': 'Python', 'Language#2': 'R', Dictionary after deletion
'Language#3': 'C', 'Language#4': 'CPP', {1: 'Python', 2: 'R', 4: 'CPP', 5: 'JAVA'}
'Language#5': 'JAVA'}
All Languages : {'Language#1': 'Python', Dictionary after removing all items
'Language#2': 'R', 'Language#3': 'C', {}
'Language#4': 'CPP', 'Language#5': 'JAVA', Language#1
'Language#6': 'Java script'} Language#2
!------------------------------------------------! Language#3
All Languages : {'Language#1': 'Python', Language#4
'Language#2': 'R', 'Language#3': 'C', Language#5
'Language#4': 'CPP', 'Language#5': 'JAVA', Language#6
'Language#6': 'Java_Script'}
Python
All Languages :dict_items([('Language#1',
R
'Python'), ('Language#2', 'R'), ('Language#3',
C
'C'), ('Language#4', 'CPP'), ('Language#5',
CPP
'JAVA'), ('Language#6', 'Java_Script')])
JAVA
Total Languages 6
Java_Script
Language datatypeformat <class 'dict'>
Key: Language#1; Value: Python
Language datatypeformat <class 'str'>
Key: Language#2; Value: R
ITEM DELETION
Key: Language#3; Value: C
C
Key: Language#4; Value: CPP
Dictionary after deletion
Key: Language#5; Value: JAVA
{1: 'Python', 2: 'R', 4: 'CPP', 5: 'JAVA', 6:
Key: Language#6; Value: Java_Script
'Java Script'}
RESULT:
Thus the program for language using dictionary was written and executed successfully.
EX:NO:5E) Implementing Real Time/Technical Application Using Sets
(Elements Of Civil Structure)
AIM:
To write a python program for elements of civil structure using sets
ALGORITHM:
1. Define sets using by giving values inside {}
2. Printing values by directly accessing it by its name or using for loop
3. Add the elements using add function
4. Discard elements using its value
5. Perfor union of sets using |
6. Perform intersection using &
7. Perform difference using –
8. Perform comparison using >= or <=
PROGRAM/SOURCE CODE:
civil = {'Foundation', 'Floors', 'Walls', 'Beams', 'Columns', 'Roof'}
print('Approach #1= ', civil)
print('==========')
print('Approach #2')
for item in civil:
print('Component = {}'.format(item))
print('==========')
civil.add('Stairs')
print('New Civil Structure set = {}'.format(civil))
civil.discard('Walls')
print('discard() method = {}'.format(civil))
set1 = {'Foundation', 'Floors', 'Walls', 'Beams'}
set2 = {'Walls', 'Beams', 'Columns', 'Roof','Walls','Beams'}
union = set1 | set2
print("Union of sets = {}".format(union))
print('==========')
intersection = set1 & set2
print("Intersection of sets = {}".format(intersection))
print('==========')
difference = set1 - set2
print("Difference of sets = {}".format(difference))
print('==========')
subset = set1 <= set2
superset = set2 >= set1
print("Subset result = {}".format(subset))
print("Superset result = {}".format(superset))
OUTPUT:
Approach #1= {'Columns', 'Foundation', discard() method = {'Columns', 'Foundation',
'Floors', 'Roof', 'Beams', 'Walls'} 'Floors', 'Roof', 'Beams', 'Stairs'}
========== Union of sets = {'Columns', 'Foundation',
Approach #2 'Floors', 'Roof', 'Beams', 'Walls'}
Component = Columns ==========
Component = Foundation Intersection of sets = {'Walls', 'Beams'}
Component = Floors ==========
Component = Roof Difference of sets = {'Foundation', 'Floors'}
Component = Beams ==========
Component = Walls Subset result = False
========== Superset result = False
New Civil Structure set = {'Columns',
'Foundation', 'Floors', 'Roof', 'Beams',
'Walls', 'Stairs'}
RESULT:
Thus the program for elements of civil structure using sets was written and executed
successfully.
ALGORITHM:
1. Define dictionaries by giving key and value pairs
2. Copy elements from one dictionary to another using copy command
3. Update values using update function
4. Access elements from dictionary using items() function
5. Getting length of dictionary from len function
6. Accessing datatype of element using type() function
7. Delete element by using pop function
8. Remove all elements using clear() function
9. Creating dictionary by using dict() and zip() function
10. Creating dictionary element with squares using squares = {x: x*x for x in range(5)}
11. Getting element using get() function
PROGRAM/SOURCE CODE:
civil = {'Structure#1':'Foundation','Structure#2':'Floors',
'Structuret#3':'Walls','Structure#4':'Beams','Structure#5':'Columns','Structure#6':'Roofs' }
civil1 = civil.copy()
print("All Elements of civil struture : ", civil1)
civil.update({'Strucutre#7' : 'Stairs'})
print("All Elements of civil struture : ", civil)
print("!------------------------------------------------!")
civil.update( {'Structure#4' : 'Wals'})
print("All Elements of civil struture : ", civil)
print('All Elements of civil struture :',civil.items())
print('Total components in the Civil structure',len(civil))
print(' Civil datatype format ',type(civil))
civil_str = str(civil)
print(' Civil datatype format ',type(civil_str))
civil2 = {1:'Foundation',2:'Floors', 3:'Walls',4:'Beams',5:'Columns',6:'Roofs' }
print( " ITEM DELETION ")
print(civil2.pop(3))
print(" ")
print(" Dictionary after deletion " )
print(civil2)
print(" ")
print(civil2.popitem())
print(" ")
print(" Dictionary after deletion " )
print(civil2)
print(" ")
print(" Dictionary after removing all items " )
civil2.clear()
print(civil2)
dict_tuples = dict([("Foundation",1), ("Floors",2), ("Walls",3)])
dict_tuples
dict_keys = ["Foundation", "Floors", "Walls"]
dict_values = [1, 2, 3]
dict_zipped = dict(zip(dict_keys, dict_values))
dict_zipped
squares = {x: x*x for x in range(5)}
squares
integers = [1, 2, 3, 4, 5]
odds_squares = {x: x*x for x in integers if x%2 == 1}
odds_squares
civil["Structure#1"]
civil_id = civil.get("Structure#2", -1)
civil_id
for item in civil:
print(item)
for item in civil.values():
print(item)
for key, value in civil.items():
print(f"Key: {key}; Value: {value}")
OUTPUT:
All Elements of civil struture : ('Structure#6', 'Roofs'), ('Strucutre#7',
{'Structure#1': 'Foundation', 'Structure#2': 'Stairs')])
'Floors', 'Structuret#3': 'Walls', 'Structure#4': Total components in the Civil structure 7
'Beams', 'Structure#5': 'Columns', Civil datatypeformat <class 'dict'>
'Structure#6': 'Roofs'} Civil datatypeformat <class 'str'>
All Elements of civil struture : ITEM DELETION
{'Structure#1': 'Foundation', 'Structure#2': Walls
'Floors', 'Structuret#3': 'Walls', 'Structure#4': Dictionary after deletion
'Beams', 'Structure#5': 'Columns', {1: 'Foundation', 2: 'Floors', 4: 'Beams', 5:
'Structure#6': 'Roofs', 'Strucutre#7': 'Stairs'} 'Columns', 6: 'Roofs'}
!------------------------------------------------! (6, 'Roofs')
All Elements of civil struture : Dictionary after deletion
{'Structure#1': 'Foundation', 'Structure#2': {1: 'Foundation', 2: 'Floors', 4: 'Beams', 5:
'Floors', 'Structuret#3': 'Walls', 'Structure#4': 'Columns'}
'Wals', 'Structure#5': 'Columns', Dictionary after removing all items
'Structure#6': 'Roofs', 'Strucutre#7': 'Stairs'} {}
All Elements of civil Structure#1
struture :dict_items([('Structure#1', Structure#2
'Foundation'), ('Structure#2', 'Floors'), Structuret#3
('Structuret#3', 'Walls'), ('Structure#4', Structure#4
'Wals'), ('Structure#5', 'Columns'), Structure#5
Structure#6
Strucutre#7 Key: Structure#1; Value: Foundation
Foundation Key: Structure#2; Value: Floors
Floors Key: Structuret#3; Value: Walls
Walls Key: Structure#4; Value: Wals
Wals Key: Structure#5; Value: Columns
Columns Key: Structure#6; Value: Roofs
Roofs Key: Strucutre#7; Value: Stairs
Stairs
RESULT:
Thus the program for elements of civil structure using dictionaries was written and
executed successfully.
AIM:
To write a python program to find factorial of a number by using functions.
ALGORITHM:
1. Start the program
2. Define a function to find factorial
3. The function name is recur_factorial(n)
4. Inside the function check for n value
a) If n is equal to 1 return 1 else call the function
b) Get input for finding factorial for a number
c) Check for number if it is negative print some message
d) Else if number is 0 then the factorial for 0 is 1 will be printed
e) Else Call the Function
PROGRAM/SOURCE CODE:
def recur_factorial(n):
if n == 1:
return n
else:
return n*recur_factorial(n-1)
num = int(input("Enter a number: "))
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))
OUPUT:
Enter a number: 5
The factorial of 5 is 120
RESULT:
Thus the program for factorial of number using function was written and executed
successfully
ALGORITHM:
1. Define the function named myMax(list1)
2. Assign the element at 0th position as max
3. Compare the elements in list with max in for loop
4. Return the maximum element
5. Declare and initialize list
6. Call the function inside print statement
PROGRAM/SOURCE CODE:
def myMax(list1):
max = list1[0]
for x in list1:
if x > max :
max = x
return max
list1 = [10, 20, 4, 45, 99]
print("Largest element is:", myMax(list1))
OUTPUT:
Largest element is: 99
RESULT:
Thus the program for largest number using function was written and executed
successfully.
ALGORITHM:
1. Define function named calculate_area(name)
2. Inside function convert all characters into lower case
3. If name is rectangle get length and breadth and calculate area of rectangle using area=l*b
and print the result
4. If name is square get side length and calculate area of square using area=s*s and print the
result
5. If name is triangle get height and breadth length and calculate area of triangle using
area=0.5 * b * h and print the result
6. If name is circle get radius and calculate area of circle using area=pi * r * r and print the
result
7. If name is parallelogram get base and height and calculate area of parallelogram using
area=b * h and print the result
8. Else print “Shape is not available”
PROGRAM/SOURCE CODE:
defcalculate_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(f"The area of rectangle is {rect_area}.")
elif name == "square":
s = int(input("Enter square's side length: "))
sqt_area = s * s
print(f"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(f"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(f"The area of Circlee 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(f"The area of parallelogram is {para_area}.")
else:
print("Sorry! This shape is not available")
if __name__ == "__main__" :
print("Calculate Shape Area")
shape_name = input("Enter the name of shape whose area you want to find: ")
calculate_area(shape_name)
OUTPUT:
Calculate Shape Area
Enter the name of shape whose area you want to find: rectangle
Enter rectangle's length: 56
Enter rectangle's breadth: 70
The area of rectangle is 3920.
RESULT:
Thus the program for area of a shape using function was written and executed
successfully
EXNO 7A) IMPLEMENTING PEOGRMS USING STRINGS (REVERSE OF A STRING)
AIM:
To write a python program for reverse of a string
ALGORITHM:
1. Get the input string from console using input() function
2. Define empty string rstr1
3. Define index as length of string
4. If the index value > 0 then entering into while loop
5. Add every character from index-1 to rstr1
6. Decrement index values by 1
7. Print reversed string
PROGRAM/SOURCE CODE:
str1=input("A string =")
rstr1 = ''
index = len(str1)
while index > 0:
rstr1 += str1[ index - 1 ]
index = index - 1
print("Reverse",rstr1)
OUTPUT:
A string = python
Reverse nohtyp
RESULT:
Thus the program for reverse of a string was written and executed successfully.
ALGORITHM:
1. Get the input string from console using input() function
2. In if statement checks if string is equal to string[::-1] means: Start at the end (the
minus does that for you), end when nothing's left and walk backwards by 1
3. Then print the letter is palindrome
4. Else print the letter is not palindrome
PROGRAM/SOURCE CODE:
string=input(("Enter a letter:"))
if(string==string[::-1]):
print("The letter is a palindrome")
else:
print("The letter is not a palindrome")
OUTPUT:
Enter a letter:madam
The letter is a palindrome
RESULT:
Thus the program for palindrome of a string was written and executed successfully.
ALGORITHM:
1. Get the string from console using input()
2. Initialize total as 0
3. In for loop from staring to length of string
4. Increment total by 1 inside the loop
5. Print the total number of character in string using print() function
PROGRAM/SOURCE CODE:
str1 = input("Please Enter your Own String : ")
total = 0
for i in range(len(str1)):
total = total + 1
print("Total Number of Characters in this String = ", total)
OUTPUT:
Please Enter your Own String : python
Total Number of Characters in this String = 6
RESULT:
Thus the program for character count of a string was written and executed successfully.
ALGORITHM:
1. Get the string from console using input() function
2. Get the character to replace
3. Get the new character to replace in string
4. Replace the characters in string using replace() function
5. Print the original string
6. Print the replaced string
PROGRAM/SOURCE CODE:
str1 = input("Please Enter your Own String : ")
ch = input("Please Enter your Own Character : ")
newch = input("Please Enter the New Character : ")
str2 = str1.replace(ch, newch)
print("\nOriginal String : ", str1)
print("Modified String : ", str2)
OUTPUT:
Please Enter your Own String :asa
Please Enter your Own Character : a
Please Enter the New Character : s
Original String :asa
Modified String :sss
RESULT:
Thus the program for replacing characters in a string was written and executed
successfully.
EXNO 8A) IMPLEMENTING PROGRAM USING WRITTEN MODULES AND
PYTHON STANDARD LIBRARY(PANDAS)
AIM:
To write a python program using pandaslibaray
ALGORITHM:
1. Install the needed library using pip install pandas
2. Import the needed libraries
3. Initialize the list with values
4. Series used to create a one-dimensional data structure which can store different
types of data
5. Create series from dictionaries
6. Printing sliced value
7. Getting index position of element using index() function
8. Print the median of series using median() function
9. Random function used to select random values from series
10. Head function used to get the elements from top of series
11. Tail function used to get the element from bottom of series
PROGRAM/SOURCE CODE:
#To use pandas first we have to import pandas
import pandas as pd
importnumpy as np
A=['a','b','c','d','e']
df=pd.Series(A)
print(df)
data = np.array(['g','o','e','d','u','h','u','b'])
data
ser = pd.Series(data)
print(ser)
s1 = pd.Series(np.random.random(5) , index=['a', 'b', 'c', 'd', 'e'] )
print(s1)
data = {'pi': 3.1415, 'e': 2.71828} # dictionary
print(data)
s3 = pd.Series( data )
print(s3)
s1 = pd.Series(np.random.random(5) )
print(s1)
s1[3] # returns 4th element
s1[:2] #First 2 elements
print( s1[ [2,1,0]])
print(s1.index)
print("Median:" , s1.median())
s1[s1 > s1.median()]
s5 = pd.Series (range(6))
print(s5)
print(s5[:-1])
print(s5[1:])
s5[1:] + s5[:-1]
mys = pd.Series( np.random.randn(5))
print(mys)
print(mys.empty)
print(mys.head(2))
print(mys.tail(2))
print(mys.values)
print(mys.dtype)
OUTPUT:
0 a 1 b
2 c 0 0
3 d 1 1
4 e 2 2
dtype: object 3 3
0 g 4 4
1 o 5 5
2 e dtype: int64
3 d 0 0
4 u 1 1
5 h 2 2
6 u 3 3
7 b 4 4
dtype: object dtype: int64
a 0.060292 1 1
b 0.813180 2 2
c 0.267351 3 3
d 0.827797 4 4
e 0.605398 5 5
dtype: float64 dtype: int64
{'pi': 3.1415, 'e': 2.71828} 0 1.710777
pi 3.14150 1 0.107771
e 2.71828 2 1.194663
dtype: float64 3 0.442142
0 0.386199 4 -1.006500
1 0.546025 dtype: float64
2 0.168450 False
3 0.916291 0 1.710777
4 0.860689 1 0.107771
dtype: float64 dtype: float64
2 0.168450 3 0.442142
1 0.546025 4 -1.006500
0 0.386199 dtype: float64
dtype: float64 [ 1.71077658 0.10777064 1.19466255
RangeIndex(start=0, stop=5, step=1) 0.4421425 -1.00649965]
Median: 0.5460246240927344 float64
RESULT:
Thus the program using modules of pandas was written and executed successfully.
ALGORITHM:
1. Install the needed library using pip install pandas
2. Import the needed libraries
3. Initialize the array with values
4. Accessing array elements using its index position
5. Modify the element directly by using it index position
6. Printing sliced value
7. We can make the same distinction when accessing columns of an array
8. Calculate sum from sum() function
PROGRAM/SOURCE CODE:
import numpy as np
a = np.array([1, 2, 3]) # Create a rank 1 array
print(type(a))
print(a)
print(a[0], a[1], a[2])
a[0]=5
print(a)
b = np.array([[1,2,3],[4,5,6]])
print(b)
print(b.shape)
a = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])
print(a)
#Slicing in array
print(a.shape)
b = a[1:, 2:]
print(b)
row_r1 = a[1, :] # Rank 1 view of the second row of a
row_r2 = a[1:2, :] # Rank 2 view of the second row of a
print(row_r1)
print(row_r1.shape)
print(row_r2)
print(row_r2.shape)
col_r1 = a[:, 1]
col_r2 = a[:, 1:2]
print(col_r1, col_r1.shape)
print(col_r2, col_r2.shape)
a = np.array([[1,2], [3, 4], [5, 6]])
print(a[[0, 1, 2], [0, 1, 0]])
print(np.array([a[0, 0], a[1, 1], a[2, 0]]))
x = np.array([[1,2],[3,4]])
y = np.array([[5,6],[7,8]])
print(x)
print(y)
print(x + y)
x = np.array([[1,2],[3,4],[8,9]])
print(np.sum(x))
print(np.sum(x, axis=0))
print(np.sum(x, axis=1))
print(x.T)
OUTPUT:
<class 'numpy.ndarray'> [1 2 3]
123 [[ 2]
[5 2 3] [ 6]
[[1 2 3]
[10]] (3, 1)
[4 5 6]]
(2, 3) [1 4 5]
[[ 1 2 3 4] [1 4 5]
[ 5 6 7 8] [[1 2]
[ 9 10 11 12]] [3 4]]
(3, 4) [[5 6]
[[ 7 8] [7 8]]
[11 12]] [[ 6 8]
[5 6 7 8] [10 12]]
(4,) 27
[[5 6 7 8]] [12 15]
(1, 4) [ 3 7 17]
[ 2 6 10] (3,) [[1 3 8]
[2 4 9]]
RESULT:
Thus the program using modules of numpywas written and executed successfully.
ALGORITHM:
1. Install the needed library using pip install pandas
2. Import the needed libraries
3. Plotting the values using plot() function and then view the graph using view() fuction
4. Plotting the values range from [xmin, xmax, ymin, ymax]
5. Bar graph using the function bar()
6. Arrange the elements in order using arrange() function
7. The values range can be plotted using hist() function
8. A scatter plot is a chart type that is normally used to observe and visually display the
relationship between variables
9. subplot(m,n,p) divides the current figure into an m-by-n grid and creates axes in the
position specified by p
10. A pie chart is a circle that is divided into areas, or slices. Each slice represents the
count or percentage of the observations of a level for the variable
11. Stack plots are mainly used to see various trends in variables over a specific period of
time.
PROGRAM/SOURCE CODE:
from matplotlib import pyplot as plt
import numpy as np
from matplotlib import style
plt.plot([1,2,3],[4,5,1])
plt.show()
plt.plot([1, 2, 3, 4], [1, 4, 9, 16],'ro',label='line1')
plt.plot([1,2,3,4],[1,2,3,4],linewidth=5,label='line2')
plt.plot([5,6,7,8,9],[5,6,7,8,9],'ro-',label='line3')
plt.plot([5,6,7,8,9],
[6,6,6,6,6],color='red',linestyle='-',marker='o',markersize='5',markerfacecolor='g')
plt.axis([0,10,0,20])
plt.legend()
plt.show()
t=np.arange(0,5,.2)
plt.plot(t,t,'r--',t,t**2,'bo',t,t**4,'c^')
x = [5,8,10]
y = [12,16,6]
x2 = [6,9,11]
y2 = [6,15,7]
plt.plot(x,y,'g',label='line one', linewidth=5)
plt.plot(x2,y2,'c',label='line two',linewidth=5)
plt.title('Epic Info')
plt.ylabel('Y axis')
plt.xlabel('X axis')
plt.ylabel('Distance (plt.legend()
plt.grid(True,color='r')
plt.show()
plt.bar([0.25,1.25,2.25,3.25,4.25],[50,40,70,80,20],
label="BMW",color='r',width=.1)
plt.bar([.75,1.75,2.75,3.75,4.75],[80,20,20,50,60],
label="Audi", color='b',width=.5)
plt.legend()
plt.xlabel('Days')kms)')
plt.title('Information')
plt.show()
population_age =
[22,55,62,45,21,22,34,42,42,4,2,102,95,85,55,110,120,70,65,55,111,42,42,42,42,
115,80 ,75,65,54,44,43,42,48,42,42,42]
bins = np.arange(1,200)
plt.hist(population_age,bins, histtype='step')
plt.xlabel('age groups')
plt.ylabel('Number of people')
plt.title('Histogram')
plt.show()
x = [1,1.5,2,2.5,3,3.5,3.6]
y = [7.5,8,8.5,9,9.5,10,10.5]
x1=[8,8.5,9,9.5,10,10.5,11]
y1=[3,3.5,3.7,4,4.5,5,5.2]
plt.scatter(x,y, label='high income low saving',color='r')
plt.scatter(x1,y1,label='low income high savings',color='b')
plt.xlabel('saving*100')
plt.ylabel('income*1000')
plt.title('Scatter Plot')
plt.legend()
plt.show()
days = [1,2,3,4,5]
sleeping =[7,8,6,11,7]
eating = [2,3,4,3,2]
working =[7,8,7,2,2]
playing = [8,5,7,8,13]
plt.plot([],[],color='m', label='Sleeping', linewidth=5)
plt.plot([],[],color='c', label='Eating', linewidth=5)
plt.stackplot(days, sleeping,eating,working,playing,
colors=['m','c','r','k'])
plt.xlabel('x')
plt.ylabel('y')
plt.title('Stack Plot')
plt.legend()
plt.show()
days = [1,2,3,4,5]
slices = [2,2,2,13]
activities = ['sleeping','eating','working','playing']
cols = ['c','m','r','b']
plt.pie(slices,
labels=activities,
colors=cols,
startangle=180 )
plt.title('Pie Plot')
plt.show()
def f(t):
returnnp.exp(-t) * np.cos(2*np.pi*t)
t1 = np.arange(0.0, 5.0, 0.1)
t2 = np.arange(0.0, 5.0, 0.02)
plt.subplot(211) #no of plots, row wise or column wise, 1 2 plot
plt.plot(t1, f(t1), 'bo', t2, f(t2))
plt.subplot(212)
plt.plot(t2, np.cos(2*np.pi*t2))
plt.show()
# Compute the x and y coordinates for points on sine and cosine curves
x = np.arange(0, 3 * np.pi, 0.1)
y_sin = np.sin(x)
y_cos = np.cos(x)
# Set up a subplot grid that has height 2 and width 1,
# and set the first such subplot as active.
plt.subplot(2, 1, 1)
# Make the first plot
plt.plot(x, y_sin)
plt.title('Sine')
# Set the second subplot as active, and make the second plot.
plt.subplot(2, 1, 2)
plt.plot(x, y_cos)
plt.title('Cosine')
# Show the figure.
plt.show()
OUTPUT:
RESULT:
Thus the program using modules of matplotlib was written and executed successfully.
EXNO 8D) IMPLEMENTING PROGRAM USING WRITTEN MODULES AND
PYTHON STANDARD LIBRARY
(SCIPY)
AIM:
To write a python program using scipylibrary
ALGORITHM:
1. Install the needed library using pip install pandas
2. Import the needed libraries
3. linalg.solve(a, b)solve a linear matrix equation, or system of linear scalar equations.
Computes the “exact” solution, x, of the well-determined, i.e., full rank, linear matrix
equation ax = b.
4. Determinants of Square Matrices using det() function
5. An inverse of a Square Matrix using inv() function
6. Singular Value Decomposition using svd() function
7. Working with Polynomials in SciPyusing poly1d() function
8. Finding integration and derivatives using integ() and deriv() function
9. Vectorizing Function in SciPyusingvectorize()
10. Fast Fourier Transforms in SciPyusingfft() function
11. Stack plots are mainly used to see various trends in variables over a specific period of
time.
PROGRAM/SOURCE CODE:
from scipy import linalg
import numpy as np
from numpy import poly1d
from scipy import integrate
from scipy.fftpack import fft
import matplotlib.pyplot as plt
A=np.array([[2,3],[3,4]])
B=np.array([[7],[10]])
linalg.solve(A,B)
A.dot(linalg.solve(A,B))-B
RESULT:
Thus the python program to copy the contents of file from one to another file was written
and executed successfully.
EXNO 9B) IMPLEMENTING REAL TIME/TECHNICAL APPLICATION USING
FILE HANDLING(WORD COUNT)
AIM:
To write a python program to count the number of words in a file
ALGORITHM:
1. Initialize the count as zero
2. Open the file with read permission
3. For every line in file
4. Split the words using split()
5. Increment the count value as count = count + len(words)
6. Close the file
PROGRAM/SOURCE CODE:
count = 0;
file = open("E:\Saranya\Python 1st year\saran.txt", "r")
for line in file:
words = line.split(" ");
count = count + len(words);
print("Number of words present in given file: " + str(count));
file.close();
OUTPUT:
Number of words present in given file: 40
RESULT:
Thus the python program to count the number of words in a file was written executed
successfully.
EXNO 9C) IMPLEMENTING REAL TIME/TECHNICAL APPLICATION USING
FILE HANDLING(LONGEST WORD)
AIM:
To write a python program to find longest file in word
ALGORITHM:
1. Define the function longest_words with parameter file name
2. Open the file with read permission
3. Read and split the words in file
4. Find maximum words length word in file using len(max(words, key=len))
5. Print the longest word in file
PROGRAM/SOURCE CODE:
def longest_words(filename):
with open(filename, 'r') as infile:
words = infile.read().split()
max_len = len(max(words, key=len))
return [word for word in words if len(word) == max_len]
print(longest_words('E:\Saranya\Python 1st year\saran.txt'))
OUTPUT:
["'FrontStreeringAndSuspension',", "'FrontStreeringAndSuspension',"]
RESULT:
Thus the python program to find longest word in a file was written executed successfully.
EXNO 10A) IMPLEMENTING REAL TIME/TECHNICAL APPLICATION USING
EXCEPTION HANDLING (DIVIDE BY ZERO ERROR)
AIM:
To write a python program to handle exceptions for divide by zero
ALGORITHM:
1. Get the values of n,d,c from console
2. Inside try write division rule and print quotient
3. In Except throw ZeroDivisionError
4. Inside except print Division by zero error message
PROGRAM/SOURCE CODE:
n=int(input("Enter the value of n:"))
d=int(input("Enter the value of d:"))
c=int(input("Enter the value of c:"))
try:
q=n/(d-c)
print("Quotient:",q)
except ZeroDivisionError:
print("Division by Zero!")
OUTPUT:
Enter the value of n:4
Enter the value of d:10
Enter the value of c:2
Quotient: 0.5
RESULT:
Thus the python program for divide by zero using exception handling was written
executed successfully.
EXNO 10B) IMPLEMENTING REAL TIME/TECHNICAL APPLICATION USING
EXCEPTION HANDLING(VOTERS AGE VALIDITY)
AIM:
To write a python program for voters age validity using exception handling
ALGORITHM:
1. Define function main()
2. Inside function use try block
3. Inside try block get the age value
4. Then check if age>18 print eligible to vote
5. Else print not eligible to vote
6. In except block print error default error message
7. Inside finallythe code to be executed whether exception occurs or not. Typically for
closing files and other resources
8. Call the main() function
PROGRAM/SOURCE CODE:
def main():
try:
age=int(input("Enter your age"))
if age>18:
print("Eligible to vote")
else:
print("Not eligible to vote")
except ValueError as err:
print(err)
finally:
print("Thank you")
main()
OUTPUT:
Enter your age21
Eligible to vote
Thank you
RESULT:
Thus the python program for voters age validity using exception handling was written
executed successfully.
EXNO 10C) IMPLEMENTING REAL TIME/TECHNICAL APPLICATION USING
EXCEPTION HANDLING(STUDENT MARK VALIDATION)
AIM:
To write a python program for student mark validation using exception handling
ALGORITHM:
1) Get the name from console
2) Assign length of name to a
3) If the name is not numeric then print letter is not string
4) Else raise type error as “letter is numeric only strings are allowed”
5) Create empty list as mark_list[]
6) Inside for loop upto range 5
7) Get the mark and append in mark_list
8) Inside for loop check the mark is between 0 to 100
9) If yes then print “mark is accepted”
10) Else raise ValueError "mark should lies between 0 to 100"
PROGRAM/SOURCE CODE:
name=input("Enter name of the student")
isnum=True
a=len(name)
print(a)
for i in range(0,a):
if name[i].isnumeric()!=isnum:
print("letter",i,"is string")
else:
mark_list=[]
for i in range(5):
mark=input("Enter mark:")
mark_list.append(mark)
print(mark_list)
for i in mark_list:
x=int(i)
if(0<=x<=100):
print(x)
OUTPUT:
letter 2 is string 5
['12', '3', '56', '7', '3'] Enter name of the student sat
12 4
RESULT:
Thus the python program for student mark validation using exception handling was
written and executed successfully
EXNO 11) EXPLORING PYGAME TOOL
AIM:
To write a python program for exploring pygame tool.
ALGORITHM:
1. Import the needed libraries
2. Initialize pygame by init()
3. Set up the drawing window with height and width as parameters
4. Run until the user asks to quit by running=True
5. Inside while check whether the user click the window close button. If yes then Quit
the pygame
6. Fill the background with white fill(255,255,255)
7. Then draw a solid blue circle in the center
8. Flip the display
PROGRAM/SOURCE CODE:
import pygame
pygame.init()
# Set up the drawing window
screen = pygame.display.set_mode([500, 500])
# Run until the user asks to quit
running = True
while running:
# Did the user click the window close button?
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Fill the background with white
screen.fill((255, 255, 255))
# Draw a solid blue circle in the center
pygame.draw.circle(screen, (0, 0, 255), (250, 250), 75)
# Flip the display
pygame.display.flip()
# Done! Time to quit.
pygame.quit()
OUTPUT:
RESULT:
Thus the python program for exploring pygame was written executed successfully.
EXNO 12A) DEVELOPING GAME ACTIVITY USING PYGAME
(BOUNCING BALL)
AIM:
To write python program using pygame for bouncing ball
ALGORITHM:
1. Import the needed libraries
2. Initialise the pygame window
3. Set the pygame window using set_mode(width,height)
4. Set the pygame window titke as bouncing ball using set_caption()
5. Load the ball image in pygame.image.load()
6. If the pygame event is QUIT then exit.
7. Else move the ball with particular speed
8. If ballrect.left< 0 or ballrect.right> width and ballrect.top< 0 orballrect.bottom>
height then reduce the speed
PROGRAM/SOURCE CODE:
import sys, pygame
pygame.init()
size = width, height = 800, 400
speed = [1, 1]
background = 255, 255, 255
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Bouncing ball")
ball = pygame.image.load("ball.jfif")
ballrect = ball.get_rect()
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
ballrect = ballrect.move(speed)
if ballrect.left < 0 or ballrect.right > width:
speed[0] = -speed[0]
if ballrect.top < 0 or ballrect.bottom > height:
speed[1] = -speed[1]
screen.fill(background)
screen.blit(ball, ballrect)
pygame.display.flip()
OUTPUT:
RESULT:
Thus the python program for bouncing ball using pygame was written and executed
successfully.
EXNO 12A) DEVELOPING GAME ACTIVITY USING PYGAME
(CAR GAME)
AIM:
To write python program using pygame for car game.
ALGORITHM:
1) Import needed libraries
2) Initialise pygame window with height and width
3) Load the background and car images
4) Run the car by calling run_car function
5) If not crashed run else game over
6) If left key is pressed then self.car_x_coordinate -= 50
7) If right key is pressed then self.car_x_coordinate += 50
PROGRAM/SOURCE CODE:
import random
from time import sleep
import pygame
class CarRacing:
def __init__(self):
pygame.init()
self.display_width = 800
self.display_height = 600
self.black = (0, 0, 0)
self.white = (255, 255, 255)
self.clock = pygame.time.Clock()
self.gameDisplay = None
self.initialize()
def initialize(self):
self.crashed = False
self.carImg = pygame.image.load('C:/Users/lenovo/Desktop/car game/car.png')
self.car_x_coordinate = (self.display_width * 0.45)
self.car_y_coordinate = (self.display_height * 0.8)
self.car_width = 49
# enemy_car
self.enemy_car = pygame.image.load('C:/Users/lenovo/Desktop/car
game/enemy_car_1.png')
self.enemy_car_startx = random.randrange(310, 450)
self.enemy_car_starty = -600
self.enemy_car_speed = 5
self.enemy_car_width = 49
self.enemy_car_height = 100
# Background
self.bgImg = pygame.image.load("C:/Users/lenovo/Desktop/car game/back_ground.jpg")
self.bg_x1 = (self.display_width / 2) - (360 / 2)
self.bg_x2 = (self.display_width / 2) - (360 / 2)
self.bg_y1 = 0
self.bg_y2 = -600
self.bg_speed = 3
self.count = 0
def car(self, car_x_coordinate, car_y_coordinate):
self.gameDisplay.blit(self.carImg, (car_x_coordinate, car_y_coordinate))
def racing_window(self):
self.gameDisplay = pygame.display.set_mode((self.display_width, self.display_height))
pygame.display.set_caption('Car Race -- Godwin')
self.run_car()
def run_car(self):
while not self.crashed:
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.crashed = True
# print(event)
if (event.type == pygame.KEYDOWN):
if (event.key == pygame.K_LEFT):
self.car_x_coordinate -= 50
if (event.key == pygame.K_RIGHT):
self.car_x_coordinate += 50
self.gameDisplay.fill(self.black)
self.back_ground_raod()
self.run_enemy_car(self.enemy_car_startx, self.enemy_car_starty)
self.enemy_car_starty += self.enemy_car_speed
if self.enemy_car_starty > self.display_height:
self.enemy_car_starty = 0 - self.enemy_car_height
self.enemy_car_startx = random.randrange(310, 450)
self.car(self.car_x_coordinate, self.car_y_coordinate)
self.highscore(self.count)
self.count += 1
if (self.count % 100 == 0):
self.enemy_car_speed += 1
self.bg_speed += 1
if self.car_y_coordinate < self.enemy_car_starty + self.enemy_car_height:
if self.car_x_coordinate > self.enemy_car_startx and self.car_x_coordinate <
self.enemy_car_startx + self.enemy_car_width or self.car_x_coordinate + self.car_width >
self.enemy_car_startx and self.car_x_coordinate + self.car_width < self.enemy_car_startx +
self.enemy_car_width:
self.crashed = True
self.display_message("Game Over !!!")
if self.car_x_coordinate < 310 or self.car_x_coordinate > 460:
self.crashed = True
self.display_message("Game Over !!!")
pygame.display.update()
self.clock.tick(60)
def display_message(self, msg):
font = pygame.font.SysFont("comicsansms", 72, True)
text = font.render(msg, True, (255, 255, 255))
self.gameDisplay.blit(text, (400 - text.get_width() // 2, 240 - text.get_height() // 2))
self.display_credit()
pygame.display.update()
self.clock.tick(60)
sleep(1)
car_racing.initialize()
car_racing.racing_window()
def back_ground_raod(self):
self.gameDisplay.blit(self.bgImg, (self.bg_x1, self.bg_y1))
self.gameDisplay.blit(self.bgImg, (self.bg_x2, self.bg_y2))
self.bg_y1 += self.bg_speed
self.bg_y2 += self.bg_speed
if self.bg_y1 >= self.display_height:
self.bg_y1 = -600
if self.bg_y2 >= self.display_height:
self.bg_y2 = -600
def run_enemy_car(self, thingx, thingy):
self.gameDisplay.blit(self.enemy_car, (thingx, thingy))
def highscore(self, count):
font = pygame.font.SysFont("lucidaconsole", 20)
text = font.render("Score : " + str(count), True, self.white)
self.gameDisplay.blit(text, (0, 0))
def display_credit(self):
font = pygame.font.SysFont("lucidaconsole", 14)
text = font.render("Thanks & Regards,", True, self.white)
self.gameDisplay.blit(text, (600, 520))
text = font.render("J Godwin", True, self.white)
self.gameDisplay.blit(text, (600, 540))
text = font.render("[email protected]", True, self.white)
self.gameDisplay.blit(text, (600, 560))
if __name__ == '__main__':
car_racing = CarRacing()
car_racing.racing_window()
OUTPUT: