0% found this document useful (0 votes)
5 views41 pages

Problem Solving and PythonProgramming RECORD

The document outlines various Python programs and algorithms for different tasks including calculating the weight of a steel bar, computing electricity bills, exchanging variable values, circulating values of n variables, calculating distances, generating Fibonacci series, and more. Each exercise includes the aim, algorithm, program code, output, and result indicating successful execution. The document serves as a comprehensive guide for basic Python programming concepts and applications.

Uploaded by

keerthana.t.2k8
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
5 views41 pages

Problem Solving and PythonProgramming RECORD

The document outlines various Python programs and algorithms for different tasks including calculating the weight of a steel bar, computing electricity bills, exchanging variable values, circulating values of n variables, calculating distances, generating Fibonacci series, and more. Each exercise includes the aim, algorithm, program code, output, and result indicating successful execution. The document serves as a comprehensive guide for basic Python programming concepts and applications.

Uploaded by

keerthana.t.2k8
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 41

EX NO: 1A WEIGHT OF STEELBAR

DATE:

Aim:
To write a python program to find the weight of the steel bar.
Algorithm:

Step 1: Start
Step 2: Read the Diameter d
Step 3: Calculate w = (d*d)/162
Step 4: Print d
Step 5: Stop

Program:

d=int(input("Enter the diameter:"))


w=(d*d)/162
print("The Weight of steel bar is ",w)

Output:

Enter the diameter: 5


The Weight of steel bar is 0.15432098765432098

Result:
The Python Program to find the weight of steel bar has been successfully executed
and output is verified.
EX NO: 1B ELECTRICITY BILLING
DATE:

Aim:
To develop an algorithm, flowchart and program to compute electricity bill.

Algorithm:

Step 1 : Start the program


Step 2: Declare total unit consumed by the customer using the variable unit.
Step 3: If the unit consumed 0 to 100 units, calculates the total amount of consumed
is 0
Step 4: If the unit consumed between 100 to 200 units, calculate the total amount of
consumed=(100*1.5)+(unit-100)*2.5)
Step 5: If unit consumed between 200 to 300 units ,calculate total
amountofconsumed=(100*1.5)+(200-100)*2.5+(units- 200)*4
Step 6: If unit consumed between 300-350 units ,calculate total amount
ofconsumed=(100*1.5)+(200-100)*2.5+(300- 200)*4+(units-350)*5
Step7: If the unit consumed above 350 units, fixed charge – 1500/ Step8: Stop
theprogram

Program:

