Python Programming Practicals Guide
Python Programming Practicals Guide
Course Outcomes: (for students: To know what they are going to learn)
CO1: To understand the problem-solving approaches
CO2: To learn the basic programming constructs in Python
CO3: To practice various computing strategies for Python-based solutions to real world problems CO4: To use Python
data structures - lists, tuples, dictionaries.
CO5: To do input/output with files in Python.
List of Programs
1. Program to convert the given temperature from Fahrenheit to Celsius and vice versa depending upon user’s
choice.
2. Write a Python program to construct the following pattern, using a nested loop
* ** *** ****
***********
*******
****
3. Program to calculate total marks, percentage and grade of a student. Marks obtained in each of the five subjects
are to be input by user. Assign grades according to the following criteria: Grade A: Percentage >=80 Grade B:
Percentage >=70 and 80 Grade C: Percentage >=60 and =40 and < 40
4. Program, to find the area of rectangle, square, circle and triangle by accepting suitable input parameters from
user.
5. Write a Python script that prints prime numbers less than 20.
7. Write a Python program to count the number of even and odd numbers from array of N numbers.
9. Given a tuple and a list as input, write a program to count the occurrences of all items of the list in the tuple.
(Input: tuple = ('a', 'a', 'c', 'b', 'd'), list = ['a', 'b'], Output: 3)
10. Create a Savings Account class that behaves just like a Bank Account, but also has an interest rate and a
method that increases the balance by the appropriate amount of interest (Hint: use Inheritance).
11. Read a file content and copy only the contents at odd lines into a new file.
14. Create a menu driven Python program with a dictionary for words and their meanings.
Aim:
To write a Python program to convert the given temperature from Fahrenheit to Celsius and vice
Versa depending upon user’s choice.
Algorithm:
Step 1: Start.
Step 2: Read the value of ch.
Step 3: If ch==1,then perform the following operations:
i) Read the value of f.
i) Calculate c=(5/9)*(f-32).
ii) Print the value of c.
Step 4: Else if ch==2,then perform the following operations:
i) Read the value of c.
ii) Calculate f=(9/5)*c+32.
iii) Print the value off.
Step 5: Else, print the message “Wrong Choice”.
Step 6: Stop.
Flow chart
Start
Read ch
False True
If ch==1:
If ch==2: Read f
False True
f=(9/5)*c+32 Printc
Print f
Stop
Program:
#Temp_Conversion.py
print("[Link] to Celsius Conversion")
print("[Link] to Fahrenheit Conversion")
ch=int(input("Enter Your Choice: "))
if ch==1:
f=int(input("Enter the temperature in Fahrenheit:"))
c=(5/9)*(f - 32)
print(f,"Degree Fahrenheit is equal to %.2f " % c,"Degree Celsius")
elif ch==2:
c=int(input("Enter the temperature in Celsius:"))
f = (9/5)*c + 32
print(c,"Degree Celsius is equal to %.2f " %f ,"Degree Fahrenheit")
else:
print("WrongChoice.")
Output:
Result:
Thus, the temperature conversion program using Python has been executed successfully.
2. PYTHON PROGRAM TO CONSTRUCT STAR PATTERN USING NESTED LOOP
Aim:
To write a python program to construct star pattern using nested loop.
Algorithm:
Step 1: Start
Step 2 : Input n (user must enter a value less than 10)
Step 3 : Initialize i to 0
Step 4 : Loop (i from 0 to n+1):
Step 5 : Initialize string to " "
Step 6 : Loop (j from 1 to i):
Step 7 : Append "*" to string
Step 8 : Print string centered in a field of width 10
Step 9 : Initialize i to n+1
Step 10 : Loop (i from n+1 to 0, decrementing i by 1 each time):
Step 11 : Initialize string to " "
Step 12 : Loop (j from 1 to i):
Step 13 : Append "*" to string
Step 14 : Print string centered in a field of width 10
Step 15 : Stop
Flowchart:
Start
Read n
for i in range(0,n+1):
Print i
Next
Print a string *
Next
for i in range(n+1,0,-1):
for j in range(1,i):
Print i
Next
Print string
Next
Stop
Program:
Output:
enter a value less than 10:6
*
**
***
****
*****
******
*****
****
***
**
*
Result:
Thus the program to construct the star pattern using nested loop has been successfully executed.
3. CALCULATING THE TOTAL MARKS,PERCENTAGE AND GRADE OF A
STUDENT
Aim:
To write a Python program to read five subject marks and calculate the total marks,
percentage and grade of a student.
Algorithm:
Step 1 : Start.
Step 2 : Read the values of Roll_No,Stud_Name,M1,M2,M3,M4andM5.
Step 3 :Calculate Total=M1+M2+M3+M4+M5.
Step 4 :Calculate Percentage=Total/5.
Step 5 : If Percentage>=80,then calculate Grade=”A”.
Step 6 : Else If Percentage >=70 and Percentage<80, then calculate Grade=”B”.
Step 7 : Else If Percentage >=60 and Percentage<70, then calculate Grade=”C”.
Step 8 : Else If Percentage >=40and Percentage<60, then calculate Grade=”D”.
Step9 : Else, calculate Grade="E”.
Step10 :Print the values of Roll_No, Stud_Name, M1, M2, M3, M4, M5, Total, Percentage
and Grade.
Step11: Stop.
Flowchart:
Start
Total=M1+M2+M3+M4+M5
Percentage=Total/5
True if False
Percentage>=80:
Grade=”A”
False if True
Percentage>=70:
Grade=”C”
True if
False
Percentage>=40:
Grade=”D”
Grade=”E”
Stop
Program:
#Mark_List.py
import os
[Link]('cls')
Roll_No=int(input("Enter the Roll Number: "))
Stud_Name=input("Enter the Student Name:")
M1=int(input("Enter the Mark1 : "))
M2=int(input("Enter the Mark2 : "))
M3=int(input("Enter the Mark3 : "))
M4=int(input("Enter the Mark4 : "))
M5=int(input("Enter the Mark5 : "))
Total=M1+M2+M3+M4+M5
Percentage=Total/5 if Percentage>=80:
Grade="A"
elif Percentage>=70 and Percentage<80:
Grade="B"
elif Percentage>=60and Percentage<70:
Grade="C"
elif Percentage>=40 and Percentage<60:
Grade="D"
else:
Grade="E"
print("Roll Number :",Roll_No)
print("StudentName :",Stud_Name)
print("Mark1 :",M1)
print("Mark2 :",M2)
print("Mark3 :",M3)
print("Mark4 :",M4)
print("Mark5 :",M5)
print("Total :",Total)
print("Average :",Percentage)
print("Grade :",Grade)
Output:
Result:
Thus, the Python program to calculate the Total and Grade of a student has been executed
successfully.
4. FINDING THE AREA OF A RECTANGLE, SQUARE ,CIRCLE AND TRIANGLE
Aim:
To write a Python program to find the area of a Rectangle, Square, Circle and Triangle by
accepting suitable input parameters from user.
Algorithm:
Step1: Start.
Step2: Read the value of Shape.
Step3: If Shape=”Rectangle”,then call the function Rectangle(),which will calculate the
area of a Rectangle.
Step4: If Shape=”Square”,then call the function Square(),which will calculate the area of a
Square.
Step5: If Shape=”Circle”,then call the function Circle(),which will calculate the area of a Circle.
Step6: IfShape=”Triangle”,then call the functionTriangle(),which will calculate the area of a
Triangle.
Step7: Else print the message “Select a Valid Shape”.
Step8: Stop.
Program:
Program:
#Rect_Square_Circle_Triangle_Area.py
#Function to calculate the area of a Rectangle
def Rectangle():
l=float(input("Enter the Length of a Rectangle: "))
b=float(input("Enter the Breadth of a Rectangle:"))
R_Area= l* b
print("\nThe Area of a Rectangle is:%0.2f" %R_Area)
return
1. Rectangle
2. Square
3. Circle
4. Triangle
Enter the shape you want to calculate the area: Rectangle
Enter the Length of a Rectangle: 10
Enter the Breadth of a Rectangle: 20
1. Rectangle
2. Square
3. Circle
4. Triangle
Enter the shape you want to calculate the area:Circle
Enter the radius of a Circle: 10
Result:
Thus the program to find the area of a Rectangle, Square, Circle and Triangle by accepting suitable
input parameters from user has been successfully executed.
5. WRITE A PYTHON SCRIPT THAT PRINTS PRIME NUMBERS LESS THAN 20.
Aim:
To Write a Python script that prints prime numbers less than 20.
Algorithm:
Step 1 : Start.
Step 2 : Initialize a function is_prime
Step 3 : Read the value of n.
i) If num is less than 2, return False.
ii) For each integer i in the range from 2 to the square root of num
iii) Check if num modulo i equals 0 (i.e., num % i == 0). If true, return False.
Step 4 : If no divisors are found in the loop, return True.
Step 5 : Iterate over integers num from 2 to 19.
i) For each num, call is_prime(num).
ii) If is_prime(num) returns True, print num.
Flowchart:
Start
Initialize num=2
if num<2
Return false
Check | | Prime?
Print prime
Increment by 1
Stop
Program:
Output:
2
3
5
7
11
13
17
19
Result:
Thus, the Python program to find a Python script that prints prime numbers less
than 20 has been executed successfully.
6. FACTORIAL OF A NUMBER USING RECURSION
Aim:
To write a Python program to find the factorial value of a given number using
Recursion.
Algorithm:
Step 1 : Start.
Step 2 : Define a function named fact().
Step 3 : Read the value of n.
Step 4 : Call the function fact().
Step 5 : Print the factorial value.
Step 6 : Stop.
Flowchart:
Start
Read n
Print n, f
Stop
#Function Definition
def fact(m):
True False
if
m<=1
:
# Main Program
n=int(input("Enter the value of n: "))
f=fact(n)
print("The factorial of",n,"is",f)
Output:
Result:
Thus, the Python program to find the factorial value of a given number has been
executed successfully.
7. COUNTING THE EVEN AND ODD NUMBERS FROM AN ARRAY OF N NUMBERS
Aim:
To write a Python program to count the Even and Odd numbers in an array of N
numbers.
Algorithm:
Step 1 : Start.
Step 2 : Initialize the array a.
Step 3 : Initialize Event_Count=0, Odd_Count=0.
Step 4 : Read the value of N.
Step 5 : Iterate each element in the list using for loop and check if i % 2 == 0, the
condition to check even numbers.
Step 6 : If the condition satisfies, then increase Even_Count else increase Odd_Count.
Step 7 : Print the number of even numbers.
Step 8 : Print the number of odd numbers.
Step 9 : Stop.
Flowchart:
Program:
#[Link] Program to Count the number of even and odd numbers from an array of N
numbers
#Even_Odd_Count1.py
a=[]
Even_Count=0
Odd_Count=0
N=int(input("Enter the total number of elements in the array: "))
for i in range(1,N+1):
x=int(input("Enter the %d element: " %i))
[Link](x)
for i in a:
if i%2==0:
Even_Count=Even_Count+1
else:
Odd_Count=Odd_Count+1
print("Total Number of Even Numbers in the array = ", Even_Count)
print("Total Number of Odd Numbers in the array = ", Odd_Count)
Output:
Result:
Thus, the Python program to count the Even and Odd numbers in an array has been
executed successfully.
8. WRITE A PYTHON CLASS TO REVERSE A STRING WORD BY WORD
Aim:
Algorithm:
STEP 3: Split the input string str_to_rev into a list of words words_list using the space
character as the delimiter.
STEP 7: join reversed_words into a single string with spaces -> reversed_string
for i in range(len(words)):
end
Program:
class stringreverser:
def reverse_words(self,s):
#split the string into words
words=[Link](" ")
#reverse the order of words
words=words[::-1]
reversed_string=""
#reverse each words
for i in range(len(words)):
val=words[i]
val=val[::-1]
reversed_string=" ".join([reversed_string,val,""])
return reversed_string
reverser=stringreverser()
strtorev=input("enter a string to reverse word:")
reversed_string=reverser.reverse_words(strtorev)
print("reversed string:",reversed_string)
Output:
enter a string to reverse word:PYTHON
reversed string: NOHTYP
Result:
Thus, the Python program class to reverse a string word by word has been executed
successfully.
9. GIVEN A TUPLE AND A LIST AS INPUT, WRITE A PROGRAM TO COUNT THE
OCCURRENCES OF ALL ITEMS OF THE LIST IN THE TUPLE.
Aim:
To write a program to count the occurrences of all items of the list in the tuple.
Algorithm:
STEP1: Start the Program
STEP 2: Initialize an Empty Dictionary
STEP 3: Process the Tuple:
i) Convert the tuple_data to a set set1 to identify unique elements.
ii) For each element item in set1:
o Count the occurrences of item in tuple_data.
o Store this count in the occurrences dictionary with item as the key.
STEP 4: Process the List
i) Convert the list_data to a set set2 to identify unique elements.
ii) For each element item in set2:
o Count the occurrences of item in list_data.
o If item already exists in the occurrences dictionary, add the count from list_data to
the existing count.
o If item does not exist in the occurrences dictionary, store the count from list_data
in the dictionary.
STEP 5: Return the occurrences dictionary containing the combined counts of each unique
element from both tuple_data and list_data.
STEP 6: Stop the program
Flow chart
False True
Program:
def count_occurrences(tuple_data,list_data):
occurrences={}
set1=set(tuple_data)
count=tuple_data.count(item)
occurrences[item]=count
set2=set(list_data)
count=list_data.count(item)
occurrences[item]=[Link](item,0)+count
return occurrences
tuple_data=('a','a','b','c','d')
list_data=['a','a','b','b']
result=count_occurrences(tuple_data,list_data)
print(result)
Output:
Result:
Thus the python program to count the occurrences of all items of the list in the tuple has been
executed successfully.
3. CREATE A SAVINGS ACCOUNT CLASS THAT BEHAVES JUST LIKE A BANK
ACCOUNT, BUT ALSO HAS AN INTEREST RATE AND A METHOD THAT
INCREASES THE BALANCE BY THE APPROPRIATE AMOUNT OF INTEREST
Aim:
To write a Python program to create a Savings Account class that behaves just like a Bank
Account, but also has an interest rate and a method that increases the balance by the appropriate
amount of interest.
Algorithm:
Flowchart:
Program:
class Person(object):
def init (self):
[Link] = input("Enter name: ")
[Link] = input("Enter address: ")
[Link] = int(input("Enter phone number: "))
def display_person(self):
print("Name:", [Link])
print("Address:", [Link])
print("Phone:", [Link])
class DepositAccount(Person):
def init (self):
super(). init ()
[Link] = input("Enter Account Number: ")
[Link] = int(input("Enter Amount to Deposit: "))
[Link] = 0
def display_account(self):
print("Account Number:", [Link])
self.display_person()
print("Deposit Amount:", [Link])
print("Interest Amount:", [Link])
Output:
Result:
Thus, the Python program to calculate the Total and Grade of a student has been executed
successfully.
11. READING A FILE AND COPY ONLY THE ODD LINES INTO A NEW FILE
Aim:
To write a Python Program to read a file and copy only the odd lines into a new file.
Algorithm:
STEP 1 : Start
STEP 2 : Open the first file in read mode.
STEP 3 : Assign the first file to F1.
STEP 4 : Open the second file in write mode.
STEP 5 : Assign the second file to F2.
STEP 6 : Read the content line by line of the file F1 and assign it to File1_Cont.
STEP 7 : Access each element from 0 to length of File1_Cont.
STEP 8 : Check if i is not divisible by 2 then write the content in F2 else pass.
STEP 9 : Close the file F1.
STEP 10 : Now open [Link] in read mode and assign it to F2.
STEP 11 : Read the content of the file F2 and assign it to File2_Cont.
STEP 12 : Print the content of the file F2.
STEP 13 : Close the files F1 and F2.
STEP 14 : Stop.
Flowchart:
Program:
Output:
Result:
Thus, the Python program to read a file and copy only the odd lines into a new file
has been executed successfully.
12. CREATING A TURTLE GRAPHICS WINDOW WITH THE SPECIFIED SIZE
Aim:
To write a Python Program to create a turtle graphics window with the specified size.
Algorithm:
Step 1 : Start.
Step 2 : Import the Turtle module using the import turtle statement.
Step 3 : Set the window size using the setup() method.
Step 4 : Create a graphics window using the Screen() method.
Step 5 : Change the background color of the turtle graphics window using the bgcolor()
method.
Step 6 : Assign a title for the window using the title() method. Step 7 : Stop.
Flowchart:
Start
Stop
Program:
# [Link] Program to create a Turtle Graphics Window with the Specified Size
# Turt_Win.py
import turtle
# Loads the turtle module
[Link](500, 300)
# Set the window size to 500 by 300 pixels
wn = [Link]()
# Creates a graphics window
[Link]("Cyan")
[Link]("Turtle Graphics Window")
Output:
Result:
Thus, the Python program to create a Turtle Graphics Window with the specified size
has been executed successfully.
13. TOWERS OF HANOI USING RECURSION
Aim:
Algorithm:
STEP 1 : Start.
STEP 2 : Define a function named Tower_Of_Hanoi().
STEP 3 : Read the number of Disks.
STEP 4 : Move top (n-1) disks from source to auxiliary peg.
STEP 5 : Move 1 disk from source to destination peg.
STEP 6 : Move top (n-1) disks from auxiliary to destination.
STEP 7 : Stop.
Flowchart:
Program:
# Main Program
n = int(input("Enter the number of Disks: "))
Tower_Of_Hanoi(n, 'A', 'B', 'C')
# A, B, C are the names of rods
Output:
Result:
Thus, the Python Program for Towers of Hanoi using Recursion has been executed
successfully.
14. MENU DRIVEN PYTHON PROGRAM WITH A DICTIONARY OF WORDS
AND THEIR MEANINGS
Aim:
To write a menu driven Python program with a dictionary of words and their meanings.
Algorithm:
STEP 1 : Start.
STEP 2 : Create a dictionary class named My_Dict.
STEP 3 : Define two functions namely init() and add() within the My_Dict class.
STEP 4 : The init() method is used to initialize the object.
STEP 5 : The add() method is used to add the Key / Value pair into the dictionary object.
STEP 6 : Create a dictionary object named Dict_Obj.
STEP 7 : Read the value of ch.
STEP 8 : If ch==1, then perform the following operations:
i) Read the number of Key / Value pair in the dictionary object.
ii) Using while loop, perform the following operations:
a. Read the Key.
b. Read the Value.
c. Add the Key / Value pair into the dictionary object.
STEP 9 : If ch==2, then print the dictionary object.
STEP 10 : if choice==3, then exit the program else print the message “Wrong Choice”.
STEP 11 : Read the value of ans.
STEP 12 : If ans==’Y’, then go to Step 7.
STEP 13 : Stop.
Program:
# Creating the dictionary class
class My_Dict(dict):
def init (self):
# The “ init " method is used to initialize the object
self = dict()
# The "self" keyword represents the same object or instance of the class
# Main Function
Dict_Obj = My_Dict()
ans = 'Y'
if ch == 1:
n = int(input("Enter the number of Key/Value pairs in the dictionary: "))
i=1
while i <= n:
Key = input("Enter the Word: ")
Value = input("Enter the Meaning: ")
Dict_Obj.add(Key, Value)
i += 1
elif ch == 2:
print("The Dictionary Object is:")
print(Dict_Obj)
elif ch == 3:
print("Exiting the program.")
exit()
else:
print("Wrong Choice")
MENU
********************
1. Create a Dictionary
2. Print the Dictionary
3. Exit
********************
Enter Your Choice: 1
Enter the no of Key / Value pair in a dictionary: 4
Enter the Word: Booting
Enter the Meaning: Starting
Enter the Word: Joy
Enter the Meaning: Happy
Enter the Word: Seldom
Enter the Meaning: Rarely
Enter the Word: RAM
Enter the Meaning: Random Access Memory
MENU
********************
1. Create a Dictionary
2. Print the Dictionary
3. Exit
********************
Enter Your Choice: 2
The Dictionary Object is
{'Booting': 'Starting', 'Joy': 'Happy', 'Seldom': 'Rarely', 'RAM': 'Random Access Memory'}
MENU
********************
1. Create a Dictionary
2. Print the Dictionary
3. Exit
********************
Enter Your Choice: 3
Result:
Thus, the menu driven Python program with a dictionary of words and their meanings
has been exe successfully.
15. IMPLEMENTATION OF HANGMAN GAME USING PYTHON
Aim:
Algorithm:
STEP 1 : Start.
STEP 2 : Import the random module into the program.
STEP 3 : Create an empty list named words.
STEP 4 : Read the value of n.
STEP 5 : Using for loop, read the words one by one and store the words into the list.
STEP 6 : In this game, the interpreter will choose one random word from a list of words.
STEP 7 : Read the name of the user.
STEP 8 : Read the alphabet to guess.
STEP 9 : If the random word contains that alphabet, it will be shown as the output (with
correct placement) else the program will prompt us to guess another alphabet.
STEP 10 : Read the number of turns.
STEP 11 : The user will be given the number of turns to guess the complete word.
STEP 12 : Stop.
Flowchart:
Start
Import the
random module
Create an empty
list named words
Read n
for i in range(1,n+1):
Read w
Next
name
Read guess
Read turns
Stop
Program:
import random
# Function will choose one random word from this list of words
word = [Link](words)
Guess a Character: a
w
a
_
_
_
Guess a Character: t
w
a
t_
_
Guess a Character: e
w
a
t
e_
Guess a Character: r
w
a
t
er
You Win
The word is: water
Result:
Thus, the Python program to implement the Hangman game has been executed
successfully.
********************