0% found this document useful (0 votes)
115 views53 pages

Python Programming Practicals Guide

Uploaded by

narendiran639
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
115 views53 pages

Python Programming Practicals Guide

Uploaded by

narendiran639
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

THIRUTHANGAL NADAR COLLEGE

(Belongs to the Chennaivazh Thiruthangal Hindu Nadar Uravinmurai Dharma Fund)

A Self Financing Co-Educational College of Arts & Science


Affiliated to the University of Madras
Re-accredited ‘B++’ Grade by NAAC &An ISO 9001:2015
Certified Institution Selavayal, Chennai, Tamil Nadu, India

Department : BSc COMPUTER SCIENCE


Class : I BSc (CS) B
Subject Name : PYTHON PROGRAMMING PRACTICALS
Subject Code : 125C11
Prepared By : S. KAVIPRIYA

Learning Objectives: (for teachers: what they have to do in the class/lab/field)


 Acquire programming skills in core Python.
 Acquire Object-oriented programming skills in Python.
 Develop the skill of designing graphical-user interfaces (GUI) in Python.
 Develop the ability to write database applications in Python.
 Acquire Python programming skills to move into specific branches

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.

6. Program to find factorial of the given number using recursive function.

7. Write a Python program to count the number of even and odd numbers from array of N numbers.

8. Write a Python class to reverse a string word by word.

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.

12. Create a Turtle graphics window with specific size.

13. Write a Python program for Towers of Hanoi using recursion

14. Create a menu driven Python program with a dictionary for words and their meanings.

15. Devise a Python program to implement the Hangman Game.


1. FAHRENHEIT TO CELSIUS CONVERSION AND CELSIUS TO FAHRENHEIT
CONVERSION

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

Print“Wrong Choice” Read c c=(5/9)*(f-32)

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:

1. Fahrenheit to Celsius Conversion


2. Celsius to Fahrenheit Conversion
Enter Your Choice: 1
Enter the temperature in Fahrenheit: 100
Degree Fahrenheit is equal to 37.78 Degree Celsius
>>>
1. Fahrenheit to Celsius Conversion
2. Celsius to Fahrenheit Conversion
Enter Your Choice: 2
Enter the temperature in Celsius: 40
Degree Celsius is equal to 104.00 Degree Fahrenheit
>>>

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):

for j in range(1, i):

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:

#program to display a pattern


n=int(input("enter a value less than 10:"))
for i in range (0,n+1):
string= " "
for j in range (1,i):
string=string+"*"
print(format(string,"^10"))
for i in range (n+1,0,-1):
string=" "
for j in range(1,i):
string=string+"*"
print(format(string,"^10"))

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

Read Roll_No, Stud_Name,


M1, M2, M3, M4, M5

Total=M1+M2+M3+M4+M5

Percentage=Total/5

True if False
Percentage>=80:

Grade=”A”

False if True
Percentage>=70:

True False Grade=”B”


if
Percentage>=60:

Grade=”C”
True if
False
Percentage>=40:

Grade=”D”
Grade=”E”

Print Total, Percentage, Grade

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:

Enter the Roll Number 1001


Enter the Student Name : AkashKumar
Enter the Mark1 90
Enter the Mark2 87
Enter the Mark3 98
Enter the Mark4 87
EntertheMark5 100

Enter the Roll Number 1001


Enter the Student Name : AkashKumar
Mark1 90
Mark2 87
Mark3 98
Mark4 87
Mark5 100
Total 462
Average : 92.4
Grade :A
>>>

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

#Function to calculate the area of a Square


def Square():
s=int(input("Enter the side length of a Square:"))
S_Area=s*s
print("\nThe Area of a Square is:",S_Area)
return

#Function to calculate the area of a Circle def Circle():


PI=3.14
r=float(input("Enter the radius of a Circle:"))
C_Area=PI*r*r
print("\nThe Area of a Circle is:%0.2f" %C_Area)
return

#Function to calculate the area of a Triangle def Triangle():


a=int(input("Enter the first side of a Triangle:"))
b=int(input("Enter the second side of a Triangle :"))
c=int(input("Enter the third side of a Triangle:")) s=(a+b+c)/2
T_Area=(s*(s-a)*(s-b)*(s-c))**0.5
print("The Area of a Triangle is:%0.2f" %T_Area)
return

# Main Program print("[Link]")


print("2. Square")
print("3. Circle")
print("4. Triangle")
Shape=input("Enter the shape you want to calculate the area:")
if Shape=="Rectangle":
Rectangle()
Elif Shape=="Square":
Square()
elifShape=="Circle":
Circle()
elif Shape=="Triangle": Triangle()
else:
print("Select a Valid Shape")
Output:

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

