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

Ge3171 Lab Manual

The document is a lab manual for Problem Solving and Python Programming at Anna University, detailing various exercises including algorithms, pseudocode, and flowcharts for tasks such as calculating electricity bills, swapping values, calculating distances, and generating patterns. Each exercise includes a clear aim, step-by-step algorithms, Python programs, and results verifying the outputs. The manual serves as a practical guide for implementing programming concepts using Python.

Uploaded by

P SANTHIYA
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Ge3171 Lab Manual

The document is a lab manual for Problem Solving and Python Programming at Anna University, detailing various exercises including algorithms, pseudocode, and flowcharts for tasks such as calculating electricity bills, swapping values, calculating distances, and generating patterns. Each exercise includes a clear aim, step-by-step algorithms, Python programs, and results verifying the outputs. The manual serves as a practical guide for implementing programming concepts using Python.

Uploaded by

P SANTHIYA
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 70

lOMoARcPSD|15656136

GE3171-Lab Manual

Problem Solving and Python Programming (Anna University)

Studocu is not sponsored or endorsed by any college or university


Downloaded by P. SANTHIYA - CSE (psa.cse@builderscollege.edu.in)
lOMoARcPSD|15656136

EX NO. 1
ELECTRICITY BILLING
DATE:

AIM:
To write algorithm, pseudocode and to draw the flowchart for calculating the electricity bill.

ALGORITHM:
STEP1: Start the program
STEP2: Read the number of unit consumed
STEP3: if unit <= 100
STEP4: else if unit<=200
Calculate Bill = (100*10) + (unit-100) *15
STEP5: else if unit<=300
Calculate Bill = (100*10) + (unit*15) + (unit-200) *20
STEP6: else
Calculate Bill = (100*10) + (100*15) + (100*20) + (unit-300) *25
STEP7: Print the value of Bill
STEP8: Stop the program

PSEUDOCODE:
BEGIN
READ the number of unit consumed
IF units<=100
COMPUTE Bill=units*10
ELSE IF unit<=200
COMPUTE Bill = (100*10) + (unit-100) *15
ELSE IF unit<=300
COMPUTE Bill= (100*10) + (unit*15) + (unit-200) *20
ELSE
COMPUTE Bill = (100*10) + (100*15) + (100*20) + (unit-300) *25
PRINT the value of Bill
END

Downloaded by P. SANTHIYA - CSE (psa.cse@builderscollege.edu.in)


lOMoARcPSD|15656136

FLOWCHART:

Downloaded by P. SANTHIYA - CSE (psa.cse@builderscollege.edu.in)


lOMoARcPSD|15656136

RESULT:
The algorithm, pseudocode was been written and flow chart have been drawn for calculating
electricity bill.

Downloaded by P. SANTHIYA - CSE (psa.cse@builderscollege.edu.in)


lOMoARcPSD|15656136

EX NO. 2. (a) EXCHANGE THE VALUES OF TWO


DATE: VARIABLES

AIM:
To implement the python program for swapping the two number with temporary variable and
without using temporary variable.

AIGORITHM: (Using Temporary Value)


STEP1: Start
STEP2: read the value of a, b
STEP3: temp=a
a=b
b=temp
STEP4: print a, b
STEP5: Stop

PROGRAM:
a=int(input(“Enter the value for a:”))
b=int(input(“Enter the value for b:”))
temp=a
a=b
b=temp
print(a,b)

OUTPUT:
Enter the value for a: 80
Enter the value for b: 90
(90,80)

Downloaded by P. SANTHIYA - CSE (psa.cse@builderscollege.edu.in)


lOMoARcPSD|15656136

ALGORITHM: (Without Using Temporary Variable)

STEP1: Start
STEP2: Read the value of a,b
STEP3: a=a-b
b=a+b
a=b-a
STEP4: print a,b
STEP5: Stop

PROGRAM:
a=int(input(“Enter the value for a:”))
b=int(input(“Enter the value for b:”))
a=a-b
b=a+b
a=b-a
print(a,b)

OUTPUT:

Enter the value for a: 80


Enter the value for b: 90
(90, 80)

RESULT:
Thus the python program for swapping the two numbers with and without using temporary variable
was implemented and output was verified.

Downloaded by P. SANTHIYA - CSE (psa.cse@builderscollege.edu.in)


lOMoARcPSD|15656136

EX NO. 2. (b) DISTANCE BETWEEN TWO POINTS


DATE:

AIM:
To implement Python program for calculating the distance between two points.

ALGORITHM:
STEP 1: Start
STEP 2: Take two points as an input from the user.
STEP 3: Calculate the difference between the corresponding X-coordinates i.e X2-X1 and
Y - coordinates i.e Y2-Y1 of two points.
STEP 4: Apply the formula derived from Pythogorean theorem i.e sqrt((X2-X1)^2+(Y2-Y1)^2).
STEP 5: Print distance.
STEP 6: End

