0% found this document useful (0 votes)
39 views83 pages

PSPP Manual

GE3171-Problem solving and python programming laboratory manual

Uploaded by

josephsamuel1274
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)
39 views83 pages

PSPP Manual

GE3171-Problem solving and python programming laboratory manual

Uploaded by

josephsamuel1274
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/ 83

SUN COLLEGE OF ENGINEERING AND

TECHNOLOGY
UDAYA NAGAR, VELLAMODI

KANYAKUMARI DISTRICT

RECORD NOTE BOOK

Reg. No:

Name :
Semester :
Department :
Subject Name :
Subject Code :
SUN COLLEGE OF ENGINEERING AND
TECHNOLOGY
UDAYA NAGAR, VELLAMODI
Kanyakumari District

Bonafide Certificate

This is to certify that this bonafide record of work was done by


Mr./Ms register no in the
GE3171- PROBLEM SOLVING AND PYTHON PROGRAMMING LABORATORY during
Semester.

Staff - in - charge Head of the Department

University Reg. No …………………………………….


University Examination held in ………………………

Internal Examiner External Examiner


LIST OF EXPERIMENTS

S.NO DATE List of experiments Mark Page No Signature


EXNO: 1 A
ELECTRICITY BILL
DATE:

AIM:
To write a program for generating electricity bill using python.

ALGORITHM:
Step1: Start
Step 2: Declare total unit consumed by the customer using the variable unit.
Step 3: If the unit consumed less or equal to 100 units, calculates the total amount of
consumed=units*1.5
Step 4: If the unit consumed between 100 to 200 units, calculates the total amount of
consumed=(100*1.5)+(unit-100)*2.5)
Step 5: If unit consumed between 200 to 300 units, calculates total amount of
consumed=(100*1.5)+(200-100)*2.5+(units-200)*4
Step 6: If unit consumed between 300-350 units, calculates total amount of
consumed=(100*1.5)+(200-100)*2.5+(300-200)*4+(units-350)*5
Step 7: If the unit consumed above 350 units, fixed charge - 1500/
Step 8: End
FLOWCHART:

start

read units

If(units Payamount=units*1.5
<=100) Fixed charge=25

