Ex.No.
1 DEVELOPING FLOWCHART
Date:
1.a. ELECTRICITY BILL
AIM:
To draw a flow chart for to calculate the electricity bill
FLOWCHART: Start
Take Unit
Value
Yes
Amount=Unit*0
Unit<=100
S_charge=Amount*0.20
No
S_
Yes
Amount=25-(Unit-50)*0.75
Unit<=150
S_charge=Amount*0.20
No
Yes Amount=100-(Unit-150)*1.20
Unit<=250
S_charge=Amount*0.20
No
Amount=220+(Unit+250)*1.50
Total Amount=Amount+s_charge
Total
Amount
Stop 1
1.(b) RETAIL SHOP BILLING:
Start
Input
itemcost,quantity
Input rate
Yes
Rate>1000 Tax=Rate*10
No
Tax=Rate*5
Output item
cost,tax,itemcost+
tax
Stop
2
𝒙𝟑 𝒙𝟓 𝒙𝟕
1.(C). SINE SERIES (Sin x = x- 𝟑! + - 𝟕! + ………):
𝟓!
Start
Read X,n
Declare Counter i-1
X=X*3.142/180
t=X
Sum=X
Loop
No
i<=n
Yes
t=(-t*x*x)/(2*i*(2*i+1))
Sum=sum+t
i=i+1
Print sum
Stop
3
1.(d) WEIGHT OF THE STEEL BAR:
Start
Read
Density D,
Volume V
Compute Weight=D*V
Display
Weight
Stop
RESULT:
Thus the flowchart for the given problem was created successfully.
4
Ex.No.2(A) SIMPLE STATEMENTS AND EXPRESSIONS -
EXCHANGE THE VALUES OF TWO VARIABLES
Date:
AIM:
To exchange the given values of two variables using python.
ALGORITHM:
Step 1: Start the program.
Step 2: Get two integer inputs a and b from the user using the input() function.
Step 3: Declare third variable, c.
Step 4: Set c=a, a=b, b=c.
Step 5: Print the output swapped values a and b.
Step 6: Stop the program.
PROGRAM:
print("Swapping using temporary variable")
a = int(input("a = "))
b = int(input("b = "))
print("Before Swapping")
print("a = ", a)
print("b = ", b)
c=a
a=b
b=c
print("After Swapping")
print("a = ", a)
print("b = ", b)
5
OUTPUT:
Swapping using temporary variable
a = 24
b = 54
Before Swapping
a = 24
b = 54
After Swapping
a = 54
b = 24
RESULT:
Thus the Python program to exchange the given values of two variables was
created and executed successfully.
6
Ex.No.2(B) CIRCULATE THE VALUES OF N VARIABLES
Date :
AIM:
To write a Python program to circulate the given values of n variables
ALGORITHM:
Step 1: Start the program.
Step 2: Get one integer input terms from the user using the input() function.
Step 3: Read the value of terms.
Step 4: Create a list as list1.
Step 5: Validate the range of terms.
Step 6: Then, get one integer input ele from the user using input() function.
Step 7: Add a single item to the existing list using the append method.
Step 8: Print the circulative values.
Step 9: Stop the program.
PROGRAM:
terms=int(input("Enter number of values : "))
list1=[]
for val in range(0,terms,1):
ele=int(input("Enter integer : "))
list1.append(ele)
print("Circulating the elements of list ",list)
for val in range(0,terms,1):
ele=list1.pop(0)
list1.append(ele)
print(list1)
7
OUTPUT:
Enter number of values : 3
Enter integer : 3
Enter integer : 5
Enter integer : 7
Circulating the elements of list <class 'list'>
[5, 7, 3]
[7, 3, 5]
[3, 5, 7]
RESULT:
Thus the Python program to circulate the given values of n variables was created
and executed successfully.
8
Ex.No.2(C) DISTANCE BETWEEN TWO POINTS
Date :
AIM:
To write a Python program to calculate distance between two points.
ALGORITHM:
Step 1: Start the program.
Step 2: Get two integer inputs x1 and x2 for coordinates 1 from the user using the
input() function.
Step 3: Then, Get two integer inputs y1 and y2 for coordinates 2.
Step 4: Calculate using the two points (x1,y1) and (x2,y2),the distance between
these points is given by the formula.
Step 5:result = (((x2-x1)**2+((y2-y1)**2))**0.5.
Step 6: Print the result of distance between values.
Step 7: Stop the program.
PROGRAM:
print("Enter coordinates for Point 1 : ")
x1=int(input("enter x1 : "))
x2=int(input("enter x2 : "))
print("Enter coordinates for Point 2 : ")
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 coordinates for Point 1 :
enter x1 : 4
enter x2 : 5
Enter coordinates for Point 2 :
enter y1 : 6
enter y2 : 2
Distance between (4, 5) and (6, 2) is : 4.123105625617661
RESULT:
Thus the program was written and executed to calculate distance between two
points.
10
Ex.No.2(D) DEMONSTRATE DIFFERENT NUMBER DATA TYPES
Date :
AIM:
To write a Python program to demonstrate different number data types.
ALGORITHM:
Step 1: Start the program.
Step 2: Set the a value.
Step 3: Print data type of a by using type() function.
Step 4: Simlarly again set the different type of value a.
Step 5: Print the data type of that a by using type() function.
Step 6: Stop the program.
PROGRAM:
a=5
print(a, "is of type", type(a))
a = 2.0
print(a, "is of type", type(a))
a = 1+2j
print(a, "is complex number?", isinstance(1+2j,complex))
11
OUTPUT:
5 is of type <class 'int'>
2.0 is of type <class 'float'>
(1+2j) is complex number? True
RESULT:
Thus the program was written and executed to demonstrate different number
data types.
12
Ex.No.2(E) DIFFERENT ARITHMETIC OPERATIONS ON NUMBERS
Date :
AIM:
To write a program to perform different arithmetic operations on numbers in
python
ALGORITHM:
Step 1: Start the program.
Step 2: Read the value of num1 and num2 from the user.
Step 3: Add the num1 and num2.
Step 4: Subtract num1 and num2.
Step 5: Calculate multiplication, division, floor division exponetation and modulus.
Step 6: Print the value of add, dif, mul, div, floor_div, power, modulus.
Step 7: Stop the program.
PROGRAM:
num1 = int(input('Enter First number: '))
num2 = int(input('Enter Second number '))
add = num1 + num2
dif = num1 - num2
mul = num1 * num2
div = num1 / num2
floor_div = num1 // num2
power = num1 ** num2
modulus = num1 % num2
print('Sum of ',num1 ,'and' ,num2 ,'is :',add)
print('Difference of ',num1 ,'and' ,num2 ,'is :',dif)
13
print('Product of' ,num1 ,'and' ,num2 ,'is :',mul)
print('Division of ',num1 ,'and' ,num2 ,'is :',div)
print('Floor Division of ',num1 ,'and' ,num2 ,'is :',floor_div)
print('Exponent of ',num1 ,'and' ,num2 ,'is :',power)
print('Modulus of ',num1 ,'and' ,num2 ,'is :',modulus)
OUTPUT:
Enter First number: 9
Enter Second number 5
Sum of 9 and 5 is : 14
Difference of 9 and 5 is : 4
Product of 9 and 5 is : 45
Division of 9 and 5 is : 1.8
Floor Division of 9 and 5 is : 1
Exponent of 9 and 5 is : 59049
Modulus of 9 and 5 is : 4
RESULT:
Thus the program was written and executed to perform different arithmetic
operations on numbers in python.
14
Ex.No.2(F) TO PRINT THE CURRENT DATE
Date :
AIM:
To write a python script to print the current date in the fallowing format”Sun
May 29 02:26:23 IST 2017”
ALGORITHM:
Step 1: Start the program.
Step 2: Import time module.
Step 3: find the localtime by using the function
time.asctime(time.localtime(time.time()))
Step 4: Print the localtime.
Step 7: Stop the program.
PROGRAM:
import time;
localtime = time.asctime(time.localtime(time.time()))
print("The current time = ", localtime)
15
OUTPUT:
The current time = Wed Mar 1 14:41:50 2022
RESULT:
Thus the python program was written and executed to print the
current date in the fallowing format”Sun May 29 02:26:23 IST 2017”.
16
Ex.No.2(G) TO CONVERT TEMPERATURE IN CELSIUS TO FAHRENHEIT
Date :
AIM:
To write a python script to convert temperature in Celsius to Fahrenheit
ALGORITHM:
Step 1: Start the program.
Step 2: Read the value of celsius by using input() function.
Step 3: Calculate using the formula (celsius * 1.8) + 32
Step 4: Print the fahrenheit values.
Step 5: Stop the program.
PROGRAM:
celsius =float(input("Enter the celsius value:"))
fahrenheit = (celsius * 1.8) + 32
print('%0.1f degree Celsius is equal to %0.1f degree Fahrenheit' %
(celsius,fahrenheit))
17
OUTPUT:
Enter the celsius value:38
38.0 degree Celsius is equal to 100.4 degree Fahrenheit
RESULT:
Thus the python program was written and executed to convert temperature in
Celsius to Fahrenheit.
18
Ex.No.3(A) CONDITIONALS AND ITERATIVE LOOPS -
FIND THE LARGEST NUMBER AMONG THE THREE NUMBERS
Date :
AIM:
To write a Python program to find the largest number among the three input
numbers.
ALGORITHM:
Step 1: Start the program.
Step 2: Read the value of num1, num2 and num3.
Step 3: If check the conditions (num1 >= num2) and (num1 >= num3) then set
largest = num1.
Step 4: The above conditions are false, again check (num2 >= num1) and
(num2 >= num3) then set largest = num2
Step 5: Else set largest = num3.
Step 6: Print the largest value.
Setp 7: Stop the program.
19
PROGRAM:
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
num3 = int(input("Enter third number: "))
if (num1 >= num2) and (num1 >= num3):
largest = num1
elif (num2 >= num1) and (num2 >= num3):
largest = num2
else:
largest = num3
print("The largest number between",num1,",",num2,"and",num3,"is",largest)
OUTPUT:
Enter first number: 23
Enter second number: 55
Enter third number: 12
The largest number between 23 , 55 and 12 is 55
RESULT:
Thus a Python program to find the largest number among the three input
numbers was created and executed successfully.
20
Ex.No.3(B) CONSTRUCT THE PATTERN
Date :
AIM:
To write a python program to construct the given patter, using a nested for loop.
ALGORITHM:
Step 1: Start the program.
Step 2: Call the run() function.
Step 3: In run() function definition, set the value of j, k, p.
Step 4: Using for loop, print the pattern in given range.
Step 5: Using while loop print the pattern in given condition.
Setp 6: Stop the program.
PROGRAM:
def run():
j=7
k=7
p=1
for i in range(8):
print( " " * k," #" * i)
k -=1
while j > 1:
j -= 1
print (" " * p," #" * j)
p+=1
run()
21
OUTPUT:
##
###
####
#####
######
#######
######
#####
####
###
##
RESULT:
Thus a Python program to construct the pattern, using a nested for loop was
created and executed successfully.
22
Ex.No.3(C) PRINT PRIME NUMBERS LESS THAN 20
Date :
AIM:
To write a python script to print prime numbers less than 20.
ALGORITHM:
Step 1: Start the program.
Step 2: Set Start value 1
Step 3: Read the input of n.
Step 4: Using for loop and if condition, find the prime number.
Step 5: Print the prime number.
Setp 6: Stop the program.
PROGRAM:
Start = 1
n = int(input("Enter the number: "))
print("Prime numbers between", Start, "and", n, "are:")
for num in range(Start, n + 1):
if num > 1:
for i in range(2, int(num/2)+1):
if (num % i) == 0:
break
else:
print(num)
23
OUTPUT:
Enter the number: 20
Prime numbers between 1 and 20 are:
11
13
17
19
RESULT:
Thus a Python program to print prime numbers less than 20 was created and
executed successfully.
24
Ex.No.4(A) LIST AND LIST OPERATIONS
Date :
AIM:
To write a program to create, append and remove lists in python.
ALGORITHM:
Step 1: Start the program.
Step 2: create a list1 by using, list1 = ['computer', 'programming', 1957, 2070,
3242]
Step 3: Similarly create list2 and list3.
Step 4: print list1, list2 and list3.
Step 5: Concatenate the list1 and list2 using '+'.
Step 6: Then pring list1 after concatenation.
Step 7: Deleting given index item by using 'del list1[index]' and print list1.
Step 8: Stop the program.
PROGRAM
#create a list in python.
print("CREATE A LIST:")
print("==============")
list1 = ['computer', 'programming', 1957, 2070, 3242]
list2 = [1, 2, 3, 4, 5]
list3 = ["a", "b", "c", "d", "e"]
print("Elements of the lists, list1,list2 and list3 are:")
print(list1)
print(list2)
print(list3)
# Lists concatenation in python example
print("\nLIST CONCATENATION:")
print("===================")
list1 = list1 + list2
print("List's items after concatenating:")
print(list1)
25
# Deleting element from list in python example
print("\nDELETING ELEMENT FROM LIST:")
print("===========================")
print("Elements of the list, list1 are:");
print(list1)
index = input("\nEnter index no:")
index = int(index)
print("Deleting the element present at index number",index)
del list1[index]
print("\nNow elements of the list, list1 are:")
print(list1)
OUTPUT :
CREATE A LIST:
==============
Elements of the lists, list1,list2 and list3 are:
['computer', 'programming', 1957, 2070, 3242]
[1, 2, 3, 4, 5]
['a', 'b', 'c', 'd', 'e']
LIST CONCATENATION:
===================
List's items after concatenating:
['computer', 'programming', 1957, 2070, 3242, 1, 2, 3, 4, 5]
DELETING ELEMENT FROM LIST:
===========================
Elements of the list, list1 are:
['computer', 'programming', 1957, 2070, 3242, 1, 2, 3, 4, 5]
Enter index no:4
Deleting the element present at index number 4
Now elements of the list, list1 are:
['computer', 'programming', 1957, 2070, 1, 2, 3, 4, 5]
>>>
RESULT:
Thus a program to create, append and remove lists in python was created and
executed successfully.
26
Ex.No.4(B) DEMONSTRATE WORKING WITH TUPLE
Date :
AIM:
To write a program to demonstrate working with tuples in python.
ALGORITHM:
Step 1: Start the program.
Step 2: Create a tuple1by using 'tuple1 = ("python", "tuple", 1952, 2323, 432)'.
Step 3: Similarly create tuple2 and tuple3.
Step 4: print tuple1, tuple2 and tuple3.
Step 5: Creating empty tuple 'tp=()'
Step 6: tp have no element, print the message.
Step 7: Add the element of tp and print.
Step 8: Stop the program.
PROGRAM
print("Creating tuple1,tuple2 and tuple3...")
print("=============================")
tuple1 = ("python", "tuple", 1952, 2323, 432)
tuple2 = (1, 2, 3, 4, 5)
tuple3 = ("a", "b", "c", "d", "e")
print(tuple1)
print(tuple2)
print(tuple3)
print("\nCreating an empty tuple...")
print("========================")
tp = ()
print("An empty tuple, tp is created successfully.")
if not tp:
print("The tuple, tp, contains no any item.")
27
print("\nInserting some items to the tuple...")
print("============================")
tp = ("my parents", "my friend", "my brother", "my sister")
print("\nPrinting the tuple tp...")
print(tp)
print("\nNow printing each item in the tuple...")
print("===============================")
for item_in_tuple in tp:
print(item_in_tuple);
OUTPUT :
Creating tuple1,tuple2 and tuple3...
===========================
('python', 'tuple', 1952, 2323, 432)
(1, 2, 3, 4, 5)
('a', 'b', 'c', 'd', 'e')
Creating an empty tuple...
====================
An empty tuple, tp is created successfully.
The tuple, tp, contains no any item.
Inserting some items to the tuple...
============================
Printing the tuple tp...
('my parents', 'my friend', 'my brother', 'my sister')
Now printing each item in the tuple...
=============================
my parents
my friend
my brother
my sister
>>>
RESULT:
Thus a program to demonstrate working with tuples in python was created and
executed successfully.
28
Ex.No.5 DEMONSTRATE WORKING WITH DICTIONARIES
Date :
AIM:
To write a program to demonstrate working with dictionaries in python.
ALGORITHM:
Step 1: Start the program
Step 2: Create a dictionary in different way.
Step 3: Print the dictionary dict1, dict2 and dict3
Step 4: Access the element of dict2 and print.
Step 5: Change the value of dict1 and print.
Step 6: Add the element in dict3 and print.
Step 7: Delete the element by using pop(), popitem() and del function and print.
Step 8: Stop the program.
PROGRAM:
print("CREATE DICTIONARY IN DIFFERENT WAY...")
print("======================================")
dict1 = {} #empty dictionary
dict1 = {1: 'apple', 2: 'ball'}
dict2 = {'name': 'John', 1: [2, 4, 3]}
dict3 = dict({1:'C', 2:'Java',3:'OOPS'})
dict1 = dict([(1,'apple'), (2,'ball')])
print("dict1=",dict1)
print("dict2=",dict2)
print("dict3=",dict3)
print("dict1=",dict1)
print("\nACCESS ELEMENTS...")
print("==================")
print(dict2['name'])
print(dict2.get(1))
print("\nChange or add elements in a dictionary...")
print("====================================")
dict1[2] = 'car'
print(dict1)
dict3[4] = 'HTML'
29
print(dict3)
print("\nDelete or remove elements...")
print("==========================")
print(dict3.pop(3))
print(dict3)
print(dict3.popitem())
print(dict3)
del dict3
print(dict3)
OUTPUT :
CREATE DICTIONARY IN DIFFERENT WAY...
======================================
dict1= {1: 'apple', 2: 'ball'}
dict2= {'name': 'John', 1: [2, 4, 3]}
dict3= {1: 'C', 2: 'Java', 3: 'OOPS'}
dict1= {1: 'apple', 2: 'ball'}
ACCESS ELEMENTS...
==================
John
[2, 4, 3]
Change or add elements in a dictionary...
================================================
{1: 'apple', 2: 'car'}
{1: 'C', 2: 'Java', 3: 'OOPS', 4: 'HTML'}
Delete or remove elements...
============================
OOPS
{1: 'C', 2: 'Java', 4: 'HTML'}
(4, 'HTML')
{1: 'C', 2: 'Java'}
Traceback (most recent call last):
File "D:/python 2021/py pgm(R-21)/PY PGM/dictionary.py", line 33, in <module>
print(dict3)
NameError: name 'dict3' is not defined
>>>
RESULT:
Thus a python program to demonstrate working with dictionaries was created
and executed successfully.
30
Ex.No.6 FACTORIAL USING FUNCTION
Date :
AIM:
To write a python program to find the factorial of a number using recursion.
ALGORITHM:
Step 1: Start the program.
Step 2: Get the input of num value using input().
Step 3: Using if, check num<0 then print “Sorry, factorial does not exit for negative
numbers”.
Step 4: Else if check num==0 then print “The factorial of 0 is 1”.
Step 5: Else find the factorial value by using call factorial(num) function.
Step 6: In factorial () function, check the given value n==1 then return n.
Step 7: Else return n * factorial (n-1) value.
Step 8: Stop the program.
PROGRAM
def factorial(n):
if n == 1:
return n
else:
return n*factorial(n-1)
num = int(input("Enter the 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",factorial(num))
31
OUTPUT 1:
Enter the number:5
The factorial of 5 is 120
OUTPUT 2:
Enter the number:-4
Sorry, factorial does not exist for negative numbers
RESULT:
Thus, a python program to find the factorial of a number using recursion was
created and executed successfully.
32
Ex.No.7(a) CREATE, CONCATENATE AND PRINT A STRING AND
ACCESSING SUB-STRING
Date :
AIM:
To write a program to create, concatenate and print a string and accessing sub-
string from given string.
ALGORITHM:
Step 1: Start the program.
Step 2: Create a string ‘mystring’ using single quotes, double quotes and triple quotes
and print mystring.
Step 3: Concatenate two string str1 and str2 using ‘+’ and print it.
Step 4: Repetition the string str1 using ‘*’ and print it.
Step 5: Accessing the string str using the index of the string and print it.
Step 6: Slicing the string str using [:] with index of the string and print it.
Step 7: Stop the program.
PROGRAM
#create string
print("STRING CREATION")
print("===============")
mystring = 'Hello'
print(mystring)
mystring = "Hello"
print(mystring)
my_string = '''Hello'''
print(my_string)
33
# triple quotes string can extend multiple lines
mystring = """Hello, welcome to
the world of Python"""
print(my_string)
#access string: concatenate
print("ACCESSING STRING: CONCATENATION")
print("===============================")
str1 = 'Hello'
str2 ='World!'
# using +
print('str1 + str2 = ', str1 + str2)
# using *
print('str1 * 3 =', str1 * 3)
#PRINT STRING
print("PRINTING STRING")
print("===============")
str = 'programiz'
print('str = ', str)
#first character
print('str[0] = ', str[0])
#last character
print('str[-1] = ', str[-1])
#slicing 2nd to 5th character
print('str[1:5] = ', str[1:5])
#slicing 6th to 2nd last character
print('str[5:-2] = ', str[5:-2])
34
OUTPUT:
STRING CREATION
===============
Hello
Hello
Hello
Hello
ACCESSING STRING: CONCATENATION
===============================
str1 + str2 = HelloWorld!
str1 * 3 = HelloHelloHello
PRINTING STRING
===============
str = programiz
str[0] = p
str[-1] = z
str[1:5] = rogr
str[5:-2] = am
RESULT:
Thus a python program to create, concatenate and print a string and accessing
sub-string from given string was created and executed successfully.
35
Ex.No.8 DEFINE A MODULE AND IMPORT A SPECIFIC FUNCTION
Date:
AIM:
To write a python program to define a module and import a specific function in
that module to another program.
ALGORITHM:
Step 1: Start the program
Step 2: Create the user define module ‘sample.py’
Step 3: In sample.py, define the function add(a,b) and add the value a and b the return
the result.
Step 4: In the shell window, import the module ‘sample.py’ and call the add() function.
Step 5: Import the math module, print the math pi value.
Step 6: Stop the program.
PROGRAM i):
# Python Module 'sample.py'
def add(a,b):
result=a+b
return result
36
OUTPUT: >>> import sample >>> sample.add(12,5) 17
PROGRAM ii):
# to import standard module math
import math
print("The value of pi is", math.pi)
OUTPUT:
The value of pi is 3.141592653589793
RESULT:
Thus a python program to define a module and import a specific function in that
module to another program was created and executed successfully.
37
Ex.No.:9 COPY FROM ONE FILE TO ANOTHER
Date:
AIM:
To write a Python program to copy one file to another using File handling.
ALGORITHM:
Step 1: Start the program
Step 2: Import shutil module.
Step 3: Using copy2( ) function in shutil module and give the already created txt source
file address and destination file address.
Step 4: In another way using copyfile( ) function.
Step 5: Stop the program.
PROGRAM:
import shutil
shutil.copy2('D:/PY PGM/file1.txt', 'D:/PY PGM/file2.txt')
#another way to copy file
shutil.copyfile('D:/PY PGM/file1.txt', 'D:/PY PGM/file3.txt')
print("File Copy Done")
38
OUTPUT:
>>>
RESTART: C:/Users/AppData/Local/Programs/Python/Python36-32/filecopy.py
File Copy Done
(see the copied file in mentioned drive D:)
file1.txt
Hai how are you?
this is problem solving and python
programming lab.
file2.txt
Hai how are you?
this is problem solving and python
programming lab.
RESULT:
Thus a Python programs to copy one file to another using File handling was
created and executed successfully.
39
Ex.No.: 10 DIVIDE BY ZERO ERROR
Date:
AIM:
To write a Python program to raising divide by zero error using Exception
handling.
ALGORITHM:
Step 1: Start the program.
Step 2: Get the elements of a and b from the user
Step 3: Within the try calculate c = ((s+b) / (a-b)
Step 4: if check a==b then raose ‘Zero Division Error’
Step 5:In except catch the ZeroDivisionError print “Infinite: Divided by 0”
Step 6: Else print the value c.
Step 7: Stop the program.
PROGRAM:
a=int(input("Enter the value of a :"))
b=int(input("Enter the value of b :"))
try:
c=((a+b)/(a-b))
if(a==b):
raise ZeroDivisionError
except ZeroDivisionError:
print ("Infinite: Divided by 0")
else:
print (c)
40
OUTPUT 1:
Enter the value of a :4
Enter the value of b :4
Infinite: Divided by 0
OUTPUT 2:
Enter the value of a :5
Enter the value of b :2
2.3333333333333335
RESULT:
Thus a Python program to raising divide by zero error using Exception handling
was created and executed successfully.
41
Ex.No.11 EXPLORING PYGAME TOOL
Date:
AIM:
To write a Python program for exploring pygame tool.
ALGORITHM:
Step 1: Start the program.
Step 2: Set up the drawing window
Step 3: Run until the user asks to quit
Step 4: Fill the background with white.
Step 5: Filp the display
Step 6: Quit pygame
Step 7: Stop the program.
PROGRAM:
import pygame
pygame.init()
screen=pygame.display.set_mode([500,500])
running=True
while running:
for event in pygame.event.get():
if event.type==pygame.QUIT:
running=False
screen.fill((255,255,255))
pygame.draw.circle(screen,(0,0,255),(250,250),75)
pygame.display.flip()
pygame.quit()
42
OUTPUT :
RESULT:
Thus a Python program for exploring pygame tool was created and executed
successfully.
43
Ex.No.12 SIMULATE BOUNCING BALL USING PYGAME
Date :
AIM:
To write a Python program to simulate bouncing ball using pygame.
ALGORITHM:
Step 1: Start
Step 2: Import necessary GUI for simulation
Step 3: Set the window coordinates and the ball coordiates
Step 4: Assign various colors for the ball and set the base color
Step 5: Fix the color, shape and bouncing speed randomly
Step 6: Write a function to move the base according to the ball position
Step 7: Stop
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.jpg")
ballrect = ball.get_rect()
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
ballrect = ballrect.move(speed)
if ballrect.left < 0 or ballrect.right > width:
speed[0] = -speed[0]
44
if ballrect.top < 0 or ballrect.bottom > height:
speed[1] = -speed[1]
screen.fill(background)
screen.blit(ball, ballrect)
pygame.display.flip()
OUTPUT :
RESULT:
Thus a Python program to simulate bouncing ball using pygame was simulated
successfully.
45