PROGRAM:
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:”))
distance= ((((X2-X1)**2+((Y2-Y1)**2))**0.5)
print(“The distance between the two points is:”,distance)

OUTPUT:
Enter the value of X1:6
Enter the value of X2:5
Enter the value of Y1:9
Enter the value of Y2:2
The distance between the two points is: 7.0710678118654755

Downloaded by P. SANTHIYA - CSE (psa.cse@builderscollege.edu.in)


lOMoARcPSD|15656136

RESULT:
Thus the python program for calculating the distance between two points has been implemented
and output was verified.

Downloaded by P. SANTHIYA - CSE (psa.cse@builderscollege.edu.in)


lOMoARcPSD|15656136

EX NO. 2. (c) CIRCULATE THE VALUES OF N


DATE: VARIABLES

AIM:
To implement Python program for circulating the values of n variables of a list.

ALGORITHM:
STEP 1: Start the program.
STEP 2: Assign the list of elements in A.
STEP 3: Read the value of number of circulation.
STEP 4: Call function circulate().
STEP 5: Initialize i=1 to n+1.
STEP 6: Concatenate A[i:] and A[:i] and store it in B.
STEP 7: Print the value of B.
STEP 8: Return
STEP 9: Stop the main function

PROGRAM:
def circulate(A,n):
for i in range(1,n+1):
B=A[i:] + A[:i]
Print(“Circulation”,i,“=”,B)
return

A=[1,2,3,4,5,6,7,8,9]
n=int(input("Enter number of times to be circulated: "))
circulate(A,n)

Downloaded by P. SANTHIYA - CSE (psa.cse@builderscollege.edu.in)


lOMoARcPSD|15656136

OUTPUT:
Enter number of times to be circulated: 5
Circulation 1 = [2, 3, 4, 5, 6, 7, 8, 9, 1]
Circulation 2 = [3, 4, 5, 6, 7, 8, 9, 1, 2]
Circulation 3 = [4, 5, 6, 7, 8, 9, 1, 2, 3]
Circulation 4 = [5, 6, 7, 8, 9, 1, 2, 3, 4]
Circulation 5 = [6, 7, 8, 9, 1, 2, 3, 4, 5]

RESULT:
Thus the Python program for circulating the values of n variables of a list has been implemented
and the output was verified.

Downloaded by P. SANTHIYA - CSE (psa.cse@builderscollege.edu.in)


lOMoARcPSD|15656136

EX NO. 3.(a) NUMBER SERIES (FIBONACCI)


DATE:

AIM:
To implement Python program for printing the number Series (Fibonacci).

ALGORITHM:
STEP 1: Start
STEP 2: Take an integer variable n1, n2, n3 and num
STEP 3: Set n1=0 and n2=0.
STEP 4: Display n1 and n2.
STEP 5: n3=n1+n2.
STEP 6: Display n3.
STEP 7: Start n1=n2, n2=n3.
STEP 8: Repeat from 5-7, for n times.
STEP 7: Stop

PROGRAM:
num = int(input("Enter the Number:"))
n1, n2 = 0, 1
print("Fibonacci Series:", n1, n2, end=",")
for i in range(2, num):
n3 = n1 + n2
n1 = n2
n2 = n3
print(n3, end=" ")
print()

OUTPUT:
Enter the Number: 8
Fibonacci Series: 0 1, 1 2 3 5 8 13

10

Downloaded by P. SANTHIYA - CSE (psa.cse@builderscollege.edu.in)


lOMoARcPSD|15656136

RESULT:
Thus the Python program for printing the Fibonacci number series has been implemented and the
output was verified.

11

Downloaded by P. SANTHIYA - CSE (psa.cse@builderscollege.edu.in)


lOMoARcPSD|15656136

EX NO. 3. (b)
DATE:
NUMBER PATTERN

AIM:
To implement Python program for printing the number pattern.

ALGORITHM:
STEP 1: Start.
STEP 2: Input the number of rows.
STEP 3: Create the outer loop for number of rows.
STEP 4: Create a nested loop for columns.
STEP 5: Display the numbers.
STEP 6: Stop

PROGRAM:
rows = int(input('Enter the number of rows(-1): '))
for i in range(rows):
for j in range(i):
print(i, end=' ')
print('')

OUTPUT:
Enter the number of rows(-1):5

1
22
333
4444

12

Downloaded by P. SANTHIYA - CSE (psa.cse@builderscollege.edu.in)


lOMoARcPSD|15656136

RESULT:
Thus the Python program for printing the number pattern has been implemented and the output was
verified.

13

Downloaded by P. SANTHIYA - CSE (psa.cse@builderscollege.edu.in)


lOMoARcPSD|15656136

EX NO. 3. (c)
DATE:
PYRAMID PATTERN

AIM:
To implement Python program for printing the pyramid pattern.

ALGORITHM:
STEP 1: Start
STEP 2: Read the height of the pyramid.
STEP 3: Initialize k=0
STEP 4: Set the first loop to iterate rows.
STEP 5: Create the nested loop.
STEP 6: Repeat the steps until k!=(2*i-1) by incrementing k to 1
STEP 7: Stop

PROGRAM:
rows = int(input("Enter number of rows: "))
k=0
for i in range(1, rows+1):
for space in range(1, (rows-i)+1):
print(end=" ")
while k!=(2*i-1):
print("* ", end="")
k += 1
k=0
print()

14

Downloaded by P. SANTHIYA - CSE (psa.cse@builderscollege.edu.in)


lOMoARcPSD|15656136

OUTPUT:
Enter number of rows: 5

*
***
*****
*******
*********

RESULT:
Thus the Python program for printing the pyramid pattern has been implemented and the output
was verified.

15

Downloaded by P. SANTHIYA - CSE (psa.cse@builderscollege.edu.in)


lOMoARcPSD|15656136

EX NO. 4 (a)
ITEMS PRESENT IN A LIBRARY USING LIST
DATE:

AIM:
To implement the real time or technical applications using Lists.

ALGORITHM:

Step 1: Start
Step 2: Read no_items
Step 3: Create an empty list L
Step 4: Repeat Step 5 until no_items
Step 5: Read items and append into L
Step 6: Print L
Step 7: Repeat Step 8 until True
Step 8: Read choice ch
Step 9: If ch == 1 then
Read element e1 and index ind
Insert el into L at ind
Print L
Step 10: If ch == 2 then
Read element e1
Remove el from L
Print L
Step 11: If ch == 3 then
Read index ind and new element new_e1
Modify L with new_e1 at ind
Print L
Step 12: If ch == 4 then
Read Search element search_e1
If search_e1 in L then
Print Found
else
Print Not Found
16

Downloaded by P. SANTHIYA - CSE (psa.cse@builderscollege.edu.in)


lOMoARcPSD|15656136

Step 13: If ch == 5 then


quit
Step 14: Stop

PROGRAM:
print("Items in a Library")
no_item = int(input("Enter Number of Items: "))
L=[]
for i in range(no_item):
e=input()
L.append(e)
print(L)
print("List of Operations")
print("1.Insert\n2.Remove\n3.Modify\n4.Search\n5.Exit")
while True:
ch=int(input("Enter your choice : "))
if ch==1:
e1=input("Enter an Item to Insert : ")
ind=int(input("Where to insert an item? Give index : "))
L.insert(ind,e1)
print("List of Items after insertion\n",L)
if ch==2:
e1=input("Enter an Item to delete : ")
L.remove(e1)
print("List of Items after deletion\n",L)
if ch==3:
ind=int(input("Enter an item's index to be modify: "))
new_e1=input("Enter an new Item: ")
if(len(L) > ind):
L[ind]=new_e1
print("List of Items after modification\n",L)

else:

print("Index Out of bound")


17

Downloaded by P. SANTHIYA - CSE (psa.cse@builderscollege.edu.in)


lOMoARcPSD|15656136

search_e1=input("Enter an Item to search : ")


if(search_e1 in L):
print(search_e1,"Found")
if ch==5:
print("Exit")
quit()

OUTPUT:

RESULT:

Thus the Python program was written and executed successfully.

18

Downloaded by P. SANTHIYA - CSE (psa.cse@builderscollege.edu.in)


lOMoARcPSD|15656136

EX NO. 4 (b)
COMPONENTS OF A CAR USING TUPLES.
DATE:

AIM:
To implement the real time or technical applications using Tuples.

ALGORITHM:
Step 1: Start
Step 2: Read n
Step 3: Create an empty list list1
Step 4: Repeat step5 until n
Step 5: Read items and append into list1
Step 6: Create a tuple1 and assign it to tuple(list1)
Step 7: Repeat step8 until True
Step 8: Read choice ch
Step 9: If ch==1 then
Assign t2 to (“accelerator”, “horn”, “steering”)
Print tuple1 + t2
Step10: If ch==2 then
Print tuple1 * 4
Step11: If ch==3 then
Read object from user
Print tuple1.index(object)
Step 12: If ch==4 then
Read start and end from user
Print tuple1[start: end]
Step13: If ch==5 then
Read element from user
Print tuple1.count(element)
Step14: If ch==6 then

Read element from user


Print element in tuple
Print element not in tuple
19

Downloaded by P. SANTHIYA - CSE (psa.cse@builderscollege.edu.in)


lOMoARcPSD|15656136

Step15: if ch == 7 then
Print len(tuple1)
Step16: If ch==8 then
Quit
Step17: Stop

PROGRAM:
n = int(input("enter number of items:"))

list1 = []

for i in range(n):

items = input("Enter the item: ")

list1.append(items)

tuple1 = tuple(list1)

print("1.concatenation\n2.repetition\n3.indexing\n4.slicing\n5.count\n6.membership\n

7.length\n8.exit")

while True:

ch = int(input("Enter your choice: "))

if ch == 1:

t2 = ("accelerator", "horn", "steering")

print(tuple1 + t2)

if ch == 2:

print("Repetition")

print(tuple1 * 4)

if ch == 3:

obj = input("enter the object to find the index: ")

print(tuple1.index(obj))

20

Downloaded by P. SANTHIYA - CSE (psa.cse@builderscollege.edu.in)


lOMoARcPSD|15656136

if ch == 4:

print("slicing operation")

start = int(input("Enter the start index: "))

end = int(input("Enter the end index: "))

print(tuple1[start:end])

if ch == 5:

element = input("Enter the object to be counted: ")

print(tuple1.count(element))

if ch == 6:

element = input("Enter the object to check its existence: ")

print("the object is in the tuple", element in tuple1)

print("the object is not in the tuple", element not in tuple1)

if ch == 7:

print("Length of the tuple: ",

len(tuple1))

if ch == 8:

print("Exit")

quit()

21

Downloaded by P. SANTHIYA - CSE (psa.cse@builderscollege.edu.in)


lOMoARcPSD|15656136

OUTPUT:

RESULT:
Thus the Python program was written and executed successfully.

22

Downloaded by P. SANTHIYA - CSE (psa.cse@builderscollege.edu.in)


lOMoARcPSD|15656136

EX NO. 4 (c)
ELEMENTS OF A CIVIL STRUCTURE USING
DATE: TUPLES

AIM:

To implement the real time or technical applications using Tuples

ALGORITHM:

Step 1: Start

Step 2: Read no_items

Step 3: Create an empty list L

Step 4: Repeat step5 until no_items

Step 5: Read items and append into L

Step 6: Print L

Step 7: Repeat step8 until True

Step 8: Read choice ch

Step 9: If ch==1 then

Read element e1 and index ind

Insert e1 into L at ind

Print L

Step 10: If ch==2 then

Read element e1

Remove e1 from L

Print L

Step 11: If ch==3 then

Read new item,new_e1

Append L with new_element,new_e1

Print L

23

Downloaded by P. SANTHIYA - CSE (psa.cse@builderscollege.edu.in)


lOMoARcPSD|15656136

Step 12: If ch==4 then

Read count element count_n

Count number of occurance of element count_n in list L

Print count_number

Step 13: If ch==5 then

Sort element of list L and store it in sort_

Print sorted element of list,sort_

Step 14: If ch==6 then

Reverse element of list L and store it in reverse_

Print reversed element of list,reverse_

Step 15: If ch==7 then

Quit()

Step 16: Stop

PROGRAM:

print("Materials required for construction of Building")

no_items=int(input("Enter Number of material:"))

L=[]

for i in range(no_items):

e=input()

L.append(e)

print(L)

print("List of Operations")

print("1.Insert\n2.Remove\n3.Append\n4.Count\n5.Sort\n6.Reverse\n7.Exit")

while True:

ch=int(input("Enter your choice:"))

24

Downloaded by P. SANTHIYA - CSE (psa.cse@builderscollege.edu.in)


lOMoARcPSD|15656136

if ch==1:

e1=input("Enter an Item to Insert:")

ind=int(input("Where to insert an item? Give index:"))

L.insert(ind,e1)

print("List of Items after insertion\n",L)

if ch==2:

e1=input("Enter an Item to delete:")

L.remove(e1)

print("List of Items after deletion\n",L)

if ch==3:

new_e1=input("Enter a new Item:")

L.append(new_e1)

print("List of Items after appending\n",L)

if ch==4:

count_n=input("Enter an item to be counted:")

count_number=L.count(count_n)

print(count_number)

if ch==5:

Sort=sorted(L)

print("List after sorted",Sort)

if ch==6:

Reverse=list(reversed(L))

print(Reverse)

if ch==7:

print("Exit")

quit()

25

Downloaded by P. SANTHIYA - CSE (psa.cse@builderscollege.edu.in)


lOMoARcPSD|15656136

OUTPUT:

26

Downloaded by P. SANTHIYA - CSE (psa.cse@builderscollege.edu.in)


lOMoARcPSD|15656136

EX NO. 5 (a)
ELEMENTS OF A CIVIL STRUCTURE
DATE:

AIM:

To implementing real-time/technical applications using dictionary operations.

ALGORITHM:

Step 1: Start

Step 2: Read n

Step 3: Create a dictionary with key and value pair

Step 4: If ch==1

Print items of the dictionary

Step 5: If ch==2

Get key values of dictionary

Step 6: If ch==3

Print the key values

Step 7: If ch==4

Pop values from dictionary.

Step 8: If ch==5

Print values in the dictionary.

Step 9: If ch==6

Update the values in the dictionary

Step 10: If ch==7

Pop items from dictionary.

Step 11: If ch==8

Clearing the dictionary

Step 12: If ch==9; then exit the process

Step 13: Stop

27

Downloaded by P. SANTHIYA - CSE (psa.cse@builderscollege.edu.in)


lOMoARcPSD|15656136

PROGRAM:

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


dictionary = {}
for i in range(n):
key = input("Enter the key: ")
value = input("Enter the value: ")
dictionary[key] = value
print("Dictionary: ", dictionary)
print("List of Operations: ")
print("1.items\n2.get\n3.keys\n4.pop\n5.values\n6.update\n7.pop item\n8.clear\n9.exit")
while True:
ch = int(input("Enter your choice: "))
if ch == 1:
print("Items of the dictionary are ")
print(dictionary.items())
elif ch == 2:
key = input("Enter the key to get: ")
print(dictionary.get(key))
elif ch == 3:
print("The keys in the dictionary are ")
print(dictionary.keys())
elif ch == 4:
key = input("Enter the key to pop: ")
dictionary.pop(key)
print("Dictionary: ", dictionary)
elif ch == 5:
print("The values in the dictionary are ")
print(dictionary.values())
elif ch == 6:
key = input("Enter the key to update: ")
value = input("Enter the new value: ")
dictionary.update({key: value})
print("Dictionary: ", dictionary)
28

Downloaded by P. SANTHIYA - CSE (psa.cse@builderscollege.edu.in)


lOMoARcPSD|15656136

elif ch == 7:
print("Popping the last item")
dictionary.popitem()
print("Dictionary: ", dictionary)
elif ch == 8:
print("Clearing the dictionary")
dictionary.clear()
print("Dictionary: ", dictionary)
elif ch == 9:
print("Exit")
quit()

29

Downloaded by P. SANTHIYA - CSE (psa.cse@builderscollege.edu.in)


lOMoARcPSD|15656136

OUTPUT:

30

Downloaded by P. SANTHIYA - CSE (psa.cse@builderscollege.edu.in)


lOMoARcPSD|15656136

RESULT:
Thus the Python program was written and executed successfully.

31

Downloaded by P. SANTHIYA - CSE (psa.cse@builderscollege.edu.in)


lOMoARcPSD|15656136

EX NO. 5(b)
COMPONENTS OF AN AUTOMOBILE
DATE:

AIM:
To implementing real-time/technical application using sets.

ALGORITHM:
Step 1: Start
Step 2: Read n
Step 3: Create an empty set
Step 4: Repeat step 5 until n
Step 5: Read cars and add them into the set
Step 6: Print L
Step 7: Repeat step 8 until true
Step 8: Read choice ch
Step 9: If ch==1 then
Read e1 and add that element into the set.
Step 10: If ch==2 then
Read e1 and discard that element from the set
Step 11: If ch==3
If e1 in L
Print Found.
Step 12: If ch==4
Print exit
Step 13: Stop

32

Downloaded by P. SANTHIYA - CSE (psa.cse@builderscollege.edu.in)


lOMoARcPSD|15656136

PROGRAM:

n=int(input("Enter no.of.cars:")) L=set()


for i in range(n): e=input("Enter car name:")
L.add(e)
print(L)
print("List of operation")
print("1.Add a car\n2.Remove a car\n3.Access element\n4.Exit")while
True:
ch=int(input("Enter your choice:"))
if ch==1:
e1=input("Enter a car name to add:")
L.add(e1)
print("Set after adding car",L)
if ch==2:
e1=input("Enter a car name to discard:")
L.discard(e1)
print("Set after discarding car:",L)
if ch==3:
e1=input("Enter a car name to access that car:")
if e1 in L:
print(e1,"Found")else:
print(e1," Not found")if ch==4:
print("Exit")
quit()

33

Downloaded by P. SANTHIYA - CSE (psa.cse@builderscollege.edu.in)


lOMoARcPSD|15656136

OUTPUT:

RESULT:
Thus the Python program was written and executed successfully.

34

Downloaded by P. SANTHIYA - CSE (psa.cse@builderscollege.edu.in)


lOMoARcPSD|15656136

EX NO. 6 (a)
FACTORIAL OF A NUMBER USING FUNCTION
DATE:

AIM:

To write a program in python to find the factorial of a number using function.

ALGORITHM:

Step 1: Start the program.

Step 2: Read the input from the user.

Step 3: Check if the number is positive.

Step 4: Call the function recur_factorial, with input value as an argument.

Step 5: Print the factorial

Step 6: Stop the program

Function
recur_factorial(n)

Step 1: Start the function.

Step 2: If n=1 return n as factorial.

Step 3: Else calculate factorial as n*recur_factorial(n-1) and return factorial.

Step 4: Stop the function.

35

Downloaded by P. SANTHIYA - CSE (psa.cse@builderscollege.edu.in)


lOMoARcPSD|15656136

PROGRAM:
def
recur_factoria
l(n):if n == 1:
retur
nn
else:
return n*recur_factorial(n-1)
print("FACTORIAL OF A NUMBER")
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))

