0% found this document useful (0 votes)
54 views

1-PPS Python Lab Manual CSEL202

Uploaded by

mkailasanathan6
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
54 views

1-PPS Python Lab Manual CSEL202

Uploaded by

mkailasanathan6
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 86

Ex.No.

1(a) Identification and solving of simple real life or


scientific or technical problems - Electricity Billing

AIM:
To write a python program for the electricity billing.

ALGORITHM:
Step 1: Start the program.
Step 2: Read the input variable "unit".
Step 3: Process the following:
When the unit is less than or equal to 100units,
calculate usage-unit*5.
When the unit is between 100 to200 units,
calculate usage (100*5)+((unit-100)*7).
When the unit is between 200 to 300 units,
calculate usage (100*5)+(100*7)+((unit- 200)*10)
When the unit is above 300units, calculate usage
(100*5)+(100*7)+(100*10)+((unit- 300)*15)
For further, no additional charge will be calculated.
Step 4: Display the amount "usage" to the user.
Step 5: Stop the program.
PROGRAM:
unit=int(input("Please enter Number of Unit you
Consumed :"))
if(unit<=100):
usage=unit*5
elif(unit<=200):
usage=(100*5)+((unit-00)*7)
elif(unit<=300):
usage=(100*5)+(100*7)+((unit-0)*10)
else:
usage=(100*5)+(100*7)+(100*10)+((unit-300)*15)
print("Electricity Bill=%.2f"%usage)
print("Note: No additional charge will be calculated ")
OUTPUT:
Please enter Number of Unit you Consumed : 650
Electricity Bill = 7450.00
Note: No additional charge will be calculated
RESULT:
Thus the electricity billing program has been executed and
verified successfully.
Ex.No.1(b) Identification and solving of simple real life or
scientific or technical problems - Retail Shop Billing

AIM:
To write a python program for the retail shop billing.

ALGORITHM:
Step 1: Start the program
Step 2: Initialize the values of the items
Step 3: Read the input like the name of item and quantity.
Step 4: Process the following amount= (item_name *quantity) +
amount
Step 5: Repeat the step4 until the condition get fails.
Step 6: Display the value of "amount".
Step 7: Stop the program.
PROGRAM:
print("Welcome to Riya Retail Shopping")
print("List of items in our market")
soap=60;power=120;tooth_brush=40;paste=80;perfume=250
amount=0
print("1.Soap\n2.Powder\n3.Tooth Brush\n4.Tooth Paste
\n5.Perfume")
print("To Stop the shopping type number 0")
while (1):
item = int(input("Enter the item number: "))
if(item==0):
break
else:
if(item<=5):
quantity=int(input("Enter the quantity: "))
if(item==1):
amount=(soap*quantity)+amount
elif(item==2):
amount=(power*quantity)+amount
elif(item==3):
amount=(tooth_brush*quantity)+amount
elif(item==4):
amount=(paste*quantity)+amount
elif(item==5):
amount=(perfume*quantity)+amount
else:
print("Item Not available")
print("Total amount need to pay is: ",amount)
print("Happy for your visit")
OUTPUT:
Welcome to Riya Retail Shopping
List of items in our market
1.Soap
2.Powder
3.Tooth Brush
4.Tooth Paste
5.Perfume
To Stop the shopping type number 0
Enter the item number: 1
Enter the quantity: 5
Enter the item number: 2
Enter the quantity: 4
Enter the item number: 0
Total amount need to pay is: 780
Happy for your visit
RESULT:
Thus the retail shop billing program has been executed and verified
successfully.
Ex.No.1(c) Identification and solving of simple real life or
scientific or technical problems - Sin Series

AIM:
To write a python program for sin series.

ALGORITHM:
Step 1: Start the program.
Step 2: Read the input like the value of x in radians and n
where n is a number up to which we want to print the
sum of series.
Step 3: For first term,
x-x*3.14159/180
t-x;
sum-x
Step 4: For next term,
t(t*(-1)*x*x)/(2*i*(2*i+1))
sum-sum+t;
Step 5: Repeat the step4, looping 'n' 'times to get the sum of
first 'n' terms of the series.
Step 6: Display the value of sum.
Step 7: Stop the program.
PROGRAM:
x=float(input("Enter the value for x : "))
a=x
n=int(input("Enter the value for n : "))
x=x*3.14159/180
t=x;
sum=x
for i in range(1,n+1):
t=(t*(-1)*x*x)/(2*i*(2*i+1))
sum=sum+t
print("The value of Sin(",a,")=",round(sum,2))
OUTPUT:
Enter the value for x : 30
Enter the value for n : 5
The value of Sin( 30.0 )= 0.5
RESULT:
Thus the sine series program has been executed and verified
successfully.
Ex.No.2(a) Python programming using simple statements and
expressions - Exchange the Values of Two Variables

AIM:
Write a python program to exchange the values of two variables.

ALGORITHM:
Step 1: Declared a temporary variable a and b.
Step 2: Assign the value of a and b.
Step 3: Assign the value of a to b, and b to a.
Step 4: We don’t even need to perform arithmetic operations.
We can use:
a,b = b,a
Step 5: To print the result.
PROGRAM:
a=10
b=20
a,b=b,a
print("The swapping of a value is=",a)
print("The swapping of b value is=",b)
OUTPUT:
The swapping of a value is= 20
The swapping of b value is= 10
RESULT:
Thus the swapping of two numbers python program was executed
successfully and verified.
Ex.No.2(b) Python programming using simple statements and
expressions - Circulate the Values of “n” Variables

AIM:
Write a python program to circulate the values of n variables.

ALGORITHM:
Step 1: Circulate the values of n variables.
Step 2: Get the input from the user.
Step 3: To create the empty list then declare the conditional
statements using for loop.
Step 4: Using append operation to add the element in the list and
the values are rotate by using this append operation.
Step 5: Stop the program.
PROGRAM:
def circulate(A,N):
for i in range(1,N+1):
B=A[i:]+A[:i]
print("circulation",i,"=",B)
return
A=[11,12,13,14,15,16,17,18]
N=int(input("Enter n:"))
circulate(A,N)
OUTPUT:
Enter n:5
circulation 1 = [12, 13, 14, 15, 16, 17, 18, 11]
circulation 2 = [13, 14, 15, 16, 17, 18, 11, 12]
circulation 3 = [14, 15, 16, 17, 18, 11, 12, 13]
circulation 4 = [15, 16, 17, 18, 11, 12, 13, 14]
circulation 5 = [16, 17, 18, 11, 12, 13, 14, 15]
RESULT:
Thus the python program to circulate the values of n variables was
executed successfully and verified.
Ex.No.2(c) Python programming using simple statements and
expressions - Distance between two points

AIM:
Write a python program to calculate the distance between two
numbers.

ALGORITHM:
Step 1: Start the program.
Step 2: Read all the values of x1,x2,y1,y2.
Step 3: Calculate the result.
Step 4: Print the result.
Step 5: Stop the program.
PROGRAM:
import math
x1=int(input("Enter the value of x1="))
x2=int(input("Enter the value of x2="))
y1=int(input("Enter the value of y1="))
y2=int(input("Enter the value of y2="))
dx=x2-x1
dy=y2-y1
d=dx**2+dy**2
result=math.sqrt(d)
print(result)
OUTPUT:
Enter the value of x1=56
Enter the value of x2=76
Enter the value of y1=87
Enter the value of y2=98
22.825424421026653
RESULT:
Thus the distance between of two points was successfully executed
and verified.
Ex.No.3(a) Scientific problems using conditionals and
iterative loops - Number Series

AIM:
Write a python program with conditional and iterative statements for
number series.

ALGORITHM:
Step 1: Start the program.
Step 2: Read the value of n.
Step 3: Initialize i = 1,x=0.
Step 4: Repeat the following until i is less than or equal to n.
Step 4.1: x=x*2+1.
Step 4.2: Print x.
Step 4.3: Increment the value of i .
Step 5: Stop the program.
PROGRAM:
n=int(input(" Enter the number of terms for the series "))
i=1
x=0
while(i<=n):
x=x*2+1
print(x, sep= "")
i+=1
OUTPUT:
Enter the number of terms for the series 5
1
3
7
15
31
RESULT:
Thus the python program to print numbers series is executed and
verified.
Ex.No.3(b) Scientific problems using conditionals and
iterative loops - Number Patterns

AIM:
Write a python program with conditional and iterative statements for
number pattern.

ALGORITHM:
Step 1: Start the program.
Step 2: Declare the value for rows.
Step 3: Let i and j be an integer number.
Step 4: Repeat step 5 to 8 until all value parsed.
Step 5: Set i in outer loop using range function, i = rows+1 and
rows will be initialized to I.
Step 6: Set j in inner loop using range function and i integer will be
initialized to j.
Step 7: Print i until the condition becomes false in inner loop.
Step 8: Print new line until the condition becomes false in outer
loop.
Step 9: Stop the program.
PROGRAM:
rows = int(input('Enter the number of rows'))
for i in range(rows+1):
for j in range(i):
print(i, end=' ')
print(' ')
OUTPUT:
Enter the number of rows 5
1
22
333
4444
55555
RESULT:
Thus the python program to print numbers patterns is executed and
verified
Ex.No.3(c) Scientific problems using conditionals and
iterative loops - Pyramid Pattern

AIM:
Write a Python program with conditional and iterative statements for
Pyramid Pattern.

ALGORITHM:

Step 1: Start the program


Step 2: Read the value for rows.
Step 3: Let i and j be an integer number.
Step 4: Repeat step 5 to 8 until all value parsed.
Step 5: Set i in outer loop using range function, i = 0 to rows ;
Step 6: Set j in inner loop using range function, j=0 to i+1;
Step 7: Print * until the condition becomes false in inner loop.
Step 8: Print new line until the condition becomes false in outer
loop.
Step 9: Stop the program.
PROGRAM:
n=int(input("Enter the no. of rows "))
for i in range(0, n):
for j in range(0, i+1):
print("*",end=" ")
print("\r")
OUTPUT:
Enter the no. of rows 5
*
**
***
****
*****
RESULT:
Thus the python program to print numbers pyramid patterns is
executed and verified.
Ex.no.4 Implementing real-time/technical applications
using Lists, Tuples

AIM:
To Write a python program to implement items present in a library.

ALGORITHM:
STEP 1: Start the program.
STEP 2: Create the variable inside that variable assigned the list of
elements based on the library using List and tuple.
STEP 3: Using array index to print the items using list and tuple.
STEP 4: To print the result using output statement.
STEP 5: Stop the program.
PROGRAM:
library=["books", "author", "barcodenumber" , "price"]
library[0]="ramayanam"
print(library[0])
library[1]="valmiki"
library[2]=123987
library[3]=234
print(library)
print("Tuple : ")
tup1 = (12134,250000 )
tup2 = ('books', 'totalprice')
tup3 = tup1+ tup2
print(tup3)
OUTPUT:
ramayanam
['ramayanam', 'valmiki', 123987, 234]
Tuple :
(12134, 250000, 'books', 'totalprice')
RESULT:
Thus the Python Program is executed successfully and the output is
verified.
Ex.No.5(a) Implementing real-time/technical applications
using sets, dictionaries - Language

AIM:
To write a python program for language.

ALGORITHM:
Step 1: Start the program.
Step 2: Assign the languages.
Step 3: Perform all the dictionary operations.
Step 4: Print the result.
Step 5: End the program.
PROGRAM:
LANGUAGE1={'Pitch','Syllabus','Script','Grammar','Sentences'}
LANGUAGE2={'Grammar','Syllabus','Context','Words','Phonetics'}
print("Union of LANGUAGE1 and LANGUAGE2
is”,LANGUAGE1|LANGUAGE2)
print("Intersection of LANGUAGE1 and LANGUAGE2
is ",LANGUAGE1&LANGUAGE2)
print("Difference of LANGUAGE1 and LANGUAGE2
is ",LANGUAGE1-LANGUAGE2)
print("Symmetric difference of LANGUAGE1 and LANGUAGE2
is ",LANGUAGE1^LANGUAGE2)
OUTPUT:
Union of LANGUAGE1 and LANGUAGE2 is {'Syllabus',
'Sentences', 'Pitch', 'Grammar', 'Words', 'Script', 'Context',
'Phonetics'}
Intersection of LANGUAGE1 and LANGUAGE2 is {'Syllabus',
'Grammar'}
Difference of LANGUAGE1 and LANGUAGE2 is {'Script',
'Sentences', 'Pitch'}
Symmetric difference of LANGUAGE1 and LANGUAGE2 is
{'Script', 'Sentences', 'Pitch', 'Context', 'Words', 'Phonetics'}
RESULT:
Thus the Language program has been executed and verified
successfully.
Ex.No.5(b) Implementing real-time/technical applications using
sets, dictionaries - Components of an Automobile

AIM:
To write a python program to implement Components of an
automobile using Sets and Dictionaries.

ALGORITHM:
STEP 1: Start the program.
STEP 2: Create the variable and stored the unordered list of
elements based on materials required for construction of
building set and dictionary.
STEP 3: Using for loop to list the number of elements and using
array index to print the items using set and dictionary.
STEP 4: To print the result using output statement.
STEP 5: Stop the program.
(i) SET :

PROGRAM:
cars={'BMW','Honda','Audi','Mercedes','Honda','Toyota','Ferrari',
'Tesla'}
print('Approach #1=',cars)
print('---------------')
print('Approach #2')
for car in cars:
print('Car name={}'.format(car))
print('---------------')
cars.add('Tata')
print('New cars set={}'.format(cars))
cars.discard('Mercedes')
print('discard()method={}'.format(cars))
OUTPUT:
Approach #1= {'Ferrari', 'Mercedes', 'Audi', 'Tesla', 'BMW', 'Toyota',
'Honda'}
---------------
Approach #2
Car name=Ferrari
Car name=Mercedes
Car name=Audi
Car name=Tesla
Car name=BMW
Car name=Toyota
Car name=Honda
---------------
New cars set={'Ferrari', 'Tata', 'Mercedes', 'Audi', 'Tesla', 'BMW',
'Toyota', 'Honda'}
discard()method={'Ferrari', 'Tata', 'Audi', 'Tesla', 'BMW', 'Toyota',
'Honda'}
(ii) DICTIONARY

PROGRAM:
Dict = {}
print("Empty Dictionary: ")
print(Dict)
Dict[0] = 'BRICKS'
Dict[2] = 'CEMENT'
Dict[3] = 'BLUE PRINT'
print("\nDictionary after adding 3 elements: ")
print(Dict)
Dict['Value_set'] = 2, 3, 4
print("\nDictionary after adding 3 elements: ")
print(Dict)
Dict[2] = 'STEEL'
print("\nUpdated key value: ")
print(Dict)
Dict[5] = {'Nested': {'1': 'LIME', '2': 'SAND'}}
print("\nAdding a Nested Key: ")
print(Dict)
OUTPUT:
Empty Dictionary:
{}

Dictionary after adding 3 elements:


{0: 'BRICKS', 2: 'CEMENT', 3: 'BLUE PRINT'}

Dictionary after adding 3 elements:


{0: 'BRICKS', 2: 'CEMENT', 3: 'BLUE PRINT', 'Value_set': (2, 3, 4)}

Updated key value:


{0: 'BRICKS', 2: 'STEEL', 3: 'BLUE PRINT', 'Value_set': (2, 3, 4)}

Adding a Nested Key:


{0: 'BRICKS', 2: 'STEEL', 3: 'BLUE PRINT', 'Value_set': (2, 3, 4), 5:
{'Nested': {'1': 'LIME', '2': 'SAND'}}}
RESULT:
Thus the program was executed successfully and verified.
Ex.No.5(c) Implementing real-time/technical applications
using sets, dictionaries - Elements of a civil structure

AIM:
To write a python program for elements of a civil structure.

ALGORITHM:
Step 1: Start the program.
Step 2: Assign the elements of a civil structure.
Step 3: Perform all the set operations.
Step 4: Print the result.
Step 5: End the program.
PROGRAM:
print("Elements of a civil structure")
print("............................")
print("1.foundation\n2.floors\n3.walls\n4.beamsandslabs\n5.
columns\n6.roof\n7.stairs\n8.parapet\n9.lintels
\n10.Dampproof")
elements1={"foundation","floors","floors","walls",
"beamsandslabs","columns","roof","stairs","parapet",
"lintels"}
print("\n")
print(elements1)
print("\n")
elements1.add("dampproof")
print(elements1)
elements2={"plants","compound"}
print("\n")
print(elements2)
print("\n")
elements1.update(elements2)
elements1.remove("stairs")
print(elements1)
elements1.discard("hardfloor")
elements1.pop()
print(elements1)
print(sorted(elements1))
print("\n")
print("set operation")
s1={"foundation","floors"}
s2={"floors","walls","beams"}
print(s1.symmetric_difference(s2))
print(s1.difference(s2))
print(s2.difference(s1))
print(s1.intersection(s2))
print(s1.union(s2))
OUTPUT:
Elements of a civil structure
............................
1.foundation
2.floors
3.walls
4.beamsandslabs
5.columns
6.roof
7.stairs
8.parapet
9.lintels
10.Dampproof

{'lintels', 'roof', 'walls', 'columns', 'parapet', 'floors', 'foundation',


'stairs', 'beamsandslabs'}

{'lintels', 'roof', 'dampproof', 'walls', 'columns', 'parapet', 'floors',


'foundation', 'stairs', 'beamsandslabs'}

{'plants', 'compound'}
{'plants', 'lintels', 'roof', 'dampproof', 'compound', 'walls', 'columns',
'parapet', 'floors', 'foundation', 'beamsandslabs'}
{'lintels', 'roof', 'dampproof', 'compound', 'walls', 'columns',
'parapet', 'floors', 'foundation', 'beamsandslabs'}
['beamsandslabs', 'columns', 'compound', 'dampproof', 'floors',
'foundation', 'lintels', 'parapet', 'roof', 'walls']

set operation
{'foundation', 'walls', 'beams'}
{'foundation'}
{'beams', 'walls'}
{'floors'}
{'walls', 'floors', 'foundation', 'beams'}
RESULT:
Thus the elements of a civil structure program has been executed and
verified successfully.
Ex.No.6(a) Implementing factorial programs using functions

AIM:
To Write a Python function to calculate the factorial of a number.

ALGORITHM:
Step 1: Get a positive integer input (n) from the user.
Step 2: Check if the values of n equal to 0 or not if it's zero it
will return 1 Otherwise else statement can be executed.
Step 3: Using the below formula, calculate the factorial of a
number n*factorial(n-1).
Step 4: Print the output i.e the calculated.
PROGRAM:
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
n=int(input("Input a number to compute the factiorial : "))
print(factorial(n))
OUTPUT:
Input a number to compute the factiorial : 4
24
RESULT:
Thus the program was executed and verified successfully.
Ex.No.6(b) Implementing program largest number
in a list using function

AIM:
To Write a Python program to get the largest number from a list.

ALGORITHM:
Step 1: Declare a function that will find the largest number.
Step 2: Use max() method and store the value returned by it in a
variable.
Step 3: Return the variable.
Step 4: Declare and initialize a list or take input.
Step 5: Call the function and print the value returned by it.
PROGRAM:
def max_num_in_list( list ):
max = list[ 0 ]
for a in list:
if a > max:
max = a
return max
print(max_num_in_list([1, 2, -8, 0]))
OUTPUT:
2
RESULT:
Thus the program was executed and verified successfully.
Ex.No.6(c) Implementing programs using functions –
area of shape

AIM:
To Write a python program to implement area of shape using
functions.

ALGORITHM:
Step 1: Get the input from the user shape’s name.
Step 2: If it exists in our program then we will proceed to find the
entered shape’s area according to their respective
formulas.
Step 3: If that shape doesn’t exist then we will print “Sorry!”.
Step 4: Stop the program.
PROGRAM:
def calculate_area(name):
name = name.lower()
if name == "rectangle":
l = int(input("Enter rectangle's length: "))
b = int(input("Enter rectangle's breadth: "))
rect_area = l * b
print("The area of rectangle is", rect_area, ".")
elif name == "square":
s = int(input("Enter square's side length: "))
sqt_area = s * s
print("The area of square is", sqt_area, ".")
elif name == "triangle":
h = int(input("Enter triangle's height length: "))
b = int(input("Enter triangle's breadth length: "))
tri_area = 0.5 * b * h
print("The area of triangle is", tri_area, ".")
elif name == "circle":
r = int(input("Enter circle's radius length: "))
pi = 3.14
circ_area = pi * r * r
print("The area of triangle is", circ_area, ".")
elif name == 'parallelogram':
b = int(input("Enter parallelogram's base length: "))
h = int(input("Enter parallelogram's height length: "))
para_area = b * h
print("The area of parallelogram is", para_area, ".")
else:
print("Sorry! This shape is not available")
print("Calculate Shape Area")
shape_name = input("Enter the name of shape whose area you
want to find: ")
calculate_area(shape_name)
OUTPUT:
Calculate Shape Area
Enter the name of shape whose area you want to find:RECTANGLE
Enter rectangle's length: 10
Enter rectangle's breadth: 15
The area of rectangle is 150.
RESULT:
Thus the python program to implement area of shape using functions
was successfully executed and verified.
Ex.No.7(a) Implementing programs using strings – Reverse

AIM:
To write a python program to implement reverse of a string using
string functions.

ALGORITHM:
Step 1: Start the program.
Step 2: Using function string values of arguments passed in that
function.
Step 3: Python string to accept the negative number using slice
operation.
Step 4: To print the reverse string value by Using reverse method
function.
Step 5: Print the result.
PROGRAM:
def reverse(string):
string = string[::-1]
return string
s = "Firstyearcse"
print ("The original string is : ",end="")
print (s)
print ("The reversed string(using extended slice syntax) is :
",end="")
print (reverse(s))
OUTPUT:
The original string is : Firstyearcse
The reversed string(using extended slice syntax) is : escraeytsriF
RESULT:
Thus the reverse of a string function python program was executed
and successfully verified.
Ex.No. 7(b) Implementing programs using strings - Palindrome

AIM:
To write a python program to implement palindrome using string
functions.

ALGORITHM:
Step 1: Start by declaring the isPalindrome() function and passing
the string argument.
Step 2: Then, in the function body,
Step 3: To get the reverse of the input string using a slice operator
– string[::-1].
Step 4: -1 is the step parameter that ensures that the slicing will
start from the end of the string with one step back each
time.
Step 5: If the reversed string matches the input string, it is a
palindrome Or else, it is not a palindrome.
PROGRAM:
def isPalindrome(s):
return s == s[::-1]
s = input("Enter the string=")
ans = isPalindrome(s)
if ans:
print("The string is palindrome ")
else:
print("The string is not a palindrome")
OUTPUT:
Enter the string=madam
The string is palindrome
RESULT:
Thus the program of palindrome by using function in python
executed successfully and verified.
Ex.No.7(c) Implementing programs using strings
- Character count

AIM:
To Write a python program to implement Characters count using
string functions.

ALGORITHM:
Step 1: User to enter the string. Read and store it in a variable.
Step 2: Initialize one counter variable and assign zero as its value.
Step 3: Increment this value by 1 if any character is found in the
string.
Step 4: Using one loop, iterate through the characters of the string
one by one.
Step 5: Check each character if it is a blank character or not. If it is
not a blank character, increment the value of the counter
variable by ’1‘.
Step 6: After the iteration is completed, print out the value of the
counter.
Step 7: This variable will hold the total number of characters in
the string.
PROGRAM:
input_string = input("Enter a string : ")
count = 0
for c in input_string :
if c.isspace() != True:
count = count + 1
print("Total number of characters : ",count)
OUTPUT:
Enter a string : RAJIV GANDHI COLLEGE OF ENGINEERING
AND TECHNOLOGY
Total number of characters : 44
RESULT:
Thus the program of character count in string in python was executed
successfully and verified.
Ex.No.7(d) Implementing programs using strings
– Replacing Characters

AIM:
To write a python program to implement Replacing Characters using
string functions.

ALGORITHM:
Step 1: Using string.replace(old, new, count)
Step 2: by using string Parameters to change it old – old substring
you want to replace.new – new substring which would
replace the old substring.
Step 3: count – (Optional ) the number of times you want to
replace the old substring with the new substring.
Step 4: To returns a copy of the string where all occurrences of a
substring are replaced with another substring.
PROGRAM:
string = "Welcome to python programming"
print(string.replace("to", "our"))
print(string.replace("og", "a", 3))
OUTPUT:
Welcome our python programming
Welcome to python praramming
RESULT:
Thus the program was executed and successfully verified.

You might also like