The Area of a Rectangle is:200.00


>>>
1. Rectangle
2. Square
3. Circle
4. Triangle
Enter the shape you want to calculate the area:Square
Enter the side length of a Square : 10

The Area of a Square is: 100


>>>

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

The Area of a Circle is: 314.00


>>>
1. Rectangle
2. Square
3. Circle
4. Triangle

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

Loop until num >= 20

Stop
Program:

# Function to check if a number is prime


def is_prime(num):
if num < 2:
return False
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
return False
return True
# Print prime numbers less than 20
for num in range(2, 20):
if is_prime(num):
print(num)

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

#Calling the function fact


f=fact(n) A

Print n, f

Stop

#Function Definition
def fact(m):

True False
if
m<=1
:

return 1 return m*fact(m – 1)


Program:

#[Link] Program to find the Factorial of a number using Recursion


#Fact_Recur.py def fact(m):
if m<=1:
return 1
else:
return m*fact(m-1)

# Main Program
n=int(input("Enter the value of n: "))
f=fact(n)
print("The factorial of",n,"is",f)

Output:

Enter the value of n: 5


The factorial of 5 is 120

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:

Enter the total number of elements in the array: 5


Enter the 1 element: 90
Enter the 2 element: 45
Enter the 3 element: 67
Enter the 4 element: 88
Enter the 5 element: 11
Total Number of Even Numbers in the array = 2
Total Number of Odd Numbers in the array = 3

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:

To write a Python class to reverse a string word by word.

Algorithm:

STEP 1: Start the program

STEP 2: Prompt the user to input a string.

STEP 3: Split the input string str_to_rev into a list of words words_list using the space
character as the delimiter.

STEP 4: Reverse the order of the words in the list words_list.

STEP 5: initialize reversed_words as an empty list

STEP 6: for each word in words_list:

i) reverse the characters in the word

ii) append the reversed word to reversed_words

STEP 7: join reversed_words into a single string with spaces -> reversed_string

STEP 8: print "Reversed string:" followed by reversed_string

STEP 9: stop the program


Flow chart
start

Prompt user to enter a


string (str_to_rev)

Split str_to_rev into of


words (words_list)

Reverse the order of words


in words_list

Initialize an empty list for


reversed
words(reversed_words)

for i in range(len(words)):

Join reversed_words into a


single string
(reversed_string)

Print "Reversed string:"


followed by reversed_string

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:

#program to find the occurences count in list and tuple

def count_occurrences(tuple_data,list_data):

occurrences={}

set1=set(tuple_data)

for item in set1:

count=tuple_data.count(item)

occurrences[item]=count

set2=set(list_data)

for item in set2:

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:

{'c': 1, 'd': 1, 'b': 3, 'a': 4}

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:

STEP 1: Start the process.


STEP 2: Define a class Person with the following attributes and methods:
i) Attributes:
 name: To store the person's name.
 address: To store the person's address.
 phone: To store the person's phone number.
ii) Methods:
 init (self): Initialize name, address, and phone by taking inputs from the
user.
 display_person(self): Display the values of name, address, and phone.
STEP 3: Define a class DepositAccount that inherits from Person, with the following attributes
and methods:
i) Attributes:
 accno: To store the account number.
 amount: To store the deposit amount.
 interest: To store the calculated interest (initialized to 0).
ii) Methods:
 init (self): Initialize accno, amount, and call the init method of the
Person class.
 display_account(self): Display the account details, including the inherited
person details, deposit amount, and interest amount.
 calculate_simple_interest(self, n, r): Calculate the simple interest using the
formula: interest = (amount * n * r) / 100.
STEP 4: Create an object obj_acc of the class DepositAccount.
STEP 5: Prompt the user to enter
i) n: The number of years.
ii) r: The rate of interest (in percentage).
STEP 6: Call the method calculate_simple_interest(n, r) on obj_acc to compute the interest based
on the inputs.
STEP 7: Call the method display_account() on obj_acc to display the account details, including
the calculated interest.
STEP 8: End the process.

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])

def calculate_simple_interest(self, n, r):


[Link] = ([Link] * n * r) / 100

# Creating an instance of DepositAccount


obj_acc = DepositAccount()

# Calculating simple interest


print(format("Simple Interest Calculation", '^40'))
n = int(input("Enter the number of years: "))
r = int(input("Enter the rate of interest in %: "))
obj_acc.calculate_simple_interest(n, r)
# Displaying account details and interest
print(format("Display Receipt of Interest", '^40'))
obj_acc.display_account()