OUTPUT:
Enter a number: 5
The factorial of 5 is 120

RESULT:
Thus the Python program was written and executed successfully.

36

Downloaded by P. SANTHIYA - CSE (psa.cse@builderscollege.edu.in)


lOMoARcPSD|15656136

EX NO. 6 (b)
LARGEST NUMBER IN A LIST USING FUNCTION
DATE:

AIM:
To write a program in python to find the largest number in list using function.

ALGORITHM:
Step 1: Start
Step 2: Read the total number of elements in the list.
Step 3: Read the elements of the list
Step 4: Call the function max_num_in list with list as the input argument
Step 5: Print the largest element in the list.
Step 6: Stop
Function max_num_in_list:
Step 1: Start the function
Step 2: Assign max=list[0] first element of the list
Step 3: For each element in list compare it with max, replace max with the largest value.
Step 4: Return the value of max
Step 5: Stop the function

PROGRAM:

def max_num_in_list( list ):max = list[ 0 ]

for a in list: if a > max:

max = areturn max

list1=[]

print("LARGEST NUMBER IN THE LIST\n")

num = int(input("Enter number of elements in list: "))

37

Downloaded by P. SANTHIYA - CSE (psa.cse@builderscollege.edu.in)


lOMoARcPSD|15656136

for i in range(1, num + 1):