yes
Payamount=(100*1.5)+(unit-100)*2.5
If(units
<=200 Fixed charge=25

no

yes Payamount=(100*1.5)+(200-100)*2.5+(units-200)*4
If(units
<=300 Fixed charge=75

no

yes
If(units Payamount=(100*1.5)+(200-100)*2.5+(300-
200)*4+(units-
<=350
300)*5, Fixed

no
Payamount=0

Fixed charge=1500

total= Payamount +Fixedcharge

Print total

stop
PROGRAM:

units=int(input("Enter the number of units you consumed in a month:"))


if(units<=100):
payAmount=units*1.5
fixedcharge=25.00
elif(units<=200):
payAmount=(100*1.5)+(units-100)*2.5
fixedcharge=50.00
elif(units<=300):
payAmount=(100*1.5)+(200-100)*2.5+(units-200)*4
fixedcharge=75.00
elif(units<=350):
payAmount=(100*1.5)+(200–100)*2.5+(300–200)*4+(units-300)*5
fixedcharge=100.00
else:
payAmount=0
fixedcharge=1500.00
Total=payAmount+fixedcharge;
print("\nElecticity bill=%.2f" %Total)

OUTPUT:
Enter the number of units you consumed in a month:100
Electricity bill = 175.00

RESULT:
Thus the program for generating electricity has been written and executed successfully.
EXNO: 1 B
WEIGHT OF THE STEEL BAR
DATE:

AIM:
To write a python program for calculating weight of the steel bar.

ALGORITHM:
Step 1: Start
Step 2: Read the values for the density and volume of the steel bar.
Step 3: Calculate the weight using the formula weight=volume * density.
Step 4: Print the values.
Step 5: End.
FLOW CHART:

start

Read density, volume

weight=(density*volume)/1000

Print( weight)

stop
PROGRAM:

Density=float(input("Enter the density of the steel:"))


Volume=float(input("Enter the volume of the steel:"))
Weight=Volume*Density
print ("The weight of the steel bar is", Weight/1000,"Kg")

OUTPUT:
Enter the density of the steel: 1000
Enter the volume of the steel: 10
The weight of the steel bar is 10.0 Kg

RESULT:
Thus the program for calculating weight of the steel bar has been written and executed
successfully.
EXNO: 1 C
SINE SERIES
DATE:

AIM:
To write a python program for finding sum of sine series.

ALGORITHM:
Step 1: Start
Step 2: Take in the value of x in degrees and the number of terms and store it in separate variables.
Step 3: Pass these values to the sine function as arguments.
Step 4: Define a sine function and using a for loop, first convert degrees to radians.
Step 5: Then use the sine formula expansion and add each term to the sum variable.
Step 6: Then print the final sum of the expansion.
Step 7: Exit.
FLOW CHART:

start

Read x, n, i=0, sine=0

Sign=(-1)**i, pi=22/7, y=x*(pi/180)


if(i<=n)
Sine+=((y**(2.0*i+1))/math.facorial(2*i+1))*sign
yes

no

Print(rount(sin(x,n),

stop
PROGRAM:

import math
def sin(x,n):
sine = 0
for i in range(n):
sign = (-1)**i
pi=22/7
y=x*(pi/180)
sine = sine + ((y**(2.0*i+1))/math.factorial(2*i+1))*sign
return sine
x=int(input("Enter the value of x in degrees:"))
n=int(input("Enter the number of terms:"))
print(round(sin(x,n),2))

OUTPUT 1:
Enter the value of x in degrees:30
Enter the number of terms:10
0.5
OUTPUT 2:
Enter the value of x in degrees:45
Enter the number of terms:15
0.71

RESULT:
Thus the program for finding sum of sine series has been written and executed successfully.
EXNO: 2 A
EXCHANGE THE VALUES OF TWO VARIABLES
DATE:

AIM:
To write a python program for exchange the values of two variables.
ALGORITHM:
Step 1: Start
Step 2: Declare a variable a,b and temp as integer.
Step 3: Read two numbers a and b.
Step 4: temp=a
Step 5: a=b
Step 6: b=temp.
Step 7: Print a and b.
Step 8: Stop.
FLOW CHART:

start

Read a,b

temp=a

a=b

b=temp

Print(x and y)

stop
PROGRAM:
a= int (input ("Enter the value for a="))
b= int (input ("Enter the value for b="))
print("Before swapping a={0},b={1}".format(a,b))
temp=a
a=b
b=temp
print("After swapping a={0},b={1}".format(a,b))

OUTPUT:
Enter the value for a 10
Enter the value for b 20
Before swapping a=10,b=20
After swapping a=20,b=10

RESULT:
Thus the program for exchange the values of two variables have been written and executed
successfully.
EXNO: 2 B
CIRCULATE THE VALUES OF N VARIABLES
DATE:

AIM:
To write a python program for circulating the values of n variables using function.
ALGORITHM:
Step 1: Start
Step2: Define a List named list.
Step 3: Get the input n value to rotate the values.
Step 4: Perform the following Step b=a[n:]+a[:n], using slice operator
Step 5: Print the rotated values.
Step 6: Stop
FLOW CHART:

start

Get example list

Print(original list)

Read rotate(l,n)

Rotate_list=l[n:]+l[n:]

Print(Rotate_list)

stop
PROGRAM:
def circulate(A,N):
for i in range(1,N+1):
B=A[i:]+A[:i]
print("Circulation ",i,"=",B)
return
A=[91,92,93,94,95]
N=int(input("Enter n:"))
circulate(A,N)

OUTPUT:
Enter n:5
Circulation 1 = [92, 93, 94, 95, 91]
Circulation 2 = [93, 94, 95, 91, 92]
Circulation 3 = [94, 95, 91, 92, 93]
Circulation 4 = [95, 91, 92, 93, 94]
Circulation 5 = [91, 92, 93, 94, 95]

RESULT:
Thus the program for circulating the values of n variables has been written and executed
successfully.
EXNO: 2 C
DISTANCES BETWEEN TWO POINTS
DATE:

AIM:
To write a python program for calculating the distance between two points.
ALGORITHM:
Step 1: Start
Step 2: Take a two points as an input from an user.
Step 3: Calculate the difference between the corresponding X-coordinates
Step 4: X2 - X1 and Y-coordinates. Y2 - Y1 of two points.
Step 5: Print the values
Step 6: Stop
FLOW CHART:

start

Read(x1,y1),(x2,y2)

Z1=(x1-x2)**2

Z2=(y1-y2)**2

distance = math.sqrt( z1+z2)

Print(distance)

stop
PROGRAM:
import math
x1 = int(input("Enter a x1: "))
y1 = int(input("Enter a y1: "))
x2 = int(input("Enter a x2: "))
y2 = int(input("Enter a y2: "))
distance = math.sqrt(((x2-x1)**2)+((y2-y1)**2))
print("Distance = ",distance)

OUTPUT:
Enter a x1: 3 Enter a y1: 2

Enter a x2: 7 Enter a y2: 8

Distance = 7.211102550927978

RESULT:
Thus the python program for calculating the distance between two points has been
written and executed successfully.
EXNO: 3 A
NUMBER PATTERNS
DATE:

AIM:
To write a python program for displaying the number pattern.
ALGORITHM:
Step 1: Start
Step2: Define the depth value
Step 3: Outer loop will print number of rows
Step 4: Inner loop will print the value of i after each iteration
Step 5: Print number
Step 6: Line after each row to display pattern correctly
Step 7: Stop
FLOWCHART:

start

Read depth

For number in range(depth)

For i in range(number)

Print(number)

stop
PROGRAM:
depth = 6
for number in range(depth):
for i in range(number):
print(number, end=" ")
print(" ")

OUTPUT:
1
22
333
4444
55555

RESULT:
Thus the program for displaying the number pattern has been written and executed
successfully.
EXNO: 3 B
INCREMENTING NUMBER PATTERN PROBLEMS
DATE:

AIM:
To write a python program for displaying the incrementing number pattern.
ALGORITHM:
Step 1: Start
Step 2: Initialize x=0 and perform the operation
Step 3: Reassign it x=x+1 to increment a variable value by 1.
Step 4: Print x then the output will appear
Step 5: The value of x is incremented by 1
Step 6: Stop
FLOWCHART:
start

Read number=0,depth

for number in range(1,depth)

for i in range(1, number+1)

Print(i )

stop
PROGRAM:
depth = 6
for number in range(1, depth):
for i in range(1, number + 1):
print(i, end=' ')
print(" ")

OUTPUT:
1
12
123
1234
12345

RESULT:
Thus the program for displaying the incrementing number pattern has been written and
executed successfully.
EXNO: 3 C PYRAMID PATTERNPROBLEMS WITH STARS
DATE:

AIM:
To write a python program for displaying pyramid pattern with star.
ALGORITHM:
Step 1: Start
Step 2: rows = input("Enter the number of rows: ")
Step 3: # Outer loop will print the number of rows.
Step 4: for i in range(0, rows):
Step 5: # This inner loop will print the stars.
Step 6: for j in range(0, i + 1):
Step 7: print("*", end=' ')
Step 8: # Change line after each iteration.
Step 9: print(" ")
Step 10: Stop
FLOW CHART:

start

Read number=0,depth

for number in range(1,depth)

For i in range(1, number+1)

stop
PROGRAM:
def diamond(n):
for m in range(0, n):
for i in range(0, m+1):
print("* ",end="")
print("\n")
n=5
diamond(n)

OUTPUT:
*
**
***
****
*****

RESULT:
Thus the program for displaying pyramid pattern with star has been written and executed
successfully.
EXNO: 3 D INVENTED SEMI-PYRAMID PATTERN PROBLEM WITH
DATE: DESENDING ORDER OF NUMBERS

AIM:
To write a program for printing invented semi-pyramid pattern problem with descending order
of numbers.
ALGORITHM:
Step 1: Start
Step 2: Define the depth value
Step 3: Reversed loop for downward inverted pattern
Step 4: Increment in count after each iteration
Step 5: Print number
Step 6: Start
FLOWCHART:

start

Read

for i in range(depth,0,-1)

n=i

for j in range(0, i):

Print(n )

stop
PROGRAM:
depth = 5
for i in range(depth,0,-1):
n=i
for j in range(0, i):
print(n, end=' ')
print("\n")

OUTPUT:
55555
4444
333
22
1

RESULT:
Thus the program for printing invented semi-pyramid pattern problem with descending order of
numbers has been written and executed successfully.
EXNO: 3 E
STAR PATTERN
DATE:

AIM:
To write a python program for displaying star pattern.
ALGORITHM:
Step 1: Start
Step 2: Read the n value
Step 3: Find k is used to print the space
Step 4: Outer loop to print number of rows
Step 5: Inner loop is used to print number of space
Step 6: Decrement in k after each iteration
Step 7: This inner loop is used to print stars
Step 8: Downward triangle Pyramid
Step 9: Output for downward triangle pyramid
Step 10: Inner loop will print the spaces
Step 11: Increment in k after each iteration
Step 12: This inner loop will print number of stars
Step 13: Stop
FLOWCHART: start

Read n

for i in range(0, n)

for j in range(0, i+1)

Print(* )

Print(‘’ )

for i in range(n,0,-1)

for j in range(0, i-1)

Print(* )

Print(‘’ )

stop
PROGRAM:
n = int(input('Enter the number:'))
for i in range(0, n):
for j in range(0, i+1):
print("*",end= ' ')
print(„‟)
for i in range(n, 0, -1):
for j in range(0, i-1):
print('* ', end= '')
print('')

OUTPUT:
*
**
***
****
*****
******
*****
****
***
**
*

RESULT:
Thus the program for displaying star pattern has been written and executed successfully.
EXNO: 4 IMPLEMENTING REALTIME /TECHNICAL APPLICATION
DATE: USING LIST, TUPLES

AIM:
To write program for implementing real time/technical application using list, tuple.
ALGORITHM:
Step 1: Start
Step2: Get the library items in the form of list
Step 3: Get the car items in the form of list
Step 4: Perform list operations on that list
Step 5: Checking of elements in the list
Step 6: Update element on the list
Step 7: Add and remove element in the list
Step 8: Same operations also check in tuple
Step 9: Start
PROGRAM:
print("Using list")
library=["books", "periodicals", "newspapers", "manuscripts", "films","maps", "prints","documents",
"microform", "CDS", "cassettes","videotapes", "DVDs","Blu-ray Discs", "e-books",
"audiobooks","databases"]
car=["engine","battery","transmission","steering","brakes","videoplayers","sensors"]
construction=["cement","steel","concrete","wires","sand","bricks"]
keyword=input("Enter what you need from library: ")
count=0
for i in range(len(library)):
if (library[i]==keyword):
count=count+1
if count>=1:
print("Item you needed from library is available. Visit library to collect it")
else:
print("Sorry, Not available")
keyword=input("Enter the components you looking for in a car: ")
count=0
for i in range(len(car)):
if (car[i]==keyword):
count=count+1
if count>=1:
print("Component you looking in a car is available")
else:
print("Sorry, Not available")
keyword=input("Enter your required component for a construction: ")
count=0
for i in range(len(construction)):
if (construction[i]==keyword):
count=count+1
if count>=1:
print("Your required component is available. Contact us for more details")
else:
print("Sorry, Not available")
print("\nItems in library: ",library)
print("\nComponents of a car: ",car)
print("\nMaterials required for construction: ",construction)

print("Using tuples")
library=("books", "periodicals", "newspapers", "manuscripts", "films","maps", "prints","documents",
"microform", "CDS", "cassettes”, “videotapes", "DVDs","Blu-ray Discs", "e-books", "audiobooks",
"databases")
car=("engine","battery","transmission","steering","brakes","videoplayers","sensors")
construction=("cement","steel","concrete","wires","sand","bricks")
keyword=input("Enter what you need from library: ")
count=0
for i in range(len(library)):
if (library[i]==keyword):
count=count+1
if count>=1:
print("Item you needed from library is available. Visit library to collect it")
else:
print("Sorry, Not available")
keyword=input("Enter the components you looking for in a car: ")
count=0
for i in range(len(car)):
if (car[i]==keyword):
count=count+1
if count>=1:
print("Component you looking in a car is available")
else:
print("Sorry, Not available")
keyword=input("Enter your required component for a construction: ")
count=0
for i in range(len(construction)):
if (construction[i]==keyword):
count=count+1
if count>=1:
print("Your required component is available. Contact us for more details")
else:
print("Sorry, Not available")
print("\nItems in library: ",library)
print("\nComponents of a car: ",car)
print("\nMaterials required for construction: ",construction)
OUTPUT:
Using list
Enter what you need from library: books
Item you needed from library is available. Visit library to collect it
Enter the components you looking for in a car: steering
Component you looking in a car is available
Enter your required component for a construction: sand
Your required component is available. Contact us for more details
Items in library: ['books', 'periodicals', 'newspapers', 'manuscripts', 'films', 'maps', 'prints', 'documents',
'microform', 'CDS', 'cassettes', 'videotapes', 'DVDs', 'Blu-ray Discs', 'e-books', 'audiobooks', 'databases']
Components of a car: ['engine', 'battery', 'transmission', 'steering', 'brakes', 'videoplayers', 'sensors']
Materials required for construction: ['cement', 'steel', 'concrete', 'wires', 'sand', 'bricks']
Using tuples
Enter what you need from library: audiobooks
Item you needed from library is available. Visit library to collect it
Enter the components you looking for in a car: brakes
Component you looking in a car is available
Enter your required component for a construction: concrete
Your required component is available. Contact us for more details
Items in library: ("books", "periodicals", "newspapers", "manuscripts", "films", "maps", "prints",
"documents", "microform", "CDS", "cassettes”, “videotapes", "DVDs", "Blu-ray Discs", "e-books",
"audiobooks", "databases")
Components of a car: ("engine","battery","transmission","steering","brakes","videoplayers","sensors")
Materials required for construction: ("cement", "steel", "concrete", "wires", "sand", "bricks")

RESULT:
Thus the program for implementing real time/technical application list, tuple has been written
and executed successfully.
EXNO: 5 A IMPLEMENTING REAL TIME /TECHNICAL APPLICATION
DATE: USING DICTIONARIES

AIM:
To write a python program for implementing real time/technical application using dictionaries.

ALGORITHM:
Step 1: Start
Step2: Perform dictionary operations
Step 3: Checking of elements
Step 4: Update element
Step 5: Add and remove element
Step 6: Stop
PROGRAM:
print("Search")
print("Display")
print("Update")
print("Insert")
op=input ("Select the operation to do")
automobile= {1:"engine",2:"battery",3:"transmission",4:"steering",5:"brakes", 6:"video
players",7:"sensors"}
if op=="Search":
keyword=input ("Enter the parts of automobile you looking for: ")
count=0
for dict_key, dict_value in automobile.items():
if (dict_value==keyword):
count=count+1
if count>=1:
print ("Component you looking in a car is available")
else:
print ("Sorry, Not available")
elif op=="Display":
for dict_key, dict_value in automobile.items():
print(dict_key,'->',dict_value)
elif op=="Insert":
key=input ("Enter a key")
value=input ("Enter a value")
automobile. update({key:value})
print(automobile)
elif op=="Update":
key=input ("Enter a key to update a value")
value=input ("Enter a value")
automobile[key]=value
print (automobile)
else:
print ("Please enter Correct option")
OUTPUT:
Search
Display
Update
Insert
Select the operation to do= search
Enter the parts of automobile you looking for: engine
Component you looking in a car is available
Select the operation to do= insert
Enter a key8
Enter a value tire
{1: 'engine', 2: 'battery', 3: 'transmission', 4: 'steering', 5: 'brakes', 6: 'video players', 7: 'sensors', '8': '
tire'}

RESULT:
Thus the program for implementing real time/technical application using dictionary has been
written and executed successfully.
EXNO: 5 B IMPLEMENTING REAL TIME / TECHNICAL
DATE: APPLICATION USING SETS

EXNO: 5 B DATE:

AIM:
To write a python program for implementing real time/technical application using sets.

ALGORITHM:
Step 1: Start
Step 2: Perform set operations.
Step 3: Insert elements.
Step 4: Insert set of element.
Step 5: remove element.
Step 6: Stop
PROGRAM:
language={"c","c++","python","java","HTML","PHP","JavaScript"}
print("Display items in set:")
for x in language:
print(x)
print ("Before insert:",language)
language.add("Node js")
print ("After insert= ",language)
print ("Before Update:",language)
new_value=["React js","MySQL"]
language.update(new_value)
print ("After Update = ",language)
print ("Before remove:",language)
language.remove("python")
print ("After remove = ",language)
OUTPUT:
Display items in set:
java
HTML
JavaScript
c++
python
PHP
c
Before insert: {'java', 'HTML', 'JavaScript', 'c++', 'python', 'PHP', 'c'}
After insert= {'java', 'HTML', 'JavaScript', 'c++', 'python', 'PHP', 'Node js', 'c'}
Before Update: {'java', 'HTML', 'JavaScript', 'c++', 'python', 'PHP', 'Node js', 'c'}
After Update = {'java', 'HTML', 'JavaScript', 'c++', 'React js', 'python', 'PHP', 'Node js', 'MySQL', 'c'}
Before remove: {'java', 'HTML', 'JavaScript', 'c++', 'React js', 'python', 'PHP', 'Node js', 'MySQL', 'c'}
After remove = {'java', 'HTML', 'JavaScript', 'c++', 'React js', 'PHP', 'Node js', 'MySQL', 'c'}

RESULT:
Thus the program for implementing real time/technical application in sets has been written and
executed successfully.
EXNO: 6 A
FACTORIAL OF A NUMBER
DATE:

AIM:
To write a python program for finding factorial of number using function.
ALGORITHM:
Step 1: Start
Step 2: Read a number n
Step 3: Initialize variables: i = 1, fact = 1
Step 4: if i<= n go to Step 4 otherwise go to Step 7
Step 5: Calculate fact = fact * i
Step 6: Increment the i by 1 (i=i+1) and go to Step 3
Step 7: Print fact
Step 8: Stop
PROGRAM:
def fact(n):
if n==1:
return n
else:
return n*fact(n-1)
num = int(input("Enter a number: "))
print("The factorial of",num,"is",fact(num))

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

RESULT:
Thus the program for finding factorial of number has been written and executed successfully.
EXNO: 6 B
FINDING LARGEST NUMBER IN A LIST USING FUNCTION
DATE:

AIM:
To write a python program for finding largest number in a list using function.

ALGORITHM:
Step 1: Define a function myMax.
Step 2: Take a list from the user.
Step 3: Find the maximum element in the list using max function.
Step 4: Display the result.
PROGRAM:
def myMax(list1):
print("Largest element is:",max(list1))

list1=[]
num=int(input("Enter number of elements in list: "))
for i in range(1, num + 1):
ele=int(input("Enter elements: "))
list1.append(ele)
print("Largest element is:", myMax(list1))

OUTPUT:
Enter number of elements in list: 4
Enter elements: 56
Enter elements: 3
Enter elements: 45
Enter elements: 23
Largest element is: 56
Largest element is: None

RESULT:
Thus the program for finding largest number in a list using function has been written and
executed successfully.
EXNO: 6 C
FINDING AREA OF CIRCLE
DATE:

AIM:
To write a python program to find the area of a circle using functions.
ALGORITHM:
Step 1: Define the function findArea.
Step 2: Assign the constant value PI to 3.142.
Step 3: Get the radius input from the user.
Step 4: Calculate the area of circle using PI * r * r and
return the value.

Step 5: Print the output.


Step 6: End
PROGRAM:

def findArea(r):
PI=3.142
return PI*(r*r);

num=float(input("Enter r value:"))
print("Area is %.6f" % findArea(num))

OUTPUT:

Enter r value:8
Area is 201.088000

RESULT:
Thus the program for finding the area of circle has been written and executed
successfully.
EXNO: 7 A
STRING REVERSE
DATE:

AIM:
To write a python program for displaying string reverse pattern.
ALGORITHM:
Step 1: Start
Step 2: Read the string from the user
Step 3: Calculate the length of the string
Step 4: Initialize rev = " " [empty string]
Step 5: Initialize i = length - 1
Step 6: Repeat until i>=0:
rev = rev + Character at position 'i' of the string
i=i-1
Step 7: Print rev
Step 8: Stop
PROGRAM:
def reverse(string):
string = "".join(reversed(string))
return string

s=input("Enter any string: ")


print("The original string is : ",end="")
print(s)

print("The reversed string(using reversed) is : ",end="")


print(reverse(s))

OUTPUT:
Enter any string: python
The original string is : python
The reversed string(using reversed) is : nohtyp

RESULT:
Thus the program for displaying string reverse pattern has been written and executed
successfully.
EXNO: 7 B
PALINDROMES
DATE:

AIM:
To create a python program to check given string is palindrome or not.

ALGORITHM:
Step 1: Start
Step 2: Read the string from the user
Step 2: Using string.casfold
PROGRAM:
string=input("Enter string: ")
string=string.casefold()
rev_string=reversed(string)
if list(string)==list(rev_string):
print("It is palindrome")
else:
print("It is not palindrome")

OUTPUT:
Enter string: python
It is not palindrome

RESULT:
Thus the program to check whether given string is palindrome or not has been written and
executed successfully.
EXNO: 7 C
CHARACTER COUNTS
DATE:

AIM:
To create a python program to count the character in a string.
ALGORITHM:
Step 1: Define a string.
Step 2: Define and initialize a variable count to 0.
Step 3: Iterate through the string till the end and for each character except spaces, increment the count
by 1.
Step 4: To avoid counting the spaces check the condition i.e. string[i] != ' '.
PROGRAM:
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 counting the character in a string has been written and executed
successfully.
EXNO: 7 D
REPLACING CHARECTERS
DATE:

AIM:
To write a python program to replace the string with another.
PROGRAM:
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: Hello world
Please Enter your Own Character: rl
Please Enter the New Character: r
Original String: Hello world
Modified String: Hello word

RESULT:
Thus the program for replacing the string with another string has been written and executed
successfully.
EXNO: 8 A
PANDAS
DATE:

AIM:
Write a Pandas program to add, subtract, multiple and divide two Pandas Series.

PROGRAM:
import pandas as pd
ds1 = pd.Series([2, 4, 6, 8, 10])
ds2 = pd.Series([1, 3, 5, 7, 9])
ds = ds1 + ds2
print("Add two Series:")
print(ds)
print("Subtract two Series:")
ds = ds1 - ds2
print(ds)
print("Multiply two Series:")
ds = ds1 * ds2
print(ds)
print("Divide Series1 by Series2:")
ds = ds1 / ds2
print(ds)
OUTPUT:
Add two Series:
0 3
1 7
2 11
3 15
4 19
dtype: int64Subtract two Series:
0 1
1 1
2 1
3 1
4 1
dtype: int64Multiply two Series:
0 2
1 12
2 30
3 56
4 90
dtype: int64Divide Series1 by Series2:
0 2.000000
1 1.333333
2 1.200000
3 1.142857
4 1.111111
dtype: float64>

RESULT:
Thus the program for creating pandas has been written and executed successfully.
EXNO: 8 B
SCIPY
DATE:

AIM:
To write a program to create scipy.

PROGRAM:
import numpy as np
from scipy import io as sio
array = np.ones((4, 4))
sio.savemat('example.mat', {'ar': array})
data = sio.loadmat('example.mat', struct_as_record=True)
data['array']

OUTPUT:
Array ([[ 1., 1., 1., 1.],
[ 1., 1., 1., 1.],
[ 1., 1., 1., 1.],
[ 1., 1., 1., 1.]])

RESULT:
Thus the program for creating scipy has been written and executed successfully.
EXNO: 8 C MATPLOTLIB
DATE:

AIM:
To write a Python programming to create a pie chart of the popularity of programming
Languages.

PROGRAM:
import matplotlib.pyplot as plt
languages = 'Java', 'Python', 'PHP', 'JavaScript', 'C#', 'C++'
popuratity = [22.2, 17.6, 8.8, 8, 7.7, 6.7]
colors = ["#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#9467bd", "#8c564b"]
explode = (0.1, 0, 0, 0,0,0)
plt.pie(popuratity, explode=explode, labels=languages, colors=colors,
autopct='%1.1f%%', shadow=True, startangle=140)
plt.axis('equal')
plt.show()
OUTPUT:

RESULT:
Thus the program for printing plot has been written and executed successfully.
EXNO: 8 D NUMPY
DATE:

AIM:
To write a python program to create numpy.

PROGRAM:
import numpy as np
X = np.array([11, 28, 72, 3, 5, 8])
print(X)
print(S.values)
# both are the same type:
print(type(S.values), type(X))

OUTPUT:
[11 28 72 3 5 8]
[11 28 72 3 5 8]

RESULT:
Thus the program for to creating numpy has been written and executed successfully.
EXNO: 9 A FILE COPY
DATE:

AIM:
To write a python program to Copy the contents of the source file to destination file using
copyfile module.
ALGORITHM:
Step 1: Start
Step 2: Import the copyfile module from shutil.
Step 3: Enter the source and destination file names.
Step 4: Copy the contents of the source file to destination file using copyfile module.
Step 5: End.
PROGRAM:
from shutil import copyfile
sourcefile = input("Enter source file name: ")
destinationfile = input("Enter destination file name: ")
copyfile(sourcefile, destinationfile)
print("File copied successfully!")
print("Contents of destination file :")
FileRead = open(destinationfile, "r")
print(FileRead.read())
FileRead.close()

OUTPUT:
Contents of the file "A.txt":
Hello world!
Execution:
Enter source file name: A.txt
Enter destination file name: B.txt
File copied successfully!
Contents of destination file:
Hello world!
Contents of the file "B.txt" after execution:
Hello world!

RESULT:
Thus the program for Copying the contents of the source file to destination file using
copyfile module has been written and executed successfully.
EXNO: 9 B
WORD COUNT
DATE:

AIM:
To write a python program to count the string in a file.
ALGORITHM:
Step 1: Start.
Step 2: Import the Counter module from collections.
Step 3: Read the file.
Step 4: Split the word using split() function.
Step 5: Count the words using Counter.
Step 6: End.
PROGRAM:
from collections import Counter
FileName = input("Enter the file name : ")
CntFile = open(FileName, 'r')
print("Number of words in the file :")
print(Counter(CntFile.read().split()))
CntFile.close()

OUTPUT:
Contents of the file "test.txt":
hi hello and welcome
Execution:
Enter the file name : test.txt
Number of words in the file :
Counter({'hi': 1, 'hello': 1, 'and': 1, 'welcome': 1})

RESULT:
Thus the program for counting the string in a file has been written and executed successfully.
EXNO: 9 C
LONGEST WORD IN FILE
DATE:

AIM:
To write a python program to create longest word in file.
ALGORITHM:
Step 1: Start.
Step 2: Read the file from which the longest word is to be found.
Step 3: Compare all the words in the file and find the maximum length.
Step 4: Print the longest word.
Step 5: End.
PROGRAM:
deflongest_word(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]
file_name=input("Enter the file name:")
print(longest_word(file_name))

OUTPUT:
Contents of the file "test.txt":
hi hello and welcome
Execution:
Enter the file name:test.txt
['welcome']

RESULT:
Thus the program for creating longest word in file has been written and executed successfully.
EXNO: 10A IMPLEMENTING REAL TIME /TECHNICAL

DATE: APPLICATION USING EXCEPTION


HANDLING DIVIDE BY ZERO

AIM:
To write a program for implementing real time /technical application using exception handling
divide by zero.
ALGORITHM:
Step 1: We will take inputs from the user, two numbers.
Step 2: If the entered data is not integer, throw an exception.
Step 3: If the remainder is 0, throw divide by zero exception.
Step 4: If no exception is there, return the result.
PROGRAM:
try:
num1 = int(input("Enter First Number: "))
num2 = int(input("Enter Second Number: "))
result = num1 / num2
print(result)
except ValueError as e:
print("Invalid Input Please Input Integer...")
except ZeroDivisionError as e:
print(e)

OUTPUT 1:
Enter First Number: abc
Invalid input please input integer...
OUTPUT 2:
Enter First Number: 43
Enter First Number: 0
Division by zero
OUTPUT 3:
Enter First Number: 331 2
Enter First Number: 4
83.0

RESULT:
Thus the program for implementing real time / technical application using exception handling
divide by zero has been written and executed successfully.
EXNO: 10 B IMPLEMENTING REAL TIME /TECHNICAL

DATE: APPLICATION USING EXCEPTION HANDLING


VOTER’S AGE VALIDITY

AIM:
To write a python program to for implementing real time /technical application using exception
handling voter‟s age validity.
.
ALGORITHM:
Step 1: Start
Step 2: Accept the age of the person.
Step 3: If age is greater than or equal to 18, then display 'You are eligible
to vote'.
Step 4: If age is less than 18, then display 'You are not eligible to vote'.
Step 5: Stop
PROGRAM:
def main():
try:
age=int(input("Enter your age"))
if age>18:
print("Eligible to vote")
else:
print("Not eligible to vote")
#display exception's default error message
except ValueError as err:
print(err)
except:
print("An Error occured")
print("rest of the code...")
main()

OUTPUT:
Enter your age 30
Eligible to vote
OUTPUT:
Enter your age thirty
Invalid literal for int() with base 10: ' thirty'
Rest of the code.

RESULT:
Thus the program for implementing real time /technical application using exception handling
voter‟s age validity has been written and executed successfully.
EXNO: 11 PYGAME
DATE:

AIM:
To write a python program for simulate elliptical orbits using pygame.

ALGORITHM:
Step 1: Import the required packages
Step 2: Set up the colours for the elliptical orbits
Step 3: Define the parameters to simulate elliptical orbits
Step 4: Display the created orbits
PROGRAM:
import pygame
import math
import sys
pygame.init()
screen = pygame.display.set_mode((600, 300))
pygame.display.set_caption("Elliptical orbit")
clock = pygame.time.Clock()
while(True):
for event in pygame.event.get():
if (event.type == pygame.QUIT):
sys.exit()
xRadius = 250
yRadius = 100
for degree in range((0,360,10)):
x1 = int(math.cos(degree * 2 * math.pi / 360) * xRadius) + 300
y1 = int(math.sin(degree * 2 * math.pi / 360) * yRadius) + 150
screen.fill(0, 0, 0)
pygame.draw.circle(screen, (255, 0, 0), [300, 150], 35)
pygame.draw.ellipse(screen, (255, 255, 255), [50, 50, 500, 200], 1)
pygame.draw.circle(screen, (0, 0, 255), [x1, y1], 15)
pygame.display.flip()
clock.tick(5)
OUTPUT:

RESULT:
Thus the program for simulate elliptical orbits using pygame has been written and executed
successfully.
EXNO: 12
SIMULATE BOUNCING BALL USING PYGAME
DATE:

AIM:
To write a python program for simulate bouncing ball using pygame.
ALGORITHM:
Step 1: Import the necessary files for the implementation of thisPygame.
Step 2: Set the display mode for the screen using window Surface= pygame.
display.set_mode((500,400),0,32)
Step 3: Now set the display mode for the pygame to bouncepygame. 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 upto down.
Step 9: Set the condition for quit.
Step 10: Exit from the pygame.
PROGRAM:
import os
os.environ['PYGAME_HIDE_SUPPORT_PROMPT'] = "hide"
import sys, pygame

from pygame.locals import *


pygame.init()
speed = [1, 1]
color = (255, 250, 250)

width = 550
height = 300
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("Pygame bouncing ball")
ball = pygame.image.load("ball.png")

rect_boundry = ball.get_rect()
while 1:
for event in pygame.event.get():
rect_boundry = rect_boundry.move(speed)
if rect_boundry.left < 0 or rect_boundry.right > width:
speed[0] = -speed[0]
if rect_boundry.top < 0 or rect_boundry.bottom > height:

speed[1] = -speed[1]
screen.fill(color)

screen.blit(ball, rect_boundry)
pygame.display.flip()

if event.type == QUIT:
pygame.quit()
sys.exit()
OUTPUT:

RESULT:
Thus the program for bouncing ball using pygame has been written and executed successfully.

You might also like