Output:

Enter name: John Doe


Enter address: 123 Elm Street
Enter phone number: 9876543210
Enter Account Number: 456789123
Enter Amount to Deposit: 10000
Simple Interest Calculation
Enter the number of years: 5
Enter the rate of interest in %: 4
Display Receipt of Interest
Account Number: 456789123
Name: John Doe
Address: 123 Elm Street
Phone: 9876543210
Deposit Amount: 10000
Interest Amount: 2000.0

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:

# Open the first file in read mode


F1 = open('[Link]', 'r')

# Open the second file in write mode


F2 = open('[Link]', 'w')

# Read the content of the file line by line


File1_Cont = [Link]()

# Write only odd lines to the second file


for i in range(0, len(File1_Cont)):
if i % 2 != 0: # Odd lines (index starts from 0, so i%2 != 0 for odd lines)
[Link](File1_Cont[i])

# Close the first file


[Link]()

# Close the second file after writing


[Link]()

# Open the second file in read mode to verify the content


F2 = open('[Link]', 'r')

# Read the content of the second file


File2_Cont = [Link]()

# Print the content of the second file


print(File2_Cont)

# Close the second file


[Link]()

Output:

Honesty is the Best Policy


Self Help is the Best Help

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

Import the turtle module

Set the window size using


the setup() method

Create a graphics window


using the Screen() method

Change the background


color using the bgcolor()
method

Assign a title for the


window

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:

To write a Python program to implement Towers of Hanoi using Recursion.

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:

#13. Python Program for Towers of Hanoi using Recursion


def Tower_Of_Hanoi(n, source, destination, auxiliary):
if n == 1:
print("Move Disk 1 from Source", source, "to Destination", destination)
return
Tower_Of_Hanoi(n-1, source, auxiliary, destination)
print("Move Disk", n, "from Source", source, "to Destination", destination)
Tower_Of_Hanoi(n-1, auxiliary, destination, source)

# 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:

Enter the number of Disks: 3


Move Disk 1 from Source A to Destination B Move Disk 2 from Source A to Destination C
Move Disk 1 from Source B to Destination C
Move Disk 3 from Source A to Destination B Move Disk 1 from Source C to Destination A
Move Disk 2 from Source C to Destination B
Move Disk 1 from Source A to Destination B >>>

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

# Function to add Key:Value pair


def add(self, Key, Value):
self[Key] = Value

# Main Function
Dict_Obj = My_Dict()
ans = 'Y'

while [Link]() == 'Y':


print(" MENU ")
print("************************************")
print(" 1. Create a Dictionary ")
print(" 2. Print the Dictionary ")
print(" 3. Exit ")
print("************************************")
ch = int(input("Enter Your Choice: "))

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")

ans = input("Do You Want to Continue (Y/N)? ")


Output:

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:

To write a Python program to implement the Hangman Game.

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

Add the word into


the list

Next

name

Read guess

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

Read turns

The user will be given the number of turns to


guess the complete word.

Stop
Program:

import random

# Creating a list of words from user input


words = []
n = int(input("Enter number of words: "))
for i in range(1, n + 1):
w = input("Enter word %d: " % i)
[Link](w)

print("\nWords in the List:")


print(words)

# Here the user is asked to enter their name


name = input("\nWhat is your name? ")
print("Good Luck, " + name + "!")

# Function will choose one random word from this list of words
word = [Link](words)

# Read the number of turns for the user


turns = int(input("Enter the number of turns: "))

print("Guess the characters!")


guesses = ''

while turns > 0:


# Counts the number of times a user fails
failed = 0

# All characters from the input word taking one at a time


for char in word:
if char
Output:

Enter number of words: 12


Enter the 1 word : rainbow
Enter the 2 word : computer
Enter the 3 word : science
Enter the 4 word : programming
Enter the 5 word : python
Enter the 6 word : mathematics
Enter the 7 word : player
Enter the 8 word : condition
Enter the 9 word : revenue
Enter the 10 word : water
Enter the 11 word : board
Enter the 12 word : tamil

Words in the List:


['rainbow', 'computer', 'science', 'programming', 'python', 'mathematics', 'player', 'condition',
'revenue', 'water', 'board', 'tamil']

What is your name? Akash


Good Luck ! Akash
Enter the number of turns : 12

Guess the Characters


_
_
_
_
_
Guess a Character: w
w
_
_
_
_

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.

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

You might also like