ele = int(input("Enter elements: "))list1.append(ele)

print("The largest number in the list is ",max_num_in_list(list1))

OUTPUT:
LARGEST NUMBER IN THE LIST
Enter number of elements in the list: 5
Enter elements: 25
Enter elements: 1
Enter elements: 99
Enter elements: 56
Enter elements: 33
The largest number in the list is 99

RESULT:
Thus the Python program was written and executed successfully.

38

Downloaded by P. SANTHIYA - CSE (psa.cse@builderscollege.edu.in)


lOMoARcPSD|15656136

EX NO. 6 (c)
AREA OF SHAPE USING FUNCTION
DATE:

AIM:

To write a python program to find area of shape using functions.

ALGORITHM:
Step 1: Start
Step 2: Read the shape for which area is to be calculated.
Step 3: Call the function calculate_area, with shape name has input argument
Step 4: Stop

Function calculate_area:
Step 1: Start
Step 2: If shape is rectangle read the value of length, breath. Calculate and print the area.
Step 3: If shape is square read the value of side length. Calculate and print the area.
Step 4: If shape is triangle read the value of height breath. Calculate and print the
area.
Step 5: If shape is circle read the value of radius then calculate and print area
Step 6: If shape is parallelogram read the value of length,height then calculate and print the area.
Step 7: Else print shape is not available
Step 8: Stop the function