print('''ELECTRICITY BILLING SYSTEM


''')
units=int(input("please enter the number of units you consumed :"))
if(units>0):
if(units>=0 and units<=100):
bill_amount=0
print("Electricity Bill amount is Rs.%.2f"%bill_amount)
elif(units>=100 and units<=200):
bill_amount=(units-100)*1.5
print("Electricity Bill amount is Rs.%.2f"%bill_amount)
elif(units>=200 and units<=500):
bill_amount=(units-200)*3+100*2
print("Electricity Bill amount is Rs.%.2f"%bill_amount )
else:
bill_amount=(units-100)*3.6+100*3.5+300*4.6 print("Electricity Bill
amount is Rs.%.2f"%bill_amount)
else:
print("invalid units entered")

Output:

ELECTRICITY BILLING SYSTEM

please enter the number of units youconsumed: 350


Electrical Bill amount is Rs:650.00

Result:
Thus the algorithm and flow chart to compute electricity bill has been solved.
EX NO : 2A EXCHANGE THE VALUES OF TWO VARIABLES
DATE:

Aim:
To write a python program to exchange the value of two variables.

Algorithm:
Step 1: Start the program
Step 2:Declare two variables
Step 3: Get the value of X,Y
Step 4: Declare a temporary variable temp
Step 5 : Exchange the value of X,Y using temp variable
Step 6: Print the value of X,Y
Step 7: Stop

Program:

x=int(input(“Enter value of x”))


y=int(input(“Enter value of y”))

temp = x
x=y
y = temp

print("Value of x:", x)
print("Value of y:", y)

Output:

Enter value of x 10
Enter value of y 50
Value of x: 50
Value of y: 10

Result:
Thus the python program to exchange the values of two variables was successfully
executed.
EX NO :2B CIRCULATE THE VALUES OF N VARIABLES
DATE :

Aim:
To write a python program to circulate the values of n variables.

Algorithm:
Step 1: Start the program

Step 2:Declare variables and list


Step 3: append values using for loop
Step 4: circulate the values using for loop
Step 5 : stop the program

Program:
n = int(input("Enter number of values : "))
list1 = []
for i in range(0,n,1):
ele = int(input("Enter integer : "))
list1.append(ele)
print("Circulating the elements of list ", list1)
for i in range(0,n,1):
ele =
list1.pop(0)
list1.append(ele)
print(list1)

Output:

Enter number of values : 3


Enter integer : 1
Circulating the elements of list [1]
Enter integer : 2
Circulating the elements of list [1, 2]
Enter integer : 3
Circulating the elements of list [1, 2, 3]
[2, 3, 1]
[3, 1, 2]
[1, 2, 3]

Result:
Thus the python program circulate the values of n variables was successfully executed.
EX NO :2C DISTANCE BETWEEN TWO POINTS
DATE :

Aim:
To write a python program to find the distance between two points.

Algorithm:
Step 1: Start the program
Step 2:Declare the input variables
Step 3: Get the input variables from the user
Step 4 : Calculate the distance using formula ((x2 - x1 )**2) + ((y2-y1)**2) )**0.5
Step 5: Print the result
Step 6: Stop

Program:

x1=int(input("enter x1 : "))
x2=int(input("enter x2 : "))
y1=int(input("enter y1 : "))
y2=int(input("enter y2 : "))
result=((((x2-x1)**2)+((y2-y1)**2))**0.5)
print("Distance : ",result)

OUTPUT:

enter x1 : 4
enter x2 : 6
enter y1 : 0
enter y2 : 6
Distance : 6.324555320336759

Result:
Thus the python program to calculate the distance between two points was successfully executed
EX NO:3A FIBONACCI SERIES
DATE:

Aim:
To write a python program to print the Fibonacci series.
Algorithm:
Step 1: Start the program
Step 2: Get the total numbers of positive terms from the user

Step 3: If the nterms is then 1 then return n2 Else print the Fibonacci
series using while loop count<nterms
Step 4: Print the result
Step 5: Stop

Program:

nterms = int(input(“enter FIBONACCI SERIES


no:”))
n1=0
n2 = 1
count = 0
if nterms <= 0:
print("Please enter a positive integer")
else:
print("Fibonacci sequence upto",nterms,":")
while count < nterms:
print(n1,end=' , ')
nth = n1 + n2
n1 = n2
n2 = nth
count += 1
Output:
enter FIBONACCI SERIES no:10
Fibonacci sequence upto 10 :
0 , 1 , 1 , 2 , 3 , 5 , 8 , 13 , 21 , 34 ,

Result:
Thus the python program to compute Fibonacci series was successfully executed.
EX.NO:3B SIMPLE NUMBER TRIANGLE PATTERN
DATE:

Aim:
To write a python program to print a simple triangle pattern using numbers

Algorithm:
Step 1:Start the program
Step2:Get the number of rows to be printed from the user
Step3: First outer loop is used to handle number of rows and Inner nested loop is used to
handle the number of columns.
Step 4:Manipulating the print statements display the number pattern Step5:
Stop the program

Program:
n = int(input("Enter the number of rows: "))
for i in range(1, n+1):
for j in range(1, i + 1):
print(j, end=' ')
print("")

Output:

1
12
123
1234

