Download as pdf or txt
Download as pdf or txt
You are on page 1of 52

EX.

NO: 1 Identification and solving of simple real life or scientific or technical


problems and developing flow charts for the same. (Electricity Billing, Retail
DATE: shop billing, Sin series, weight of motorbike, Weight of a steel bar, compute
Electrical Current in Three Phase AC Circuit, etc.)

AIM:

To write a Python Programto Calculate Electricity Bill

ALGORITHM:

Step 1: 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: Display the calculated electricity charges.
Step 9: Stop

1
FLOW CHART:

Star

Read Units

yes
If unit<50

amount = units * elif units<=100


2.6surcharge =25

yes no

amount = 130 + ((units - 50) * 3.25) amount = 130 + 162.50 + 526 + ((units -
200) * 8.45)) surcharge = 75

Stop

2
PROGRAM:

units = int(input(" Please enter Number of Units you Consumed : "))if(units < 50):
amount = units *
2.60surcharge = 25
elif(units <= 100):

amount = 130 + ((units - 50) * 3.25)

surcharge = 35else:
amount = 130 + 162.50 + 526 + ((units - 200) * 8.45)

surcharge = 75

total = amount + surcharge print("\nElectricity


Bill = %.2f" %total)

3
OUTPUT:

Please enter Number of Units you Consumed: 75


Electricity Bill: 246.25

RESULT:

Thus the python program for Electricity Bill was calculated successfully.

4
1b. Retail shop billing

AIM:

To write an algorithm and flowchart to Retail shop billing.

ALGORITHM:

Step 1: Start
Step 2: Scan the product as item
Step 3: IF Scanned Properly then proceed else goto to Step 2
Step 4: Add item to the list
Step 5: Bill = Sum of all items in the list
Step 6: If the item is the last then proceed else goto to step 2
Step 7: Calculate discount by Dis = bill*2/100
Step 8: Bill = Bill – Dis
Step 9: Print the Bill
Step 10: Stop

5
Start

Scan the Item

IF (Scan>1)

Add item to list

Bill = Sum of all items in list

IF (item
is last)

IF
(Bill>=10
00)

Dis =Bill*2/100

Bill = Bill - Dis

Print the Bill

Stop

RESULT:

Thus the algorithm and flowchart to Retail shop billing was written successfully.

6
EX.NO: 2 Python programming using simple statements and expressions (exchange
the values of two variables, circulate the values of n variables, distance
DATE: between two points).

2a.EXCHANGE THE VALUES OF TWO VARIABLES

AIM:
To write a python program to exchange the values of two variables

ALGORITHM:

Step 1.Start
Step 2.Read the variable a,b,temp.
Step 3.temp=a;a=b;b=temp;
Step 4.Print the value a,b.
Step 5.Stop

PROGRAM:

P = int( input("Please enter value for P: "))


Q = int( input("Please enter value for Q: "))
# To swap the value of two variables
# we will user third variable which is a temporary variable
temp_1 = P
P=Q
Q = temp_1
print ("The Value of P after swapping: ", P)
print ("The Value of Q after swapping: ", Q)

7
OUTPUT:

Please enter value for P: 2

Please enter value for Q: 3

The Value of P after swapping: 3

The Value of Q after swapping: 2

RESULT:

Thus the program to exchange/swap two values was written and executed successfully.

8
2b. DISTANCE BETWEEN TWO POINTS

AIM:
To write a python program to find distance between two Output points.

ALGORITHM:

Step 1: Start
Step 2: Enter the values of x1,x2,y1,y2

Step 3: Calculate the distance between two points using formula√(𝑥2 − 𝑥1)2 + (𝑦2 − 𝑦1)^2
Step 4: Display the result
Step 5: 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 between",(x1,x2),"and",(y1,y2),"is : ",result)

9
OUTPUT:

enter x1 : 4
enter x2 : 3
enter y1 : 5
enter y2 : 6
distance between (4, 3) and (5, 6) is : 1.4142135623730951

RESULT:

Thus the python program to find distance between two Output points was writtenand
executed successfully.

10
2c. CIRCULATE THE VALUES OF N VARIABLES

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

ALGORITHM:

Step 1: Start

Step 2: Get the list

Step 3: Compute for i in range (1,len(a),1):

Step 4: Print (a[i:]+a[:i])

Step 5: Stop.

PROGRAM:

a=list(input("enter the list"))print(a)

for i in range(1,len(a),1):

print(a[i:]+a[:i])

11
OUTPUT:
Enter the list '1234'['1', '2', '3', '4']

['2', '3', '4', '1']

['3', '4', '1', '2']

['4', '1', '2', '3']

RESULT:

Thus the python program to circulate the values of n variables was written
and executed successfully.

12
EX.NO: 3
Scientific problems using Conditionals and Iterative loops. (Number
DATE: series, pyramid pattern)

3a. NUMBER SERIES

AIM:
To write a python program to find number series to Fibonacci numbers.

ALGORITHM:

Step 1: Start
Step 2: Read the variable n
Step 3: Assign the value a=0 and b=1
Step 4: If n equal to 1 then print a
Step 5: Else print a and b
Step 6: Initialize 2 to n
Step 7: If I less than 2 go to step 11
Step 8: If I less than n continue else go to step 11
Step 9: Assign c equal to a+b. Then assign a = b and b = c.
Step 10: Print the value of variable c
Step 11: Stop

13
PROGRAM:

n = int(input("How many terms? "))


a=0
b=1
if n==1:
print(a)
else:
print(a)
print(b)
for I in range(2,n):
c=a+b
a=b
b=c
print(c)

14
OUTPUT:

How many terms? 7


Fibonacci sequence:
0
1
1
2
3
5
8

RESULT:

Thus the python program to find number series was written and executed successfully

15
3b. PYRAMID PATTERN

AIM:
To write a python program to find pyramid patterns.

ALGORITHM:

Step 1: Start the program


Step 2: Read the n value
Step 3: Call pypart(n)
Step 4: Initialize i to 0
Step 5: If i is less than n then continue else goto step 9
Step 6: Initialize j to 0
Step 7: Increment j and goto step 8
Step 8: Print *
Step 9: Stop

PROGRAM:

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

16
OUTPUT:

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

RESULT:

Thus the python program to find Pyramid pattern was written and executed successfully

17
EX.NO: 4 Implementing real-time/technical applications using Lists, Tuples. (Items
present in a library/Components of a car–operations of list & tuples)
DATE:

4a. IMPLEMENTING REAL-TIME/TECHNICAL APPLICATIONS USING LISTS ITEMS


PRESENT IN A LIBRARY

AIM:
To write a python program to implement real-time/technical applications using Lists, (Items
present in a library)

ALGORITHM:

Step 1: Start
Step 2: Initialize the Value in the list
Step 3: find the length of list
Step 4: Read the element to Insert in a list
Step 5: Read the element to POP in a list
Step 6: Read the element to Sort in a list
Step 7: Stop

PROGRAM 1:(LIST)

books=['C', 'C++', 'PYTHON']


print("Currently No of books available : ",len(books))
pos1 = int(input("Enter the pos to insert: "))
element = input("Enter the element to insert: ")
books.insert(pos1,element)
print("After insertion updated book list is","\n",books)
print("Currently No of books available : ",len(books))
pos2 = int(input("Enter the pos to delete: "))
books.pop(pos2)
print("After deletion updated list is","\n",books)
print("Currently No of books available : ",len(books))
books.sort(reverse=true)
print("AFter sorting the book title", len)

18
OUTPUT 1:

Currently No of books available: 3


Enter the pos to insert: 2
Enter the element to insert: abacus
After insertion updated book list is
['C', 'C++', 'abacus', 'PYTHON']
Currently No of books available: 4
Enter the pos to delete: 1
After deletion updated list is
['C', 'abacus', 'PYTHON']
Currently No of books available: 3
AFter sorting the book title ['abacus','C', 'PYTHON',]

RESULT:

Thus the python program to implement real time technical application using list item
present in a Library was written and executed successfully.

19
4b. IMPLEMENTING REAL-TIME/TECHNICAL APPLICATIONS USING TUPLES ITEMS
PRESENT IN A LIBRARY

AIM:
To write a python program to implement real-time/technical applications using Tuples,
(Items present in a library)

ALGORITHM:

Step 1: Start
Step 2: Initialize the Value in the Tuple
Step 3: find the length of Tuple
Step 4: Print the length of the book by using len ()
Step 5: Print the Maximum price of the book by using max ()
Step 6: Print the Minimum price of the book by using min ()
Step 7: Stop

PROGRAM 1:(TUPLES)

books=('C', 'C++', 'JAVA', 'C')


bookPrice=(1200,500, 1250)
print("Currently No of books available : ",len(books))
print("Maximum Book Price is ",max(bookPrice))
print("Minimum Book Price is ",min(bookPrice))
print("Enter book name to find how many copies of specified book available in the library")
countBook =input()
print(books.count(countBook))

20
OUTPUT:

Currently No of books available: 4


Maximum Book Price is 1250
Minimum Book Price is 500
Enter book name to find how many copies of specified book available in the library
JAVA
1

RESULT:

Thus the python program to implement real time technical application using Tuples item
present in a Library was written and executed successfully

21
EX.NO: 5
Implementing programs using Functions. (Factorial, largest number in a
DATE: list, area of shape)

AIM:
To write a python program to find Factorial Numbers..

ALGORITHM:

Step 1:Start
Step 2:Read the number
Step 3:If n<0 then print factorial does not exist
Step 4: Elseif n==0 then print the factorial of 0 is 1
Step 5: Else call factorial(n)
Step 6: Stop
Factorial(n)
Step 1: If n==1 then return n
Step 2: Else F=n*factorial(n-1)
Step 3: return F

PROGRAM:

def recur_factorial(n):
if n == 1:
return n
else:
return n*recur_factorial(n-1)
num = int(input("Enter a number: "))
if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
print("The factorial of",num,"is",recur_factorial(num))

22
OUTPUT:

Enter a number: 8
The factorial of 8 is 40320

Enter a number: 5
The factorial of 5 is 120

RESULT:

Thus the python program to find Factorial number was written and executed successfully.

23
EX.NO: 6
Implementing programs using Functions. (Factorial, largest number in a
DATE: list, area of shape)

AIM:

To write a Python program for Calculating Areas Of some mathematical Shapes.

ALGORITHM:

Step 1: Start
Step 2: Read the name of the shape to calculate area
Step 3: Call respective function to find area of shape
Step 4: If name exists, read the input values and calculate area
Step 5: Else print shape is not available
Step 6: Stop
PROGRAM:

defcalculate_area(name):
name =name.lower()
ifname =="rectangle":
l =int(input("Enter rectangle's length: "))
b =int(input("Enter rectangle's breadth: "))
rect_area =l *b
print("The area of rectangle is”,rect_area)
elifname =="square":
s =int(input("Enter square's side length: "))
sqt_area =s *s
print("The area of square is”,sqt_area)
elifname =="triangle":
h =int(input("Enter triangle's height length: "))
b =int(input("Enter triangle's breadth length: "))
tri_area =0.5*b *h
print("The area of triangle is”,tri_area)
elifname =="circle":
r =int(input("Enter circle's radius length: "))
pi =3.14
circ_area =pi *r *r
print("The area of triangle is”,circ_area)
elifname =='parallelogram':
b =int(input("Enter parallelogram's base length: "))
h =int(input("Enter parallelogram's height length: "))
para_area =b *h
print("The area of parallelogram is”,para_area)
else:
print("Sorry! This shape is not available")
print("Calculate Shape Area")
shape_name =input("Enter the name of shape whose area you want to find: ")
calculate_area(shape_name)

24
OUTPUT:

Calculate Shape Area


Enter the name of shape whose area you want to find: rectangle
Enter rectangle's length: 10
Enter rectangle's breadth: 15
The area of rectangle is 150.

RESULT:

Thus the python program to find area of shape was written and executed successfully

25
EX.NO: 7 Implementation of program using strings.(reverse,character count,
palindrome)
DATE:

7a.REVERSE CHARACTER

AIM:

To write a Python program for reverse character using sting

ALGORITHM:

Step 1: Start
Step 2: Read the string
Step 3: Call the function reverse
Step 4: If length of the string is zero goto step 7
Step 5: Else reverse the string using recursion
Step 6: Print the reversed string
Step 7: Stop

PROGRAM:

defreverse(s):
iflen(s) ==0:
returns
else:
returnreverse(s[1:]) +s[0]

s ="Geeksforgeeks"

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


print(s)

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


print(reverse(s))

26
OUTPUT:

The original string is: Computer


The reversed string (using recursion) is: retupmoC

RESULT:

Thus the python program to find reverse character using sting was written and executed
successfully

27
7b. CHARACTER COUNT

AIM:

To write a Python program for character count using string.

ALGORTIHM:

Step 1: Start
Step 2: Read the string
Step 3: Use for loop to iterate every character in a string
Step 4: Increment the total value
Step 5: Print The total number of string
Step 6: Stop

PROGRAM:

str1 = input("Please Enter your Own String : ")


total = 0
for i in str1:
total = total + 1
print ("Total Number of Characters in this String = ", total)

28
OUTPUT:

Please Enter your Own String : Hi Computer


Total Number of Characters in this String = 11

RESULT:

Thus the python program to find character count using sting was written and executed
successfully .

29
7c. PALINDROME

AIM:

To write a Python program for Palindrome character using sting

ALGORITHM:

Step 1: Start
Step 2: Read the string
Step 3: Call function is Palindrome to reverse the string
Step 4: Check if reverse and original or same or not.
Step 5: If true print Yes else print No
Step 6: Stop

PROGRAM:
def is Palindrome(s):

return s == s[::-1]

s = "Malayalam"

ans = is Palindrome(s)

if ans:

print ("The given string is palindrome")

else:

print ("Not a palindrome")

30
OUTPUT:

MALAYALAM
The given string is palindrome

RESULT:

Thus the python program to find Palindrome character using sting was written and
executed successfully

31
EX.NO: 8 Implement program using written modules and python standard
libraries(pandas, numpy, Matplotlib, scipy)
DATE:

AIM:

To write program using written modules and python standard libraries (pandas, numpy,
Matplotlib, scipy)

import pandas as pd
a = [1, 7, 2]
myvar = pd.Series(a)
print(myvar)

OUTPUT:

0 1
1 7
2 2
dtype: int64

Key/Value Objects as Series


You can also use a key/value object, like a dictionary, when creating a Series.

Example
Create a simple Pandas Series from a dictionary:

import pandas as pd
calories = {"day1": 420, "day2": 380, "day3": 390}
myvar = pd.Series(calories)
print(myvar)

Output:

day1 420
day2 380
day3 390
dtype: int64

32
import pandas as pd
a = [1, 7, 2]
my var = pd.Series(a, index = ["x", "y", "z"])

Output:
x 1
y 7
z 2
dtype: int64
print(myvar)

Example
Iterate on the elements of the following 1-D array:

import numpy as np
arr = np.array([1, 2, 3])
for x in arr:
print(x)

Output:
1
2
3

Example
Iterate on the elements of the following 2-D array:

import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
for x in arr:
print(x)

Output:
[1 2 3]
[4 5 6]

Example
Draw a line in a diagram from position (0,0) to position (6,250):

import matplotlib.pyplot as plt


import numpy as np
xpoints = np.array([0, 6])
ypoints = np.array([0, 250])

33
plt.plot(xpoints, ypoints)
plt.show()

Output:

Example
Draw a line in a diagram from position (1, 3) to position (8, 10):

import matplotlib.pyplot as plt


import numpy as np
xpoints = np.array([1, 8])
ypoints = np.array([3, 10])
plt.plot(xpoints, ypoints)
plt.show()

import numpy as np
from scipy.sparse.csgraph import connected_components
from scipy.sparse import csr_matrix
arr = np.array([
[0, 1, 2],
[1, 0, 0],
[2, 0, 0]
])
newarr = csr_matrix(arr)
print(connected_components(newarr))

34
Output:
(1, array([0, 0, 0], dtype=int32))

import numpy as np
from scipy.sparse.csgraph import dijkstra
from scipy.sparse import csr_matrix
arr = np.array([
[0, 1, 2],
[1, 0, 0],
[2, 0, 0]
])

newarr = csr_matrix(arr)
print(dijkstra(newarr, return_predecessors=True, indices=0))

Output:
(array([ 0., 1., 2.]), array([-9999, 0, 0], dtype=int32))

RESULT:

To write program using written modules and python standard libraries (pandas,
numpy, Matplotlib, scipy) and executed successfully.

35
EX.NO: 9 Implementing real –time/technical applications using file handling (copy
from one file to another, word count, longest word)
DATE:

9a. WORD COUNT

AIM:

To write a python program for takes command line arguments (word count).
.

ALGORITHM:

Step 1: Openthe file in read modeand handle it in text mode.


Step 2: Readthetext using read() function.
Step 3: Split the text using space separator. We assume that words in a sentenceare separated bya space
character.
Step 4: The lengthofthe split list should equalthe number ofwords in the text file.
Step 5: You can refine the count by cleaning the string prior to splitting or validating the words after
splitting.

Text File(data.txt):

Memory refers to the processes that are used to acquire, store, retain, and later retrieve
information

PROGRAM:

file = open("C:\data.txt", "rt")


data = file.read()
words = data.split()

print('Number of words in text file :', len(words))

36
OUTPUT:

Number of words in text file: 16

RESULT:

Thus the program takes command line arguments (word count)was written
and executed successfully.

37
9b. COPY FROM ONE FILE TO ANOTHER FILE

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

ALGORITHM:
Step 1: Start

Step 2: Open one file called test.txt in read mode.

Step 2: Open another file out.txt in write mode.

Step 3: Read each line from the input file and write it into the output file.

Step 4: Stop

PROGRAM:

with open("test.txt") as f:
with open("out.txt", "w") as f1:
for line in f:
f1.write(line)

38
OUTPUT:

Contents of file (test.txt):

Hello world

Output (out.text):

Hello world

RESULT:

Thus the program for copy one file from to another file waswritten and
executed successfully.

39
9c. FIND THE MOST FREQUENT WORDS IN A TEXT READ FROM A FILE

AIM:

To write a python program for find the most frequent words in a text read from a
file.

ALGORITHM:

Step 1: Program file and text file save to system same location.
Step 2: Read a line from the file.
Step 3: Check each word in the line count the occurrence from text file and check if end of file
has reached.
Step 4: Display the words along with the count from file.
Step 5: End.

PROGRAM:
import re
from collections import Counter
word=re.findall(r'\w+',open('test.txt').read().lower())
count=Counter(word).most_common(15) print(count)

test.txt

welcome to Mahendra hai hello Mahendra


hello... welcome..hello hai

40
OUTPUT:

[('hello', 3), ('hai', 2), ('welcome', 2), ('Mahendra', 2)]

RESULT:

Thus the program find the most frequent words in a text read from a file was
written and executed successfully.

41
EX.NO: 10 Implementing real-time/technical applications using Exception
handling. (divide by zero error, voter’s age validity, student mark
DATE: range validation)

AIM:
To write a python program for exception handling (divide by zero error).

ALGORITHM:

Step 1: Start
Step 2: Read data from console.

Step 3: Check if it integer, Else throws an exception.

Step 4: IF it is a valid integer accept it.

Step 5: End

PROGRAM:
try:
x=float(input(“your number:”))

inverse=1.0/x

except ValueError:

print(“Give either an int or a float”)except

ZeroDivisionError:

print(“Infinity”) finally:

print(“there may or may not have been an Exception…!”)

42
OUTPUT:

Your number: nine


Give either an int or a float
There may or may not have been an Exception…!

Your number: 0
Infinity
There may or may not have been an Exception…!

RESULT:

Thus the program takes command line arguments (word count)was written
and executed successfully.

43
EX.NO: 11
EXPLORING PYGAME TOOL
DATE:

AIM:
To write a python program for Simulate Elliptical Orbits In Pygame.

ALGORITHM:

Step 1: Install to pygame package in python.

Step 2: Define the class Solar system and initialize all the child classes under it.

Step 3: Define the class for Sun and initialize all the attributes it takes as input .

Step 4: Define the planet class and provide details of all the various
planets and theirattributes.
Step 5: End the program with source code.

PROGRAM:
import turtle

import math
class SolarSystem:
def init (self, width, height):
self.thesun = None self.planets = []
self.ssturtle = turtle.Turtle() self.ssturtle.hideturtle()
self.ssscreen = turtle.Screen()
self.ssscreen.setworldcoordinates(-width/2.0,-height/2.0,width/2.0,height/2.0)
self.ssscreen.tracer(50)
def addPlanet(self, aplanet):
self.planets.append(aplanet)

44
def addSun(self, asun):
self.thesun = asun
def showPlanets(self):
for aplanet in self.planets:
print(aplanet)
def freeze(self):
self.ssscreen.exitonclick()
def movePlanets(self):
G = .1
dt = .001
for p in self.planets:
p.moveTo(p.getXPos() + dt * p.getXVel(), p.getYPos() + dt * p.getYVel())
rx = self.thesun.getXPos() - p.getXPos()ry = self.thesun.getYPos() - p.getYPos()r
= math.sqrt(rx**2 + ry**2)
accx=G*self.thesun.getMass()*rx/r**3
accy = G * self.thesun.getMass()*ry/r**3
p.setXVel(p.getXVel() + dt * accx)p.setYVel(p.getYVel() + dt * accy)

class Sun:
def init (self, iname, irad, im, itemp):self.name = iname
self.radius = iradself.mass = im self.temp = itempself.x = 0
self.y = 0
self.sturtle = turtle.Turtle()
self.sturtle.shape("circle")
self.sturtle.color("yellow")

def getName(self):
return self.name
def getRadius(self):
return self.radius
45
def getMass(self):
return self.mass
def getTemperature(self):
return self.temp
def getVolume(self):
v = 4.0/3 * math.pi *
self.radius**3
return v
def getSurfaceArea(self):
sa = 4.0 * math.pi *
self.radius**2
return sa
def getDensity(self):
d = self.mass / self.getVolume()
return d
def setName(self, newname):self.name = newname
def str (self):
return
self.name
def getXPos(self):return self.x
def getYPos(self):return self.y
class Planet:
def init (self, iname, irad, im, idist,
ivx, ivy, ic):self.name = iname
self.radius = irad self.mass = im
self.distance = idistself.x = idist
self.y = 0 self.velx = ivxself.vely = ivyself.color = ic
self.pturtle = turtle.Turtle()
self.pturtle.up()

46
self.pturtle.color(self.color)
self.pturtle.shape("circle")
self.pturtle.goto(self.x,self.y)
self.pturtle.down()
def getName(self):
return self.name
def getRadius(self):
return self.radius
def getMass(self):
return self.mass
def getDistance(self):
return self.distance
def getVolume(self):
v = 4.0/3 * math.pi *
self.radius**3return v

def getSurfaceArea(self):
sa = 4.0 * math.pi *
self.radius**2return sa

def getDensity(self):
d = self.mass /
self.getVolume()
return d

def setName(self, newname):


self.name = newname
def show(self): print(self.name)
def str (self): return self.name
def moveTo(self,
newx, newy):
self.x = newx
self.y = newy
self.pturtle.goto(ne
wx, newy)

47
def getXPos(self):return self.x

def getYPos(self):return self.y

def getXVel(self):return
self.velx

def getYVel(self):
return self.vely

def setXVel(self, newvx):self.velx = newvx

def setYVel(self, newvy):self.vely = newvy


def createSSandAnimate():ss = SolarSystem(2,2)
sun = Sun("SUN", 5000, 10, 5800)
ss.addSun(sun)

m = Planet("MERCURY", 19.5, 1000, .25, 0, 2, "blue")


ss.addPlanet(m)

m = Planet("EARTH", 47.5, 5000, 0.3, 0, 2.0, "green")


ss.addPlanet(m)

m = Planet("MARS", 50, 9000, 0.5, 0, 1.63, "red")


ss.addPlanet(m)

m = Planet("JUPITER", 100, 49000, 0.7, 0, 1, "black")


ss.addPlanet(m)

m = Planet("Pluto", 1, 500, 0.9, 0,.5, "orange")


ss.addPlanet(m)

m = Planet("Asteroid", 1, 500, 1.0, 0, .75, "cyan")


ss.addPlanet(m)

numTimePeriods = 20000
for amove in

range(numTimePeriods):
ss.movePlanets()

ss.freeze()

create SS and Animate()

48
OUTPUT:

RESULT:
Thus the program takes Simulate Elliptical Orbits in Pygame was written
andexecuted successfully.

49
EX.NO: 12
Developing a game activity using pygame like bouncing ball, car race ,etc )
DATE:

AIM:

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

ALGORITHM:

Step 1: Import pygame module


Step 2: Call pygame.init () to initiate all imported pygame module
Step 3: Set the screen size in terms of pixels using
pygame.display.set_mode ((400, 300)
Step 4: If there is any event in pygame queue
Step 5: Get the event from the pygame queue
Step 6: If event types are pygame. QUIT then set done=true
Step 7: Else, Draw the circle update the screen display with new circle to
bring Bouncing effect
Step 8: Call sys.exit () to uninitialize all the pygame modules

50
PROGRAM:

import pygame
from pygame.locals import *
pygame.init()
screen = pygame.display.set_mode((400, 300))
done = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
pygame.draw.circle(screen, (255,255,255), [100, 80], 10, 0)
pygame.display.update()
pygame.draw.circle(screen, (0,0,0), [100, 80], 10, 0)
pygame.display.update()
pygame.draw.circle(screen, (255,255,255), [150, 95], 10, 0)
pygame.display.update()
pygame.draw.circle(screen, (0,0,0), [150, 95], 10, 0)
pygame.display.update()
pygame.draw.circle(screen, (255,255,255), [200, 130], 10, 0)
pygame.display.update()
pygame.draw.circle(screen, (0,0,0), [200, 130], 10, 0)
pygame.display.update()
pygame.draw.circle(screen, (255,255,255), [250, 150], 10, 0)
pygame.display.update()
pygame.display.update()

for event in pygame.event.get():


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

51
OUTPUT:

RESULT
Thus the program takes Simulate Bouncing Ball Using Pygame was
written and executed successfully.

52

You might also like