39

Downloaded by P. SANTHIYA - CSE (psa.cse@builderscollege.edu.in)


lOMoARcPSD|15656136

PROGRAM:
def rectangle(l,b):
R=l*b
return R
def square(s):
sq=s*s
return sq
def triangle(b,h):
tri=0.5*b*h
return tri
def circle(r):
pi=3.14
c=pi*r*r
return c
def parallelogram(b,h):
para=b*h
return para
def shape(name):
name=name.lower()
if name =="rectangle":
l=int(input("enter the length value"))
b=int(input("enter the base value"))
R=rectangle(l,b)
print(R)
elif name=="squre":
s=int(input("enter the side value"))
sq=squre(s)
print(sq)
elif name=="triangle":
b=int(input("enter the base value"))
h=int(input("enter the hight value"))
tri=triangle(b,h)
print(tri)
elif name=="circle":
40

Downloaded by P. SANTHIYA - CSE (psa.cse@builderscollege.edu.in)


lOMoARcPSD|15656136

r=int(input("enter the base value"))


c=circle(r)
print(c)
elif name=="parallelogram":
b=int(input("enter the base value"))
h=int(input("enter the hight value"))
para=parallelogram(b,h)
print(para)
name=input("enter the shape name: ")
shape(name)

OUTPUT:
enter the shape name: rectangle
enter the length value5
enter the base value6
30
enter the shape name: square
enter the side value2
4
enter the shape name: triangle
enter the base value2
enter the hight value4
4
enter the shape name: circle
enter the base value3
28.26
Enter the shape name: parallelogram
enter the base value5
enter the hight value2
10