Result:
Thus the python program to print a simplenumbertriangle pattern was successfully executed.
EX.NO.3C PROGRAM FOR PYRAMID PATTERN
DATE:

Aim:
To write a python program to print Pyramid pattern
Algorithm:
Step 1:Start the program
Step 2:Get the number of rows to be printed
Step 3: First outer loop is used to handle number of rows and Inner nested loop is used to
handle the number of columns.
Step 4:Manipulating the print statements display the star pattern

Step 5: Stop the program

Program:

rows = 5
for i in range(0, rows): for j in
range(0, i + 1):
print("*", end=' ') print("\r")

for i in range(rows, 0, -1): for j in


range(0, i - 1):
print("*", end=' ') print("\r")
Output:
*

**

***

****

*****

****

***

**

*
Result:
Thus the python program to print pyramid pattern was successfully
Executed.
EX NO :4A FACTORIAL OF A NUMBER
DATE:

Aim:
To write the python program to find out the factorial of a number using functions.

Algorithm:
Step 1: Start the program
Step 2:Get an integer to find the factorial from the user Step
3:Read the integer and assign it to a variable
Step 4:If the integer entered is negative display the message the factorial Step
5:If the value entered is 0 or 1 then the factorial is 1
Step 6:Else calculate the factorial using formula n*factorial(n-1) Step
7:Stop

Program:

def factorial(num):

fact=1

for i in range(1,num+1):
fact=fact*i

return fact

num=int(input("Enter The number: "))


print("The factorial of",num,"is",factorial(num))

Output:
Enter the number: 4
The factorial of 4 is 24

Result:
Thus the python program to calculate factorial of a number was successfully executed.
EX NO :4B AREA OF SHAPES
DATE:

Aim:
To write the python program to find out the area of various shapes using
functions.

Algorithm:
Step 1: Start the program
Step 2:Get the shape for which you want to calculate the area from the user
Step 3:Using conditionals compute the area of square, circle , rectangle and triangle
using formula.
Step 4:Display the area of the shape entered by the user.
Step 5:Stop
Program:

def areacalculator():
val=input("enter the shape you want to calculate area of:") area=0
pie=3.14
if val=="square":
side= int(input("enter the value of side:"))
area=area+(side**2)
print(area)
elif val== "circle":
radius= int(input("enter the value of radius:"))
area=area+(2*pie*radius)
print(area)
elif val== "rectangle":
length= int(input("enter the value of length:"))
width= int(input("enter the value of width:"))
area=area+(length*width)
print(area)
elif val== "triangle": print(area)
base= int(input("enter the value of base:")) height=
int(input("enter the value of height:"))
area=area+(0.5*base*height)
print(area) else:
print("Enter valid shape")
areacalculator()
Output:

enter the shape you want to calculate area of:square enter


the value of side:5
25

Result:
Thus the python program to calculate area of different shapes was successfully executed.
EX NO:5A CHARACTER COUNT
DATE:

Aim:
To write the python program for character count

Algorithm:
Step 1: Start the program
Step 2:Read the input string
Step 3: Calculate the count of the character
Step 4: Print the count and display the output
Step 5:Stop the program

Program:

test_str = "problem solving and python programming laboratory"


c=input("enter the character to check count:")

counter = test_str.count(c)
print("Count of '{}' is :".format(c)+str(counter))

Output:

enter the character to check count:p

Count of 'p' is :3

Result:

Thus the python program to character count was executed successfully and the
output was verified.
EX NO : 5B PALINDROME
DATE:

Aim:
To write the python program to find out whether a given string is a palindrome
or not.

Algorithm:
Step 1: Start the program
Step 2:Read the string
Step 3:Hold the string in a temporary variable.
Step 4: Reverse the string
Step 5:Compare the temporary variable with reversed string.
Step 6:If both letters or numbers are the same, print "this string is a palindrome."
Step 7:Else print, "this string is not a palindrome.
Step 8:Stop the program
Program:

str = input(“Enter a string:”)


a = str.casefold()
rev = reversed(a)
if list(a) == list(rev):
print("PALINDROME !")
else:
print("NOT PALINDROME !")
Output:
Enter a string: madam
PALINDROME !

Enter a string: hello


NOT PALINDROME
Result:

Thus the python program to find out whether a string a given string is
palindrome or not was executed successfully and the output was verified.
EX NO:6 CONSTRUCTION OF A BUILDING USING
LISTS
DATE:

Aim:
To write a python program to perform various operations of list.

Algorithm:
Step 1: Start the program
Step 2: Declare the components of construction using lists

Step 3: Perform the operations of list


Step 4: Display the output
Step 5: Stop

Program:

thislist = ["bricks", "cement", "brush","sand", "Paint"]


print(thislist)
print(len(thislist))
print(thislist[1])
print(thislist[-1])
print(thislist[1:3])
print(type(thislist))
if "cement" in thislist:
print("Yes, 'cement' is in the list")

thislist[1] = "Tiles"
print(thislist)
thislist.insert(2, "bricks")
print(thislist)
thislist.append("butterfly tiles")
print(thislist)
tropical = ["floor", "marbel", "granite"]
thislist.extend(tropical)

print(thislist) thislist.remove("floor")
print(thislist)

thislist.pop(1)

print(thislist) i = 0
whilei<len(thislist):
print(thislist[i])
i=i+1
thislist.sort()
print(thislist)
thislist.sort(reverse=True)
print(thislist)
Output:
['bricks', 'cement', 'brush', 'sand', 'Paint'] 5
cement Paint
['cement', 'brush']
<class 'list'>
Yes, 'cement' is in the list
['bricks', 'Tiles', 'brush', 'sand', 'Paint']
['bricks', 'Tiles', 'bricks', 'brush', 'sand', 'Paint']
['bricks', 'Tiles', 'bricks', 'brush', 'sand', 'Paint', 'butterfly tiles']
['bricks', 'Tiles', 'bricks', 'brush', 'sand', 'Paint', 'butterfly tiles', 'floor', 'marbel', 'granite']
['bricks', 'Tiles', 'bricks', 'brush', 'sand', 'Paint', 'butterfly tiles', 'marbel', 'granite']
['bricks', 'bricks', 'brush', 'sand', 'Paint', 'butterfly tiles', 'marbel', 'granite'] bricks
bricks
brushsand
Paint
butterfly tiles
marbel granite
['Paint', 'bricks', 'bricks', 'brush', 'butterfly tiles', 'granite', 'marbel', 'sand']
['sand', 'marbel', 'granite', 'butterfly tiles', 'brush', 'bricks', 'bricks', 'Paint']

Result:
Thus the python program to execute operations of lists was successfully
executed.
EX NO: 7 COMPONENTS OF A CAR USING TUPLES
DATE:

Aim:
To write the python program to perform components of car using tuples

Algorithm:
Step 1: Start the program
Step 2: Declare the components of car using tuples

Step 3: Perform the operations of tuples


Step 4: Display the output
Step 5: Stop

Program:

thistuple = ("Steering wheel", "Seat belt", "Speedometer", “Battery","Windscreen") print(thistuple)


print(len(thistuple))
print(type(thistuple))
print(thistuple[1])
print(thistuple[-1])
print(thistuple[2:5])
print(thistuple[:4])
print(thistuple[2:])
print(thistuple[-4:-1])
if "Seat belt" in thistuple:
print("Yes, 'Seat belt' is in the tuple")

y = list(thistuple)
y[1] = "kiwi"
thistuple = tuple(y)
print(thistuple)
y = list(thistuple)
y.append("Brakes")
thistuple=tuple(y)
print(thistuple)
y = list(thistuple)
y.remove("Battery")
thistuple = tuple(y)
print(thistuple)
i=0
while i < len(thistuple):

print(thistuple[i])
i=i+1
print(thistuple)

Output:
('Steering wheel', 'Seat belt', 'Speedometer', 'Battery', 'Windscreen')

5
<class 'tuple'>
Seat belt
Windscreen
('Speedometer', 'Battery', 'Windscreen')
('Steering wheel', 'Seat belt', 'Speedometer', 'Battery')
('Speedometer', 'Battery', 'Windscreen')
('Seat belt', 'Speedometer', 'Battery')
Yes, 'Seat belt' is in the tuple
('Steering wheel', 'kiwi', 'Speedometer', 'Battery', 'Windscreen')

('Steering wheel', 'kiwi', 'Speedometer', 'Battery', 'Windscreen', 'Brakes')


('Steering wheel', 'kiwi', 'Speedometer', 'Windscreen', 'Brakes')
Steering
wheel
kiwi
Speedometer

Windscreen Brakes
('Steering wheel', 'kiwi', 'Speedometer', 'Windscreen', 'Brakes')

Result:
Thus the python program to execute operations of tuples was successfully executed.
EX NO:8 OPERATIONS OF SET
DATE:

Aim:
To write the python program to operations of set.
Algorithm:

Step 1: Start the program


Step 2: Declare add_set
Step 3: Do update and remove elements in set
Step 4: Perform operations of set
Step 5: Display the output
Step 6: Stop

Program:

add_set={0,1,2,3} print(add_set)
add_set.update('4','5')
print("\n after adding element",add_set)
add_set.remove(0)
print("\n after removing element",add_set)
A = {0, 2, 4, 6, 8}
B = {1, 2, 3, 4, 5}
print("\nUnion :", A | B)
print ("\nIntersection :", A & B)
print ("\nDifference :", A - B)
print("\nSymmetric difference :", A ^ B)
Output:

{0, 1, 2, 3}
after adding element {0, 1, 2, 3, '5', '4'}
after removing element {1, 2, 3, '5', '4'}
Union : {0, 1, 2, 3, 4, 5, 6, 8}
Intersection : {2, 4}
Difference : {0, 8, 6}
Symmetric difference : {0, 1, 3, 5, 6, 8}

Result:
Thus the python program to operations of set was successfully executed.
EX NO :9 OPERATIONS OF DICTIONARY
DATE:

Aim:
To write the python program to operations of dictionary
Algorithm:

Step 1: Start the program


Step 2: Declare the list of languages

Step 3: create and update the key value


Step 4: adding nested key and deleting specific key
Step 5: Display the output
Step 6: Stop

Program:

Dict = {}

print("Empty Dictionary: ")

print(Dict)

Dict[0] = 'python'

Dict[2] = 'java'

Dict[3]= „c‟

print("\
nDictionaryafteradding 3
elements: ")

print(Dict)
Dict['Value_set'] = 2, 3, 4

print("\nDictionary after adding 3 elements: ")

print(Dict)

Dict[2] = 'Welcome'

print("\nUpdated key value: ")

print(Dict)

Dict[5] = {'Nested' :{'1' : 'Life', '2':


'python'}} print("\nAdding a NestedKey:
")

print(Dict)
print("\nAccessing a element using key:")
print(Dict[0])

print(Dict[5]['Nested'])
del Dict[3]

print("\nDeleting a specific key: ")

print(Dict)

pop_ele = Dict.pop(5)

print('\nDictionary after deletion: ' + str(Dict))

print('\nValue associated to poped key is: ' + str(pop_ele))


Output:

Empty Dictionary:

{}

Dictionary after adding 3 elements:

{0: 'python', 2: 'java', 3: 1}

Dictionary after adding 3 elements:

{0: 'python', 2: 'java', 3: 1, 'Value_set': (2, 3, 4)}

Updated key value:

{0: 'python', 2: 'Welcome', 3: 1, 'Value_set': (2, 3, 4)}

Adding a Nested Key:

{0: 'python', 2: 'Welcome', 3: 1, 'Value_set': (2, 3, 4), 5: {'Nested': {'1': 'Life', '2': 'python'}}}

Accessing a element using key:

python

{'1': 'Life', '2': 'python'}

Deleting a specific key:

{0: 'python', 2: 'Welcome', 'Value_set': (2, 3, 4), 5: {'Nested': {'1': 'Life', '2': 'python'}}}

Dictionary after deletion:

{0: 'python', 2: 'Welcome', 'Value_set': (2, 3, 4)}

Value associated to poped key is:

{'Nested': {'1': 'Life', '2': 'python'}}


Result:
Thus the python program to operations of dictionary was successfully executed.

COPY FROM ONE FILE TO ANOTHER USING FILE


EX NO:10A
HANDLING

DATE:

Aim:
To write a python program to implement copy from one file to another using FileHandling

Algorithm:

Step 1: Start the program.

Step 2: Declare the variables sfile,tfile


Step 3: Read the values sfile

Step 4: create tfile and copy text from sfile


Step 5: display file copied Successfully

Step 6: Stop the program.

Program:

print("Enter the Name of Source File:


") sFile = input()

print("Enter the Name of Target File:


") tFile = input()

fileHandle = open(sFile, "r")


texts = fileHandle.readlines()
fileHandle.close()

fileHandle = open(tFile, "w")


for s in texts:
fileHandle.write(s)
fileHandle.close()

print("\nFile Copied Successfully!")


Output:

Enter the Name of Source File:


test.txt
Enter the Name of Target File:
test2.txt

File Copied Successfully!

Result:
Thus the program to copy from one File to another using File Handling is executed
and the output is verified.
EX NO:10B FIND THE LONGEST WORD IN A FILE
DATE:

Aim:
To write a python program to implement Find the longest word in a File

Algorithm:

Step 1: Start the program.

Step 2: create test.txt file manually in python software file location

Step 3: Declare the fin and Read the file and find max length in a file

Step 4: display longest word using for loop

Step 5: Stop the program.

Program:

fin = open("test.txt","r")

str = fin.read()

words =str.split()
max_len =len(max(words,key=len)) for
word in words:

if len(word)==max_len:

longest_word =word

print(“longest word in your file is:”,longest_word)


Output:

longest word in your file is: students

Result:
Thus the program to Find the longest word in a File is executed and the output is verified.
EX NO:11A DIVIDE BY ZERO ERROR USING EXCEPTION
HANDLING
DATE:

Aim:
To write a python program to implement Divide by zero using Exception handling

Algorithm:

Step 1: Start the program.


Step 2: Declare the variables a,b,c

Step 3: Read the values a,b


Step 4: Inside the try block check the condition.
Step 5: Catch the exception and display the appropriate message.
Step 6: Stop the program.

Program:
a = int(input(“Enter a:”)
b = int(input(“Enter b:”)
c = a/b
print(“c:”,c)
except
print("Can't divide with zero")
Output:

Enter a:25 Enter


b:0
Can’t divide with zero

Result:
Thus the program to execute divide by zero is executed and the output is verified.
VOTER’S AGE VALIDITY USING EXCEPTION
EX NO: 11B
HANDLING
DATE:

Aim:
To write a python program to implement voter’s age validity using Exception handling

Algorithm:
Step 1: Start the program.

Step 2: Declare the variables to get the input age from user

Step 3: Inside the try block print the eligibility to vote based on the condition
Step 4: Catch the exception and display the appropriate message.

Step 5: Stop the program.

Program:
def main():
age=int(input("Enter your age:"))
if age>18:
print("Eligible to vote") else:
print("Not eligible to vote")
except:

print("age must be a valid number")

main()
Output:
Enter your age: 21

Eligible to vote

Enter your age: a

age must be a valid number

Result :
Thus the program to implement student mark validation using exception handling isexecuted
and the output is obtained
EX NO:12 PANDAS
DATE:

Aim:
To write a python program to print the series using an inbuilt package pandas.

Algorithm:
Step 1: Start the program

Step 2: Import the pandas package

Step 3: Using pd.series operation from pandas print the series

Step 4: Display the output

Step 5:Stop the program

Program:
import pandas as pd
A=[“python”,‟maths”,‟physics”,‟chemistry”,‟english”]

df=pd.Series(A)

print(df)

Output:
0 python
1 maths
2 physics
3 chemistry
4 English
dtype : object

Result:
Thus the python program to print a series using pandas was executed
successfully and the output was verified.
EX NO: 13 NUMPY
DATE:

Aim:
To write a python program to perform matrix addition using an inbuilt package
numpy.

Algorithm:
Step 1: Start the program
Step 2: Import the numpy package
Step 3: Get the input array to perform matrix addition
Step 4: Using np.add operation perform matrix addition for the input numbers
Step 5: Print the output matrix
Step 6:Stop the program

Program:

import numpy as np
from matplotlib import pyplot as plt

x = np.arange(3,21) y = 2
*x+8

plt.title("NumPy Array Plot") plt.plot(x,y)


plt.show()

Output:

Result:
python program to perform matrix addition using numpy was executed successfully and the output
was verified.
EX NO: 14 MATPLOTLIB
DATE:

Aim:
To write a python program to plot a graph using an inbuilt package matplotlib.

Algorithm:
Step 1: Start the program
Step 2: Import the matplotlib package
Step 3: Get the input array to plot the graph
Step 4: Using plt.plot operation plot the numbers graph
Step 5: Display the graph using plt.show()
Step 6:Stop the program

Program:

import matplotlib.pyplot as plt

xdata=['A','B','C']
ydata=[1,3,5]

plt.bar(range(len(xdata)),ydata)
plt.title('BarPlot')
plt.show()

Output:

Result:
Thus the python program to plot a graph using matplotlib was executed
successfully and the output was verified.
EX NO: 15 SCIPY
DATE:

Aim:
To write a python program to perform integration using an inbuilt package scipy.

Algorithm:
Step 1: Start the program
Step 2: Import the scipy package
Step 3: Get the input function to perform integration
Step 4:
Perform the integration operation
Step 5: Display the output

Step 6: Stop the program

Program:

from scipy.integrate import quad def f(x):


return 3.0*x*x + 1.0
I, err = quad(f, 0, 1) print(I)
print(err)

Output:
2.0
2.220446049250313e-14

Result:

Thus the python program to perform integration using scipy was executed
successfully and the output was verified
EX NO: 16 BOUNCING BALL 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 bounce
ball game
Step 2: Set the display mode for the screen using

Step 3: Now set the caption for the pygame

Step 4: Open the image using pygame.image.load() method and set the ball rectangle
boundary using get_rect() method.
Step 5: Set the speed of the ball

Step 6: Create an infinite loop to make ball move


Step7: Reverse the direction of the ball if it hits the
edge

Step8: Fill the surface background color using fill()


Step9:Render the object on screen using blit()
Step10:Make the entire image visible using
pygame.display.flip()

Step 11: Set the condition for quit.


Step 12: stop the program
Program:

import turtle

wn=turtle.Screen()
wn.bgcolor("white")
wn.title("ball")

ball = turtle.Turtle()
ball.shape("circle")
ball.color("red")

ball.penup()
ball.speed(0)
ball.goto(0,200)
ball.dy = 0
gravity = 0.1

while True:
ball.dy -=gravity
ball.sety(ball.ycor() + ball.dy)

if ball.ycor() < -300:


ball.dy *= -1

Output:

Result:
Thus the program to simulate bouncing ball using pygame is executed and the output is
sobtained.

You might also like