Professional Documents
Culture Documents
GE3171 - Python Lab ManuaLall Print
GE3171 - Python Lab ManuaLall Print
PROGRAMMING LABORATORY
OBJECTIVES:
To understand the problem solving approaches.
To learn the basic programming constructs in Python.
To practice various computing strategies for Python-based solutions
to real world problems.
To use Python data structures – lists, tuples, dictionaries.
To do input/output with files in Python.
LIST OF EXPERIMENTS:
1. Identification and solving of simple real life or scientific or technical problems,
and developing flow charts for the same. (Electricity Billing, Retail shop
billing, Sin series, weight of a motorbike, Weight of a steel bar, compute
Electrical Current in Three Phase AC Circuit, etc.)
2. Python programming using simple statements and expressions (exchange
the values of two variables, circulate the values of n variables, distance
between two points).
3. Scientific problems using Conditionals and Iterative loops. (Number
series, Number Patterns, pyramid pattern).
4. Implementing real-time/technical applications using Lists, Tuples. (Items
present in a library/Components of a car/ Materials required for construction
of a building –operations of list & tuples)
.
5. Implementing real-time/technical applications using Sets, Dictionaries.
(Language, components of an automobile, Elements of a civil structure,
etc.- operations of Sets & Dictionaries
6. Implementing programs using Functions. (Factorial, largest number in a
list, area of shape)
7. Implementing programs using Strings. (reverse, palindrome, character
count, replacing characters)
8. Implementing programs using written modules and Python Standard
Libraries (pandas, numpy. Matplotlib, scipy)
9. Implementing real-time/technical applications using File handling. (copy
from one file to another, word count, longest word)
10.Implementing real-time/technical applications using Exception
handling. (divide by zero error, voter’s age validity, student mark range
validation)
11. Exploring Pygame tool.
12. Developing a game activity using Pygame like bouncing ball, car race etc.
.
GE3171 – PROBLEM SOLVING AND PYTHON PROGRAMMING LABORATORY
.
6 Implementing programs using Functions.
6.1 GCD of given numbers using Euclid's Algorithm.
6.2 Square root of a given number using newtons method.
6.3 Factorial of a number using functions
6.4 largest number in a list
6.5 Area of shapes
7 Implementing programs using Strings.
7.1 Reverse of a string
7.2 Palindrome of a string
7.3 Character count of a string
7.4 Replace of a string
8 Implementing programs using written modules and Python
Standard Libraries.
8.1 Convert list in to a Series using pandas
8.2 Finding the elements of a given array is zero using numpy
8.3 Generate a simple graph using matplotlib
8.4 Solve trigonometric problems using scipy
9 Implementing real-time/technical applications using File handling.
9.1 Copy text from one file to another
9.2 Command Line Arguments(Word Count)
9.3 Find the longest word(File handling)
10 Implementing real-time/technical applications using Exception
handling.
10.1 Divide by zero error – Exception Handing
10.2 Voter’s age validity
10.3 Student mark range validation
11 Exploring Pygame tool.
12 Developing a game activity using Pygame
12.1 Simulate Bouncing Ball Using Pygame
12.2 Simulate Car race Using Pygame
.
Ex : 1.1
ELECTRICITY BILLING
Date:
Aim:
To write a python program to print electricity bill.
Algorithm:
.
Flow chart:
.
PROGRAM
.
OUTPUT
Algorithm:
prices = []
sub_total = 0.0
n=int(input(" Enter the no of
items :")) for i in range(n):
item = float( input("Enter the price of item #" + str(i+1) + ":
")) sub_total = sub_total + item
prices.append(item)
#compute the tax on the sub total @ rate of
7.25% tax = sub_total * (7.25/100)
total_price = sub_total + tax
print("Sub total: ",sub_total)
print("Tax: {:0.2f}".format(tax))
print("Total: {:0.2f}".format(total_price))
Output :
Aim:
Algorithm:
Step 1 : Start
Step 2 : Read the values of x and n
Step 3 : Initialize sine=0
Step 4 : Define a sine function using for loop, first convert degrees to radians.
Step 5 : Compute using sine formula expansion and add each term to the sum variable.
Step 6 : Print the final sum of the expansion.
Step 7 : Stop.
Flow Chart:
.
Program
:
import math
x=int(input("Enter the value of x in
degrees:")) n=int(input("Enter the number of
terms:")) 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
print(sine)
Result:
Thus the
python
program
for sin
series is
executed
and the
results
are
verified
Ex : 1.3
Date: Weight of a Motor Bike
Aim:
To write a python program to calculate the weight of a motor bike.
Algorithm:
Step 1: Start the program
Step 2: Read the value of a mass
Step 3: Calculate the weight of a motor bike by multiplying mass with 9.8 and store it in
weight Step 4: Print the weight
Step 5: Stop
Flow chart:
Start
Initialize g(gravity)=9.8
Compute W=m*g
Stop
.
Program:
mass = float(input("Enter the Mass of the MotorBike: "))
Weight =mass*9.8
print(“ The weight of a Motor Bike for a given mass is ”,Weight)
Output
Enter the Mass of the MotorBike: 100
The weight of a Motor Bike for a given mass is 980.0000000000001
Result: .
Thus the python program to calculate the weight of a motor bike is executed
and the results are verified.
Ex : 1.4
Date: WEIGHT OF A STEEL BAR
Aim:
To write a python program to calculate the weight of a steel bar.
Algorithm:
Step 1: Start the program
Step 2: Read the value of a diameter and length
Step 3: Calculate the weight of a steel bar by using the formula
of ((diameter*diameter)/162.28)*length and store it in weight.
Step 4: Print
weight Step 5: Stop
Flow chart:
Start
Initialize g(gravity)=9.8
Compute W=m*g
Stop
.
Program:
diameter = float(input("Enter the Diameter of the Rounded Steel
Bar:")) length = float(input("Enter the Length of the Rounded Steel
Bar:"))
Weight
=((diameter*diameter)/162.28)*length
print(“Weight of a Steel Bar”,Weight)
Output:
Enter the Diameter of the Rounded Steel
Bar:2 Enter the Length of the Rounded Steel
Bar:15 Weight of a Steel Bar is
0.3697313285679073
RESULT
Thus the python program to calculate the. weight of a steel bar is executed and the
results are verified.
Ex : 1.5
ELECTRICAL CURRENT IN THREE PHASE AC CIRCUIT
Date:
Aim:
To write a python program to calculate the electrical current in Three Phase AC Circuit.
Algorithm:
Flow Chart:
Start
Compute
V_Ph=V_L/1.732 # in V Z_Ph=sqrt((R**2)+(X_L**2))# in ohm I_Ph=V_Ph/Z_Ph# in A
I_L=I_Ph# in A
Print the kW
Stop
.
Program:
import math
R = 20 # in ohm
X_L = 15 # in
ohm V_L = 400 #
in V
f = 50 # in Hz
#calculations
V_Ph=V_L/1.732 # in V
Z_Ph=sqrt((R**2)+(X_L**2))# in
ohm I_Ph=V_Ph/Z_Ph# in A
I_L=I_Ph# in A
print ("The Electrical Current in Three Phase AC Circuit",round(I_L,6))
Output:
Aim:
To Write a python program to Exchanging the values of two variables taking input from the user.
Algorithm:
Step 1 : Start
Step 2 : Define a function named
format() Step 2 : Read the input values X
and Y Step 3 : Perform the following
steps
Step 3.1 : temp = x
Step 3.2 : x = y
Step 3.3 : y = temp
Step 4 : Print the swapped value as
result Step 5 : End
Program:
Using Temporary variable
output
: Enter value of x: 10
Enter value of y: 20
The value of x after swapping: 20
.
T
h
e
v
a
l
u
e
o
f
y
a
f
t
e
r
s
w
a
p
p
i
n
g
:
1
0
Few Other Methods to Swap
variables Without Using Temporary
variable
Program:
x=5
y = 10
x, y = y, x
print("x =", x)
print("y =", y)
output:
x = 10
y=5
Result .
Thus the Python program to exchange the values of two variables was executed
successfully and the output is verified.
Ex : 2 (b)
Circulate the values of n variables
Date:
Aim:
Write a python program to Circulate the values of n variables taking input from the user
Algorithm:
Step 1 : Start
Step 2 : Declare a list
Step 3 : Read number of input value.
Step 4 : Store the value of input in
list. Step 5 : Print the original list.
Step 6 : Use range function with for loop to circulate the
values Step 7 : Print the result
Program
:
A=list(input("Enter the list Values:"))
print(A)
for i in range(1,len(A),1):
print(A[i:]+A[:i])
Result
Thus, the Python program to Circulate th.e values of n variables was executed
successfully and the output is verified.
Ex : 2 (c)
Distance between two points
Date:
Aim:
Write a python program to calculate distance between two points taking input from the user.
Algorithm:
Step 1 : Start
Step 2 : Define a function math.sqrt()
Step 3 : Read the value of coordinates of two points P1 and
P2 Step 4 : Perform the following step
Step 5 : dist = math.sqrt( ((x2-x1)**2) + ((y2-
y1)**2) ) Step 6 : Print the distance between two
points
Step 7 : End
Program:
import math
Output:
Enter coordinates for Point
1: x1 = 2
y1 = 3
Enter coordinates for point
2: x2 = 3
y2 = 4
Distance between given points is 1.41
.
Resul
t
Thus, the Python program to calculate distance between two points was executed successfully
and the
output is
verified.
Ex : 3 (a)
Number Series-Fibonacci Series
Date:
Aim:
To Write a python program to print Fibonacci series taking input from the user
Algorithm:
Step 1 : Start
Step 2 : Read the input values using input()
Step 3 : Assign f1= -1 and f2=1.
Step 4 : Perform the term = f1+f2
Step 5 : Print the value as result
Step 6 : Perform the following
swap Step 7 : step f1 = f2
Step 8 : f2 = term
Step 9 : End
Program:
# Fibonacci series
print("Fibonacci series")
Num_of_terms = int(input("Enter number of terms :
")) f1 = -1
f2 = 1
for i in
range(0,Num_of_terms,1):
term = f1+f2
print(term, end="
") f1 = f2
f2 = term
Output:
Fibonacci series :
Enter number of terms :
Result .
Thus, the Python program to print Fibonacci series was executed successfully and the
output is verified.
501123
Result .
Thus, the Python program to print Fibonacci series was executed successfully and the
output is verified.
Ex : 3 (b)
Number Series - Odd Numbers
Date:
Aim:
To write a python program to print odd numbers by taking input from the user
Algorithm:
Step 1 : start
Step 2 : Declare the list of numbers using list.
Step 3 : Use for loop to iterate the numbers in
list. Step 4 : Check for condition
Step 5 : Num % 2==0
Step 6 : Print the
result. Step 7 : End
Program:
# list of numbers
list1 = [10, 21, 4, 45, 66, 93]
Output:
Enter number of terms: 5
Number Patterns - Odd
Numbers: 1 3 5 7 9
Result .
Thus, the Python program to print odd numbers was executed successfully and the
output is verified.
Ex : 3 (c)
Number Pattern
Date:
Aim:
To write a python program to print numbers patterns.
Algorithn:
Program:
rows = int(input('Enter the number of
rows')) for i in range(rows+1):
for j in range(i):
print(i, end=' ')
print(' ')
Output:
Enter the number of
rows 6 1
22
333
4444
55555
666666
Result:
Thus the python program to print numbers patterns is executed and verified.
Ex : 3 (d)
Pyramid Pattern
Date:
Aim:
To write a python program to print pyramid patterns
Algorithm:
Program:
n = int(input("Enter the number of rows: "))
m = (2 * n) - 2
for i in range(0, n):
for j in range(0,
m): print(end="
")
m = m - 1 # decrementing m after each
loop for j in range(0, i + 1):
# printing full Triangle pyramid using stars
print("* ", end=' ')
print(" ")
Output:
Enter the number of rows: 5
*
**
***
****
*****
Result
Thus, the Python program to print Pyramid Pattern was executed successfully and the output
.
is
verifi
ed.
.
Ex : 4.1
Implementing real-time/technical applications using Lists
Date: Basic operations of List
Aim:
To write python programs using list functions to perform the operations of list library.
Algorithm:
Step 1 : Start
Step 2 : Declare a list
Step 3 : Read the input value.
Step 4 : Store the value of input in list.
Step 5 : Process the list functions present in library
function. Step 6 : Print the result
Step 7 : End
Program:
#creating a list
Library=['OS','OOAD','MPMC']
print(" Books in library
are:") print(Library)
OUTPUT :
Books in library are:
['OS', 'OOAD', 'MPMC']
OUTPUT :
Accessing a element from the
list OS
MPMC
.
# Creating a Multi-Dimensional List
Library=[['OS', 'OOAD','MPMC'] , ['TOC','PYTHON','NETWORKS']]
print("Accessing a element from a Multi-Dimensional
list") print(Library[0][1])
print(Library[1][0])
OUTPUT :
Accessing a element from a Multi-Dimensional list OOAD
TOC
#Negative indexing
Library=['OS','OOAD','MPMC']
print("Negative accessing a element from the
list") print(Library[-1])
print(Library[-2])
OUTPUT :
Negative accessing a element from
the list MPMC
OOAD
#Slicing
Library=['OS','OOAD','MPMC','TOC','NW']
print(Library[1][:-3])
print(Library[1][:4])
print(Library[2][2:4])
print(Library[3][0:4])
print(Library[4][:])
OUTPUT :
O OOAD MC TOC NW
#append()
Library=['OS','OOAD','MPMC']
Library.append(“DS”)
Library.append(“OOPS”)
Library.append(“NWs”)
print(Library)
OUTPUT :
['OS', 'OOAD', 'MPMC', 'DS', 'OOPS', 'NWs']
#extend()
Library=['OS','OOAD','MPMC']
Library.extend(["TOC","DWDM"]) .
print(Library)
OUTPUT :
['OS', 'OOAD', 'MPMC', 'TOC', 'DWDM']
#insert()
Library=['OS','OOAD','MPMC']
Library.insert(0,”DS”)
print(Library)
OUTPUT :
['DS', 'OS', 'OOAD', 'MPMC']
#del method
Library=['OS','OOAD','MPMC']
del Library[:2]
print(Library)
OUTPUT :
['MPMC']
#remove()
Library=['OS','OOAD','MPMC','OOAD']
Library.remove('OOAD')
print(Library)
OUTPUT :
['OS', 'MPMC', 'OOAD']
#reverse()
Library=['OS','OOAD','MPMC']
Library.reverse()
print(Library)
OUTPUT :
['MPMC', 'OOAD', 'OS']
#sort()
Library=['OS','OOAD','MPMC']
Library.sort()
print(Library)
OUTPUT :
['MPMC', 'OOAD', 'OS']
#+concatenation operator
Library=['OS','OOAD','MPMC'] .
Books=['DS','TOC','DMDW']
print(Library+Books)
OUTPUT :
['OS', 'OOAD', 'MPMC', 'DS', 'TOC', 'DMDW']
# *replication operator
Library=['OS','OOAD','MPMC','TOC','NW']
print('OS' in Library)
print('DWDM' in Library)
print('OS' not in Library)
OUTPUT :
True
False
False
#count()
Library=['OS','OOAD','MPMC','TOC','NW']
x=Library.count("TOC")
print(x)
OUTPUT :
1
Result
Thus, the Python using list functions present in list library was executed successfully and the
output is verified. .
Ex : 4.2
Library functionality using list.
Date:
Aim:
To write a python program to implement the library functionality using list.
Algorithm:
Step 1 : Start the program
Step 2 : Initialize the book
list
Step 3 : Get option from the user for accessing the library function
Add the book to list
Issue a book
Return the book
View the list of book
Step 4 : if choice is 1 then get book name and add to book list
Step 5 : if choice is 2 then issue the book and remove from book list
Step 6 : if choice is 3 then return the book and add the book to list
Step 7 : if choice is 4 then the display the book list
Step 8 : otherwise exit from
menu Step 9 : Stop the program.
Program:
bk_list=["OS","MPMC","DS"]
print("Welcome to library”")
while(1):
ch=int(input(" \n 1. add the book to list \n 2. issue a book \n 3. return the book \n 4. view the
book list \n 5. Exit \n"))
if(ch==1):
bk=input("enter the book
name") bk_list.append(bk)
print(bk_list)
elif(ch==2):
ibk=input("Enter the book to issue")
bk_list.remove(ibk)
print(bk_list)
elif(ch==3):
rbk=input("enter the book to
return") bk_list.append(rbk)
print(bk_list)
elif(ch==4):
print(bk_list)
else:
break .
Output:
Welcome to library”
1. add the book to list
2. issue a book
3. return the book
4. view the book list
5. Exit
1
enter the book name NW
['OS', 'MPMC', 'DS', '
NW']
1. add the book to list
2. issue a book
3. return the book
4. view the book list
5. Exit
2
Enter the book to issue
NW ['OS', 'MPMC',
'DS']
1. add the book to list
2. issue a book
3. return the book
4. view the book list
5. Exit
3
enter the book to return
NW ['OS', 'MPMC', 'DS',
' NW']
1. add the book to list
2. issue a book
3. return the book
4. view the book list
5. Exit
4
['OS', 'MPMC', 'DS', ' NW']
.
results are verified
Result:
Thus the python program to implement the library functionality using list is executed and the
.
results are verified
Ex : 4.3
Date: Components of car using list
Aim:
To write a python program to implement the operation of list for components of car.
Algorithm:
Program
: cc=['Engine','Front xle','Battery','transmision']
com=input('Enter the car components:')
cc.append(com)
print("Components of car :",cc)
print("length of the list:",len(cc))
print("maximum of the
list:",max(cc)) print("minimum of the
list:",min(cc))
print("indexing(Value at the index 3):",cc[3])
print("Return 'True' if Battery in present in the
list") print("Battery" in cc)
print("multiplication of list element:",cc*2)
.
Output:
Enter the car components:Glass
Components of car : ['Engine', 'Front xle', 'Battery', 'transmision',
'Glass'] length of the list: 5
maximum of the list: transmision
minimum of the list: Battery
indexing(Value at the index 3):
transmision Return 'True' if Battery in
present in the list True
multiplication of list element: ['Engine', 'Front xle', 'Battery', 'transmision', 'Glass',
'Engine', 'Front xle', 'Battery', 'transmision', 'Glass']
Result
Aim:
To write a python program to create a list for materials requirement of construction and perform
the operation on the list.
Algorithm:
Step 1 : Start the program.
Step 2 : Create a list of construction
material. Step 3 : Sort the list using sort
function.
Step 4 : Print cc.
Step 5 : Reverse the list using reverse function.
Step 6 : Print cc.
Step 7 : Insert y value by using index position.
Step 8 : Slice the values using del function with start value and end up
value. Step 9 : Print the cc
Step 10 : Print the position of the value by using index function.
Step 11 : Print the values in the list of the letter ‘n’ by using for loop and member
ship operator.
Step 12 : Stop the program.
Program:
cc=['Bricks','Cement','paint','wood']
cc.sort()
print("sorted List")
print(cc)
print("Reverse List")
cc.reverse()
print(cc)
print("Insert a value 'glass' to the list")
cc.insert(0, 'Glass')
print(cc)
print("Delete List")
del cc[:2]
print(cc)
print("Find the index of Cement")
.
print(cc.ind
ex('Cement'
))
print("New List")
new=[]
for i in cc:
if "n" in i:
new.append(i)
print(new)
Output:
sorted List
['Bricks', 'Cement', 'paint', 'wood']
Reverse List
['wood', 'paint', 'Cement', 'Bricks']
Insert a value 'glass' to the list
['Glass', 'wood', 'paint', 'Cement', 'Bricks']
Delete List
['paint', 'Cement', 'Bricks']
Find the index of Cement
1
New List
['paint', 'Cement']
Result:
and verified. .
Thus the python program to create a list for construction of a building using list is executed
and verified. .
Ex : 4.5
Library functions using tuples
Date:
Aim:
To write a python program to implement the library functionality using tuples.
Algorithm
Step 1 : Start the program
Step 2 : Create a tuple named as book.
Step 3 : Add a “NW” to a book tuple by using +
operator. Step 4 : Print book.
Step 5 : Slicing operations is applied to book tuple of the range 1:2 and print
book. Step 6 : Print maximum value in the tuple.
Step 7 : Print maximum value in the tuple.
Step 8 : Convert the tuple to a list by using list function.
Step 9 : Delete the tuple.
Step 10 : Stop the program.
Program:
book=("OS","MPMC","DS")
book=book+("NW",)
print(book)
print(book[1:2])
print(max(book))
print(min(book))
book1=("OOAD","C++","C")
print(book1)
new=list(book)
print(new)
del(book1)
print(book1)
.
OUTPUT :
('OS', 'MPMC', 'DS', 'NW')
('MPMC',)
OS
DS
('OOAD', 'C++', 'C')
['OS', 'MPMC', 'DS', 'NW']
Traceback (most recent call last):
File "C:/Portable Python 3.2.5.1/3.py", line 12, in
<module> print(book1)
NameError: name 'book1' is not defined
Result:
Thus the python program to implement the library functionality using tuple is
executed and the results are verified .
Ex : 4.6
Components of a car using tuples.
Date:
Aim:
To write a python program to implement the components of a car using tuples.
Algorithm:
Step 1 : Start the program
Step 2 : Create a tuple named as cc
Step 3 : Adding a value to a tuple is by converting tuple to a list and then assign “ Gear”
value to y[1] and convert it to a tuple.
Step 4 : Step 3is implemented for removing a value in tuple.
Step 5 : Type function is used to check whether it is list or
tuples. Step 6 : Stop the program.
Program:
cc=('Engine','Front axle','Battery','transmision')
y=list(cc)# adding a value to a tuple means we have to convert to a list y[1]="Gear"
cc=tuple(y)
print(cc)
y=list(cc)# removing a value from tuple.
y.remove("Gear") cc=tuple(y)
print(cc)
new=(" Handle",)
print(type(new))
Output :
('Engine', 'Gear', 'Battery',
'transmision') ('Engine', 'Battery',
'transmision')
<class 'tuple'>
Result:
executed and verified. .
Thus the python program to implement components of a car using tuples is
Aim:
To write a python program to implement the construction of a materials using tuples.
Algorithm:
Program:
cm=('sand','cement','bricks','water')
a,b,c,d = cm
# tuple unpacking
print("\nValues after unpacking:
") print(a)
print(b)
print(c)
print(d)
print(cm.count('sand'))
print(cm.index('sand'))
new=tuple("sand")
print(new)
print(sorted(cm))
print(type(sorted(cm)))
.
Output :
Values after unpacking:
sand
cement
bricks
water
1
0
('s', 'a', 'n', 'd')
['bricks', 'cement', 'sand', 'water']
<class 'list'>
Result:
Thus the python program to create a tuple for materials of construction and
performed the various operations and result is verified.
.
Ex : 5.1 Implementing real-time/technical applications using
Date: Sets, Dictionaries.
Languages using dictionaries
Aim:
To write a python program to implement the languages using dictionaries.
Algorithm:
Step 1 : Start the program
Step 2 : Create a empty dictionary using
{} Step 3 : dict() is used to create a
dictionary.
Step 4 : To add a value, update() is used in key value pair.
Step 5 : Calculate the total values in the dictionary using len()
.
Step 6 : Remove the particular key in the dictionary by using
pop() Step 7 : Print the keys in the dictionary by using key()
Step 8 : Print the values in the dictionary by using values()
Step 9 : Print the key value pair in the dictionary using
items() Step 10 : Clear the the key value pair by using clear()
Step 11 : Delete the dictionary by using del dictionary
Program:
Language={}
print(" Empty Dictionary :",Language)
Language=dict({1: "english", "two": "tamil", 3: "malayalam"})
print(" Using dict() the languages are :",Language)
New_Language={4: "hindi",5: "hindi"}#duplicate values can
create Language.update(New_Language)
print(" the updated languages are :",Language)
print(" the length of the languages
:",len(Language)) Language.pop(5)
print(" key 5 has been popped with value
:",Language) print(" the keys are :",Language.keys())
print(" the values are :",Language.values())
print(" the items in languages are :",Language.items())
print(Language) .
Language.clear()
print(" The items are cleared in dictionary
",Language) del Language
print(Language) .
OUTPUT :
Empty Dictionary : {}
Using dict() the languages are : {1: 'english', 3: 'malayalam', 'two': 'tamil'}
the updated languages are : {1: 'english', 3: 'malayalam', 4: 'hindi', 'two': 'tamil', 5: 'hindi'}
key 5 has been popped with value : {1: 'english', 3: 'malayalam', 4: 'hindi', 'two':
the items in languages are : dict_items([(1, 'english'), (3, 'malayalam'), (4, 'hindi'), ('two',
'tamil')])
<module> print(Language)
Result:
Thus the python program to implement languages using dictionaries is executed
and verified.
.
Ex : 5.2
Components of Automobile using dictionaries
Date:
Aim:
To write a python program to implement automobile using dictionaries.
Algorithm:
Step 1: Start the program
Step 2: Create a empty dictionary using
{} Step 3: dict() is used to create a
dictionary.
Step 4: Get the value in the dictionary using get()
Step 5: adding [key] with value to a dictionary using indexing
operation. Step 6: Remove a key value pair in dictionary using
popitem().
Step 7: To check whether key is available in dictionary by using membership operator
in. Step 8: Stop the program.
Program:
auto_mobile={}
print(" Empty dictionary ",auto_mobile)
auto_mobile=dict({1:"Engine",2:"Clutch",3:"Gearbox"})
print(" Automobile parts :",auto_mobile)
print(" The value for 2 is
",auto_mobile.get(2))
auto_mobile['four']="chassis"
print(" Updated auto_mobile",auto_mobile) print(auto_mobile.popitem())
print(" The current auto_mobile parts is :",auto_mobile)
print(" Is 2 available in automobile
parts") print(2 in auto_mobile)
OUTPUT :
Empty dictionary {}
Automobile parts : {1: 'Engine', 2: 'Clutch', 3: 'Gearbox'}
The value for 2 is Clutch
Updated auto_mobile {1: 'Engine', 2: 'Clutch', 3: 'Gearbox', 'four': 'chassis'} (1, 'Engine')
The current auto_mobile parts is : {2: 'Clutch', 3: 'Gearbox', 'four': 'chassis'}
Is 2 available in automobile parts True
and verified. .
Result:
Thus the python program to implement automobile using dictionaries is executed
and verified. .
Ex : 5.3
Elements of a civil structure
Date:
Aim:
Program:
civil_ele={}
print(civil_ele)
civil_ele=dict([(1,"Beam"),(2,"Plate")])
print(" the elements of civil structure are ",civil_ele)
print(" the value for key 1 is :",civil_ele[1])
civil_ele['three']='concrete'
print(civil_ele)
new=civil_ele.copy()
print(" The copy of civil_ele",new)
print(" The length is
",len(civil_ele)) for i in civil_ele:
print(civil_ele[i])
.
OUTPUT :
{}
the elements of civil structure are {1: 'Beam', 2: 'Plate'}
the value for key 1 is : Beam
{1: 'Beam', 2: 'Plate', 'three': 'concrete'}
The copy of civil_ele {1: 'Beam', 2: 'Plate', 'three':
'concrete'} The length is 3
Beam
Plate
Concrete
Result:
Thus the python program to implement elements of a civil structure using
dictionaries is executed and verified. .
Ex : 6.1
GCD of given numbers using Euclid's Algorithm.
Date:
Aim:
To write a python program to find gcd of given numbers using Euclids algorithm.
Algorithm:
Program:
Output :
Enter the value of a 24
Enter the value of b
54
The greatest common divisor is 6
Result:
Thus the python program to find gcd of given num.bers using Euclid’s method is executed and
the results are verified.
Ex : 6.2
Square root of a given number using newtons method.
Date:
Aim:
To write a python program to find to find square root of a given number using newtons method.
Algorithm:
Program:
def newtonSqrt(n):
approx = 0.5 * n
better = 0.5 * (approx +
n/approx) while(better !=
approx):
approx = better
better = 0.5 * (approx +
n/approx) return approx
n=int(input("Enter the number"))
result=newtonSqrt(n)
print("The Square root for the given number is",result)
.
OUTPUT :
Enter the number 25
The Square root for the given number is 5.0
Result:
Thus the python program to find square root of given number using newtons method is executed and
the results are verified. .
Ex : 6.3
Factorial of a number using functions
Date:
Aim:
To write a python program to find the factorial of a given number by using functions.
Algorithm:
Program:
def factorial(n):
if n==0:
return 1
else:
return n * factorial(n-1)
n=int(input("Input a number to compute the factiorial : "))
print(factorial(n)
OUTPUT :
Input a number to compute the factorial :
5 120
Result:
Thus the python program to find the factorial of a given number by using
functions is executed and the results are verified. .
functions is executed and the results are verified. .
Ex : 6.4
largest number in a list using functions
Date:
Aim:
To write a python program to find the largest number in the list.
Algorithm:
Step 1: Start the program.
Step 2: Read the limit of the list as n.
Step 3: Read n elements into the list.
Step 4: Let large = list[0]
Step 5: Execute for loop i= 1 to n and repeat the following steps for the value of n until the
condition becomes false.
Step 5.1: if next element of the list > large then
Step 5.1.1: large = element of the list
Step 6: Print the large value.
Step 7: Stop the program.
Program:
def largest(n):
list=[]
print("Enter list elements one by
one") for i in range(0,n):
x=int(input())
list.append(x)
print("The list elements
are") print(list)
large=list[0]
for i in
range(1,n):
if(list[i]>large):
large=list[i]
print("The largest element in the list
is",large) n=int(input("Enter the limit"))
largest(n)
.
OUTPUT :
Enter the limit5
Enter list elements one by
one 10
20
30
40
50
The list elements
are [10, 20, 30, 40,
50]
The largest element in the list is 50
Result:
.
is executed and the results are verified.
Thus the python program to find the largest number in the list by using functions
.
is executed and the results are verified.
Ex : 6.5
Area of shapes
Date:
Aim:
To write a python program for area of shape using functions.
Algorithm:
.
Program:
def rect(x,y):
return x*y
def circle(r):
PI = 3.142
return PI * (r*r)
def triangle(a, b,
c):
Perimeter = a + b +
c s = (a + b + c) / 2
Area = math.sqrt((s*(s-a)*(s-b)*(s-c)))
print(" The Perimeter of Triangle = %.2f"
%Perimeter) print(" The Semi Perimeter of Triangle =
%.2f" %s) print(" The Area of a Triangle is %0.2f"
%Area)
def parallelogram(a, b):
return a * b;
# Python program to compute area of rectangle
l = int(input(" Enter the length of rectangle :
"))
b = int(input(" Enter the breadth of rectangle :
")) a = rect(l,b)
print("Area =",a)
# Python program to find Area of a circle
num=float(input("Enter r value of
circle:")) print("Area is %.6f" %
circle(num))
# python program to compute area of triangle
import math
triangle(6, 7, 8)
# Python Program to find area of
Parallelogram Base = float(input("Enter the
Base : "))
Height = float(input("Enter the Height :
")) Area =parallelogram(Base, Height)
print("The Area of a Parallelogram = %.3f" %Area)
.
Output:
Area = 6
Enter r value of
circle:2 Area is
12.568000
.
Result:
Thus the python program for area of shape using functions is executed and the
results are verified
.
Ex : 7.1
Date: Reverse of a string
Aim:
To write a python program for reversing a string..
Algorithm:
Step 1: Start the program.
Step 2: Read the value of a string value by using function call reversed_string
. Step 3: if len(text)==1 return text.
Step 4: else return
reversed_string(text[1:])+text[:1].
Step 5: Print a
Step 6: Stop the program
Program:
def reversed_string(text):
if len(text) == 1:
return text
return reversed_string(text[1:])+text[:1]
a=reversed_string("Hello, World!")
print(a)
Output:
dlroW ,olleH
Result:
Thus the python program for reversing a .string is executed and the results
verified. are
Ex : 7.2
Palindrome of a string
Date:
Aim:
To write a python program for palindrome of a string.
Algorithm:
Step 1: Start the program.
Step 2: Read the value of a string value by using input method.
Step 3: if string==string[::-1], print “ the string is palindrome ”.
Step 4: else print “ Not a palindrome ”.
Step 5: Stop the program
Program:
string=input(("Enter a
string:")) if(string==string[::-
1]):
print("The string is a
palindrome") else:
print("Not a palindrome")
Output:
Enter a string: madam
The string is a
palindrome Enter a
string: nice
Not a palindrome
are verified. .
Result:
Thus the python program for palindrome of a string is executed and the results
are verified. .
Ex : 7.3
Character count of a string
Date:
Aim:
To write a python program for counting the characters of string.
Algorithm:
Program:
Output:
enter the string hai
Total number of characters in a string: 3
verified.
.
Result: Thus the python program for counting the characters of string is executed and the results are
verified.
.
Ex : 7.4
Replace of a string
Date:
Aim:
To write a python program for replacing the characters of a string.
Algorithm:
Program:
Output:
String after replacing with given
character: Once in a blue mhhn
Result:
Thus the python program for replacing the given characters of string is executed
and the results are verified.
60
Ex : 8.1
Convert list in to a Series using pandas
Date:
Aim:
To write a python program for converting list in to a Series.
Algorithm:
Program:
Output:
0 a
1 b
2 c
3 d
4 e
dtype: object
Result:
Thus the python program for converting list in to a series is executed
and the results are verified.
61
Ex : 8.2
Finding the elements of a given array is zero using numpy
Date:
Aim:
To write a python program for testing whether none of the elements of a given array is zero.
Algorithm:
Program:
import numpy as np
#Array without zero value
x = np.array([1, 2, 3, 4,])
print("Original array:")
print(x)
print("Test if none of the elements of the said array is zero:")
print(np.all(x))
#Array with zero value
x = np.array([0, 1, 2,
3]) print("Original
array:") print(x)
print("Test if none of the elements of the said array is zero:")
print(np.all(x))
Output:
0 a
1 b
2 c
3 d
4 e
dtype: object
Result:
Thus the python program for testing whether none of the elements of a given array is zero is
executed and the results are verified.
62
Ex : 8.3
Generate a simple graph using matplotlib
Date:
Aim:
To write a python program for generating a simple graph using matplotlib.
Algorithm:
Program:
Output:
Result:
Thus the python program for generating a simple graph using matplotlib zero is executed
and the results are verified.
63
Ex : 8.4
Solve trigonometric problems using scipy
Date:
Aim:
To write a python program for finding the exponents and solve trigonometric problems using
scipy.
Algorithm:
Program:
Output:
1000.0
8.0
1.0
0.707106781187
Result:
Thus the python program for finding the exponents and solve trigonometric problems using
scipy is executed and the results are verified.
64
Ex : 9.1
Copy text from one file to another
Date:
Aim:
To write a Python program for copying text from one file to another.
Algorithm:
Step 1 : Start
Step 2 : Create file named file.txt and write some data into it.
Step 3 : Create a file name sample.txt to copy the contents of the file
Step 4 : The file file.txt is opened using the open() function using the f stream.
Step 5 : Another file sample.txt is opened using the open() function in the write mode using the
f1 stream.
Step 6 : Each line in the file is iterated over using a for loop (in the input stream).
Step 7 : Each of the iterated lines is written into the output file.
Step 8 : Stop
Program:
with open("file.txt") as f:
with open("sample.txt", "w") as f1:
for line in f:
f1.write(line)
65
Output:
Result:
Thus the python program for copying text from one file to another is executed and the results
are verified.
66
Ex : 9.2
Command Line Arguments(Word Count)
Date:
Aim:
To write a Python program for command line arguments.
Algorithm:
Step1: Start
Step2: Import the package sys
Step3: Get the arguments in command line prompt
Step4: Print the number of arguments in the command line by using len(sys.argv) function
Step5: Print the arguments using str(sys.argv ) function
Step6: Stop
Program:
import sys
print('Number of arguments:',len(sys.argv),'arguments.')
print('Argument List:',str(sys.argv))
Output:
Number of arguments: 4 arguments.
Argument List: ['cmd.py', 'arg1', 'arg2',
'arg3']
Result:
Thus the Python program for command line arguments is executed successfully and the
output is verified.
67
68
Ex : 9.3
Find the longest word(File handling)
Date:
Aim:
To write a Python program for finding the longest words using file handling concepts.
Algorithm:
Program:
Output:
['hai', 'this', 'is', 'parvathy', 'how', 'are', 'you', 'all', 'read', 'well', 'all', 'best', 'for', 'university',
'exams.']
Result:
Thus the Python program finding the longest words using file handling concepts is executed
successfully and the output is verified.
69
Ex : 10.1
Date: Divide by zero error – Exception Handing
Aim:
To write a Python program for finding divide by zero error.
Algorithm:
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:
Enter First Number: 12.5
Invalid Input Please Input Integer...
Result:
Thus the Python program for finding divide by zero error is executed successfully and the
output is verified.
70
Ex : 10.2
Date: Voter’s age validity
Aim:
To write a Python program for validating voter’s age.
Algorithm:
Program:
def main():
#single try statement can have multiple except statements.
try:
age=int(input("Enter your age"))
if age>18:
print("'You are eligible to vote'")
else:
print("'You are not eligible to vote'")
except ValueError:
print("age must be a valid number")
except IOError:
print("Enter correct value")
#generic except clause, which handles any exception.
except:
print("An Error occured")
main()
71
Output:
Enter your age20.3
age must be a valid number
Result:
Thus the Python program for validating voter’s age is executed successfully and the output is
verified.
72
Ex : 10.2
Student mark range validation
Date:
Aim:
To write a python program for student mark range validation
Algorithm:
Program:
def main():
try:
mark=int(input(" Enter your mark:"))
if(mark>=50 and mark<101):
print(" You have passed")
else:
print(" You have failed")
except ValueError:
print(" It must be a valid number")
except IOError:
print(" Enter correct valid number")
except:
print(" an error occured ")
main()
73
Output:
Enter your mark:50
You have passed
Enter your mark:r
It must be a valid number
Enter your mark:0
You have failed
Result:
Thus the python program for student mark range validation is executed and verified.
74
Ex : 11
Exploring Pygame tool.
Date:
Pygame :
Result:
Thus the Python program for validating voter’s age is executed successfully and the output is
verified.
75
Ex : 11.1
Simulate Bouncing Ball Using Pygame
Date:
Aim:
To write a Python program to simulate bouncing ball in pygame.
Algorithm:
Step1: Start
Step3: Initialize the height, width and speed in which the ball bounce
Step5: Stop
Program:
pygame.init()
speed = [1, 1]
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Bouncing ball")
ball = pygame.image.load("Tree_Short.png")
ballrect = ball.get_rect()
while 1:
ballrect = ballrect.move(speed)
76
if ballrect.left < 0 or ballrect.right > width:
speed[0] = -speed[0]
speed[1] = -speed[1]
screen.fill(background)
screen.blit(ball, ballrect)
pygame.display.flip()
Execution Procedure:
Output:
Result:
Thus the Python program to simulate bouncing ball using pygame is executed successfully
and the output is verified.
77
Ex : 11.2
car race
Date:
Aim:
To write a Python program to simulate car race in pygame.
Algorithm:
Step1: Start
Step3: Initialize the height, width and speed in which the ball bounce
Step5: Stop
Program:
78
if event.type == KEYDOWN:
if event.key == K_ESCAPE: #escape quits
terminate()
return
def playerHasHitBaddie(playerRect, baddies):
for b in baddies:
if playerRect.colliderect(b['rect']):
return True
return False
def drawText(text, font, surface, x, y):
textobj = font.render(text, 1, TEXTCOLOR)
textrect = textobj.get_rect()
textrect.topleft = (x, y)
surface.blit(textobj, textrect)
# set up pygame, the window, and the mouse cursor
pygame.init()
mainClock = pygame.time.Clock()
windowSurface = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
pygame.display.set_caption('car race')
pygame.mouse.set_visible(False)
# fonts
font = pygame.font.SysFont(None, 30)
# sounds
gameOverSound = pygame.mixer.Sound('music/crash.wav')
pygame.mixer.music.load('music/car.wav')
laugh = pygame.mixer.Sound('music/laugh.wav')
# images
playerImage = pygame.image.load('image/car1.png')
car3 = pygame.image.load('image/car3.png')
car4 = pygame.image.load('image/car4.png')
playerRect = playerImage.get_rect()
baddieImage = pygame.image.load('image/car2.png')
sample = [car3,car4,baddieImage]
wallLeft = pygame.image.load('image/left.png')
wallRight = pygame.image.load('image/right.png')
"Start" screen
drawText('Press any key to start the game.', font, windowSurface, (WINDOWWIDTH / 3) - 30,
(WINDOWHEIGHT / 3))
drawText('And Enjoy', font, windowSurface, (WINDOWWIDTH / 3), (WINDOWHEIGHT / 3)+30)
pygame.display.update()
waitForPlayerToPressKey()
zero=0
if not os.path.exists("data/save.dat"):
f=open("data/save.dat",'w')
79
f.write(str(zero))
f.close()
v=open("data/save.dat",'r')
topScore = int(v.readline())
v.close()
while (count>0):
# start of the game
baddies = []
score = 0
playerRect.topleft = (WINDOWWIDTH / 2, WINDOWHEIGHT - 50)
moveLeft = moveRight = moveUp = moveDown = False
reverseCheat = slowCheat = False
baddieAddCounter = 0
pygame.mixer.music.play(-1, 0.0)
while True: # the game loop
score += 1 # increase score
for event in pygame.event.get():
if event.type == QUIT:
terminate()
if event.type == KEYDOWN:
if event.key == ord('z'):
reverseCheat = True
if event.key == ord('x'):
slowCheat = True
if event.key == K_LEFT or event.key == ord('a'):
moveRight = False
moveLeft = True
if event.key == K_RIGHT or event.key == ord('d'):
moveLeft = False
moveRight = True
if event.key == K_UP or event.key == ord('w'):
moveDown = False
moveUp = True
if event.key == K_DOWN or event.key == ord('s'):
moveUp = False
moveDown = True
if event.type ==
KEYUP:
if event.key ==
ord('z'):
reverseCheat = False
score = 0
if event.key == ord('x'):
slowCheat = False
score = 0
80
if event.key == K_ESCAPE:
81
terminate()
if event.key == K_LEFT or event.key == ord('a'):
moveLeft = False
if event.key == K_RIGHT or event.key == ord('d'):
moveRight = False
if event.key == K_UP or event.key == ord('w'):
moveUp = False
if event.key == K_DOWN or event.key == ord('s'):
moveDown = False
# Add new baddies at the top of the screen
if not reverseCheat and not slowCheat:
baddieAddCounter += 1
if baddieAddCounter == ADDNEWBADDIERATE:
baddieAddCounter = 0
baddieSize =30
newBaddie = {'rect': pygame.Rect(random.randint(140, 485), 0 - baddieSize, 23, 47),
'speed': random.randint(BADDIEMINSPEED, BADDIEMAXSPEED),
'surface':pygame.transform.scale(random.choice(sample), (23, 47)),
}
baddies.append(newBaddie)
sideLeft= {'rect': pygame.Rect(0,0,126,600),
'speed': random.randint(BADDIEMINSPEED, BADDIEMAXSPEED),
'surface':pygame.transform.scale(wallLeft, (126, 599)),
}
baddies.append(sideLeft)
sideRight= {'rect': pygame.Rect(497,0,303,600),
'speed': random.randint(BADDIEMINSPEED, BADDIEMAXSPEED),
'surface':pygame.transform.scale(wallRight, (303, 599)),
}
baddies.append(sideRight)
for b in baddies:
if not reverseCheat and not slowCheat:
b['rect'].move_ip(0, b['speed'])
82
elif reverseCheat:
b['rect'].move_ip(0, -5)
elif slowCheat:
b['rect'].move_ip(0, 1)
for b in baddies[:]:
if b['rect'].top > WINDOWHEIGHT:
baddies.remove(b)
# Draw the game world on the window.
windowSurface.fill(BACKGROUNDCOLOR)
# Draw the score and top score.
drawText('Score: %s' % (score), font, windowSurface, 128, 0)
drawText('Top Score: %s' % (topScore), font, windowSurface,128, 20)
drawText('Rest Life: %s' % (count), font, windowSurface,128, 40)
windowSurface.blit(playerImage, playerRect)
for b in baddies:
windowSurface.blit(b['surface'], b['rect'])
pygame.display.update()
# Check if any of the car have hit the player.
if playerHasHitBaddie(playerRect, baddies):
if score > topScore:
g=open("data/save.dat",'w')
g.write(str(score))
g.close()
topScore = score
break
mainClock.tick(FPS)
# "Game Over" screen.
pygame.mixer.music.stop(
) count=count-1
gameOverSound.play()
time.sleep(1)
if (count==0):
laugh.play()
drawText('Game over', font, windowSurface, (WINDOWWIDTH / 3), (WINDOWHEIGHT / 3))
drawText('Press any key to play again.', font, windowSurface, (WINDOWWIDTH / 3) - 80,
(WINDOWHEIGHT / 3) + 30)
pygame.display.update()
time.sleep(2)
waitForPlayerToPressKey()
count=3
gameOverSound.stop()
83
Execution Procedure:
Output:
Result:
Thus the Python program to simulate car race using pygame is executed successfully and the
output is verified.
84