RESULT:
Thus the Python program was written and executed successfully.
41

Downloaded by P. SANTHIYA - CSE (psa.cse@builderscollege.edu.in)


lOMoARcPSD|15656136

EX NO. 7(a)
STRING REVERSE
DATE:

AIM:
To write a program in python for reversing the given string.
ALGORITHM:
STEP 1: Start the program
STEP 2:Get the str
STEP 3: Call the function check_palindrome
STEP 4: if true print It is palindrome
STEP 5: else print It is not palindrome
STEP 6: Stop the program.
FUNCTION check_palindrome:
STEP 1: Start the function
STEP 2: Assign rev_str = reverse of the string
STEP 3: if rev_str is equal to str do
Return True
Else
Return False
STEP 4: Stop the function

PROGRAM:
def check_palindrome(str):
rev_str=str[::-1]
if rev_str==str:
return True
else:
return False
string = input("Enter the string : ")
str = check_palindrome(string)

42

Downloaded by P. SANTHIYA - CSE (psa.cse@builderscollege.edu.in)


lOMoARcPSD|15656136

if str:
print("it is palindrome")
else:
print("it is not palindrome")

OUTPUT:
Enter the string: Tenet
It is not palindrome
Enter the string: tenet
It is palindrome

RESULT:
Thus the Python program was written and executed successfully.

43

Downloaded by P. SANTHIYA - CSE (psa.cse@builderscollege.edu.in)


lOMoARcPSD|15656136

EX NO. 7(b)
STRING PALINDROME
DATE:

AIM:
To write a program in python to check whether the given number is palindrome or not.

ALGORITHM:
STEP 1: Start the program
STEP 2:Get the string
STEP 3: Call the function check_palindrome
STEP 4: if status == 0 print It is palindrome
STEP 5: else print It is not palindrome
STEP 6: Stop the program.

FUNCTION check_palindrome:
STEP 1: Start the function
STEP 2: Assign length = length of the string, first = 0 , last = length – 1, status = 1
STEP 3: while first<last do
If string[first] is equal to string[last] do
First = first + 1
Last = last - 1
Else
status=0
break the loop
return status
STEP 4: Stop the function

44

Downloaded by P. SANTHIYA - CSE (psa.cse@builderscollege.edu.in)


lOMoARcPSD|15656136

PROGRAM:
def check_palindrome(string):
length=len(string)
first=0
last=length-1
status=1
while(first<last):
if(string[first]==string[last]):
first=first+1
last=last-1
else:
status=0
break
return int(status)
string=input ("Enter the string: ")
status=check_palindrome (string)
if status:
print ("It is palindrome")
else:
print ("It is not palindrome")

OUTPUT:
Enter the string: Tenet
It is not palindrome
Enter the string: tenet
It is palindrome

RESULT:
This is a python program to check whether the given number is palindrome or not has been
executed successfully and output got verified.

45

Downloaded by P. SANTHIYA - CSE (psa.cse@builderscollege.edu.in)


lOMoARcPSD|15656136

EX NO. 7(c)
CHARACTER COUNT
DATE:

Aim:

To write a program in python for finding the count of a character in the given string
Algorithm:

Step 1: Start the program.

Step 2: Read the value of the string.

Step 3: Read the character whose count is to be found.

Step 4: For each character in the string, if it is equal to the read character increment sum by 1.

Step 5: Display the total count of the character.

Step 6: Stop the program.

Program:

print("CHARACTER COUNT\n")

print("Enter the String:")

text = input()

print("Enter the Character:")

char = input()

textLen = len(text)

sum = 0

for i in range(textLen):

if char==text[i]:

sum = sum+1

print("\nTotal no: of occurrence of the Given Character is:")

print(sum)

46

Downloaded by P. SANTHIYA - CSE (psa.cse@builderscollege.edu.in)


lOMoARcPSD|15656136

OUTPUT:

Enter the String: google

Enter the Character: o

Total no: of occurrence of the Given Character is: 2

RESULT:
Thus the Python program was written and executed successfully.

47

Downloaded by P. SANTHIYA - CSE (psa.cse@builderscollege.edu.in)


lOMoARcPSD|15656136

EX NO. 8 (a) IMPLEMENTING PROGRAMS USING WRITTEN MODULES AND


DATE: PYTHON STANDARD LIBRARIES FOR EMPLOYEE DETAILS

AIM:

To implement a python program using written modules and python standard libraries.
ALGORITHM:
Step 1: Start the program
Step 2: Import pandas, matplotlib
Step 3: Read excel file that contains employee details
Step 4: Plot histogram using hist() for the Age field.
Step 5: Display the plot
Step 6: Stop

PROGRAM:

import matplotlib.pyplot as plt

import pandas as pd

df=pd.read_excel("D:/emp.xlsx", "Sheet1")

fig=plt.figure()

ax = fig.add_subplot(1,1,1)

ax.hist(df['AGE'],bins = 5)

plt.title('Age distribution')

plt.xlabel('Age')

plt.ylabel('Employee')

plt.show()

“emp.xlsx”

EMPID GENDER AGE SALES


E001 M 35 124
E002 F 23 114
E003 F 56 115
E004 M 34 116
E005 F 42 132
E006 M 46 161

48

Downloaded by P. SANTHIYA - CSE (psa.cse@builderscollege.edu.in)


lOMoARcPSD|15656136

E007 F 45 121
E008 M 23 122
E009 M 34 134
E010 M 12 176

OUTPUT:

RESULT:
Thus the Python program was written and executed successfully.

49

Downloaded by P. SANTHIYA - CSE (psa.cse@builderscollege.edu.in)


lOMoARcPSD|15656136

EX NO. 8 (b)
DATE: IMPLEMENTING PROGRAM USING PANDAS

AIM:

To implement numpy using written modules and Python Standard Libraries

ALGORITHM:
Step 1: Start the program
Step 2: Import numpy library
Step 3: Create alias for numpy
Step 4: Create an array of list
Step 5: Print the array
Step 6: Print the shape of array
Step 7: Stop the program

PROGRAM:
importnumpy as np
a = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])
print(a)
#Slicing in array
b = a[1:, 2:]
print(b)

OUTPUT:
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
(3, 4)
[[ 7 8]
[11 12]]

RESULT:
Thus the program was written and executed successfully.
50

Downloaded by P. SANTHIYA - CSE (psa.cse@builderscollege.edu.in)


lOMoARcPSD|15656136

EX NO. 8(c)
DATE: IMPLEMENTING PROGRAM USING MATPLOTLIB

AIM:

To implement matplotlib using written modules and Python Standard Libraries

ALGORITHM:
Step 1: Install Matplotlib
Step 2: Import pyplot and create alias for it.
Step 3: Define the x-axis and corresponding y-axis values as lists.
Step 4: Plot and name them using plt.xlabel () and plt.ylabel () functions
Step 5: Give a title to your plot using .title () function.
Step 6: Finally to view your plot using show () function.

PROGRAM:
from matplotlib import pyplot as plt
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')
plt.ylabel('Distance (kms)')
plt.title('Information')
plt.show()

51

Downloaded by P. SANTHIYA - CSE (psa.cse@builderscollege.edu.in)


lOMoARcPSD|15656136

OUTPUT:

RESULT:
Thus the Python program was written and executed successfully.

52

Downloaded by P. SANTHIYA - CSE (psa.cse@builderscollege.edu.in)


lOMoARcPSD|15656136

EX NO. 9(a)
COMMAND LINE ARGUMENTS (WORD COUNT)
DATE:

AIM:
To write a python program that take command line arguments (word count).

ALGORITHM:
Step 1: Open Python IDLE, open a new editor window
Step 2: Write a comment line to describe about the program
Step 3: Import the module sys
Step 4: Check the length of the command line argument. If it is less than 2, give a message that the
user has to enter a file name and exit the program.
Step 5: Else, take the second argument as file name and open the file.
Step 6: Read the lines one by one and split the line based on spaces between words.
Step 7: Count the number of words and print the result.
Step 8: Save the file (ctrl+s) with .py extension and Run the module through command
prompt, by executing the command “python filename.py sample.txt.”

PROGRAM:
import sys
iflen(sys.argv)<2:
print("You must enter the file name to count the number of words")
exit
else:
fname=sys.argv[1]
num_words = 0
with open(fname, 'r') as f:
for line in f:
words = line.split()
num_words += len(words)
print("Number of words:")
print(num_words)

53

Downloaded by P. SANTHIYA - CSE (psa.cse@builderscollege.edu.in)


lOMoARcPSD|15656136

OUTPUT:
python countwords.py sample.txt
Number of words:
49

RESULT:
Thus the python program to find the word count using command line arguments was written and
executed successfully.

54

Downloaded by P. SANTHIYA - CSE (psa.cse@builderscollege.edu.in)


lOMoARcPSD|15656136

EX NO. 9(b)
COPY FROM ONE FILE TO ANOTHER FILE
DATE:

AIM:
To write a python program to copy from one file to another.

ALGORITHM:
Step 1: Open Python IDLE, open a new editor window.
Step 2: Import the module sys
Step 3: Open one file called test.txt in read mode.
Step 4: Open another file out.txt in write mode.
Step 5: Read each line from the input file and write it into the output file.
Step 6: Save the file (ctrl+s) with .py extension and Run the module through command prompt, by
executing the command “python filename.py sample.txt.”

PROGRAM:
import sys
file_name = open(sys.argv[2],"w")
with open(sys.argv[1]) as filename:
for line in filename:
file_name.write(line.lower)
print("Files Copied")

OUTPUT:
(Run as C:\Python34>Python Try.py test.txt out.txt)
Files Copied
C:\Python34>

RESULT:
Thus the python program to copy from one file to another file was written and executed
successfully.
55

Downloaded by P. SANTHIYA - CSE (psa.cse@builderscollege.edu.in)


lOMoARcPSD|15656136

56

Downloaded by P. SANTHIYA - CSE (psa.cse@builderscollege.edu.in)


lOMoARcPSD|15656136

EX NO. 10 (a)
DIVIDE BY ZERO
DATE:

AIM:
To implement the real-time/technical applications using Exception handling.

ALGORITHM:
Step 1: Start the program
Step 2: Start a try block, get the dividend and divisor as input.
Step 3: Calculate the result.
Step 4: Create a except block to handle ZeroDivisionError if divisor is zero.
Step 5: Display the result.

PROGRAM:
try:
Dividend = int(input("Enter the dividend"))
Divisor = int(input("Enter the divisor"))
Result=Dividend/Divisor
print("Answer :",Result)
except ZeroDivisionError:
print("Divisor is zero")

OUTPUT:

Enter the dividend 45


Enter the divisor 0
Divisor is Zero

RESULT:
Thus to implement the real-time/technical applications using Exception handling was written and
executed successfully.

57

Downloaded by P. SANTHIYA - CSE (psa.cse@builderscollege.edu.in)


lOMoARcPSD|15656136

EX NO. 10(b)
MARK RANGE VALIDATION
DATE:

AIM:

To implement the real-time/technical applications using Exception handling.

ALGORITHM:

Step 1: Start the program.

Step 2: Start a try block, get mark as input.

Step 3: If mark <0 or mark>100 raise a ValueErrorException

Step 4: Create a except block to handle the ValueErrorException

Step 5: Display the result.

PROGRAM:

try:
mark=int(input("Enter your mark"))
if mark < 0 or mark > 100 :
raise ValueError("Enter a Valid Mark")
except ValueError as err:
print(err)
else:
print("Input Mark is Valid ")

OUTPUT:

Enter your mark -1


Enter a Valid mark

RESULT:
Thus to implement the real-time/technical applications using Exception handling was written and
executed successfully.
58

Downloaded by P. SANTHIYA - CSE (psa.cse@builderscollege.edu.in)


lOMoARcPSD|15656136

EX NO. 11
EXPLORING PYGAME TOOL
DATE:

INTRODUCTION TO PYTHON PYGAME:


Programming via gaming is a teaching tool nowadays. Gaming includes logics, physics, math
and AI sometimes. Python language uses Pygame to carry out the programming. Pygame is the
best module so far, helping in game development. Pygame is a module used to build games that
are usually 2D. Knowing Pygame proficiently can take you far in developing extreme ranges of
games or big games.

What is Pygame?
Something that can be tricky for new developers to understand is that programming languages
seldom exist in a vacuum. When making an Android app for example, you will not only have to
use Java or Kotlin (the two primary programming languages supported by Google) but also
the Android SDK. This is the “software development kit” and it contains a host of different
libraries, classes, and tools that make Java code work on Android and give it access to the features
that are exclusive to mobile platforms.
Syntax and Parameters of Python Pygame

import
pygame
from pygame.locals
import *
PyGame Concepts:
Pygame and the SDL library are portable across different platforms and devices, they
both need to define and work with abstractions for various hardware realities. Understanding
those concepts and abstractions will help you design and develop your own games.
 Initialization and Modules
 Displays and Surfaces
 Images and Rects

Attributes
There are a few attributes in case of Pygame window that we can update. Let’s dive a little into
so that we know about all the options that we have.
 Update the title
 Updating the icon
 Updating the background color

59

Downloaded by P. SANTHIYA - CSE (psa.cse@builderscollege.edu.in)


lOMoARcPSD|15656136

Eg : pygame.Rect attribute
myRect.height Integer value of the height of the rectangle
myRect.size A tuple of two integers: (width, height)
myRect.topleft A tuple of two integers: (left, top)
myRect.topright A tuple of two integers: (right, top)

Installation of PyGame on Windows:


 Start by closing any IDLE or Python window that might be open. This could
include the shell or the program itself. 

Click on the Start menu and open IDLE.

60

Downloaded by P. SANTHIYA - CSE (psa.cse@builderscollege.edu.in)


lOMoARcPSD|15656136

Now click on File at the top and then select Open.

Then double click on Scripts folder and open it.

61

Downloaded by P. SANTHIYA - CSE (psa.cse@builderscollege.edu.in)


lOMoARcPSD|15656136

At the top, you’ll see Scripts written; right click on Scripts and
select Copy address as text.

Go to the Start menu again and open Command Prompt by typing cmd.

62

Downloaded by P. SANTHIYA - CSE (psa.cse@builderscollege.edu.in)


lOMoARcPSD|15656136

Now type cd followed by space and then paste the copied address / location.

After this, press Enter.

63

Downloaded by P. SANTHIYA - CSE (psa.cse@builderscollege.edu.in)


lOMoARcPSD|15656136

Now type pip install pygame like you see on the screen.

64

Downloaded by P. SANTHIYA - CSE (psa.cse@builderscollege.edu.in)


lOMoARcPSD|15656136

Wait for the successful installation message and your PyGame installation is done.

You can test if PyGame has been installed on your Windows OS by typing import
pygame in your IDLE.

65

Downloaded by P. SANTHIYA - CSE (psa.cse@builderscollege.edu.in)


lOMoARcPSD|15656136

If there’s no error, it means PyGame has been successfully installed on your


windows computer.

66

Downloaded by P. SANTHIYA - CSE (psa.cse@builderscollege.edu.in)


lOMoARcPSD|15656136

EX NO. 12
DEVELOPING A GAME ACTIVITY USING PYGAME
DATE:

AIM:
To write a python program to simulate bouncing ball using pygame.

ALGORITHM:
Step 1: Import the necessary files for the implementation of this Pygame.
Step 2: Set the display mode for the screen
usingwindowSurface=pygame.display.set_mode((500,400),0,32)
Step 3: Now set the display mode for the pygame to bounce pygame.display.set_caption(“Bounce”)
Step 4: Develop the balls with necessary colors. BLACK=(0,0,0) WHITE=(255,255,255)
RED=(255,0,0) GREEN=(0,255,0) BLUE=(0,0,255)
Step 5: Set the display information info=pygame.display.Info()
Step 6: Set the initial direction as down.
Step 7: Change the direction from down to up.
Step 8: Then again change the direction from up to down.
Step 9: Set the condition for quit.
Step 10: Exit from the pygame.

67

Downloaded by P. SANTHIYA - CSE (psa.cse@builderscollege.edu.in)


lOMoARcPSD|15656136

PROGRAM:
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.png")
ballrect = ball.get_rect()
while 1:
for event in pygame.event.get():
if event.type ==
pygame.Q
UIT:
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()

68

Downloaded by P. SANTHIYA - CSE (psa.cse@builderscollege.edu.in)


lOMoARcPSD|15656136

OUTPUT:

RESULT:
Thus the Python program was written and executed successfully.

69

Downloaded by P. SANTHIYA - CSE (psa.cse@builderscollege.edu.in)

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy