THIRUTHANGAL NADAR COLLEGE
(Belongs to the Chennaivazh Thiruthangal Hindu Nadar Uravinmurai Dharma Fund)
A Self--Financing Co-Educational
Educational College of Arts & Science Affiliated to the University of Madras
Re-accredited at ‘B++’ Grade by NAAC & An ISO 9001:2015:2015 Certified Institution
2(f) Status Under UGC Act
Selavayal, Chennai, Tamil Nadu, India
Department: Computer Science with Artificial Intelligence
Subject Name: Python Programming Practical
Subject Code: 126C11
Class: I B.Sc. (CS with AI)
Staff: Mrs. A. Yogameena
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
Python-based
based solutions to real world
problems
CO4: To use Python data structures - lists, tuples, dictionaries.
CO5: To do input/output with files in Python.
LAB V System &Configurations:
There are 50 systems (HP) installed in this Lab.
Configurations:
Processor:12th gen intel ® core™ i5-12500
i5
RAM:8 GB
SSD: 512 GB NVME
Mouse: Optical Mouse
Operating system: Windows 11 pro
Software: Thonny
TABLE OF CONTENTS
PAGE STAFF
SNO DATE CONTENTS NO SIGN
S1. DISPLAY A NAME
S2. SUM OF TWO NUMBERS
S3. BASIC ARITHMETIC OPERATIONS
1. TEMPERATURE CONVERSION
2. PATTERN USING NESTED LOOP
3. STUDENT GRADE CALCULATION
4. AREA OF A SHAPE
5. PRIME NUMBERS
6. FACTORIAL USING RECURSIVE
FUNCTION
7. EVEN AND ODD NUMBERS
8. REVERSE A STRING
9. OCCURRENCES OF ALL
ITEMS OF THE LIST
10. SAVINGS ACCOUNT
11. COPY ODD LINES TO A FILE
CONTENT
12. TURTLE GRAPHICS
13. TOWERS OF HANOI
14. MENUS USING DICTIONARY
15. HANGMAN GAME
Department of Computer Science with Artificial Intelligence
EX NO: S1
DISPLAY A NAME
DATE:
Aim:
To write a Python program that takes the user's name as input and prints it.
Algorithm:
Step1 : Start the program.
Step2: Use the input() function to prompt the user to enter their name.
Display the message: "enter your name:"
Store the input in a variable called name.
Step3: Use the print() function to display the value stored in name.
Step 4: End the program.
Flowchart:
Program :
name=input(“Enter your name:”)
print(name)
Output:
Enter your name : SUDHAKAR
SUDHAKAR
Result:
Thus the program has been executed successfully .
Department of Computer Science with Artificial Intelligence
EX NO: S2
SUM OF TWO NUMBERS
DATE:
Aim:
To take two numbers as input from the user, convert them to integers, and display their sum.
Algorithm:
Step1: Start
Step2: Prompt the user to enter the first number.
Step3: Convert the input to an integer and store it in variable str1.
Step 4:Prompt the user to enter the second number.
Step5:Convert the input to an integer and store it in variable str2.
Step 6:Add str1 and str2.
Step7:Display the result (sum).
Step 8: Stop
Department of Computer Science with Artificial Intelligence
Flowchart:
Program :
str1 = int(input("enter your 1st number:"))
str2 = int(input("enter your 2nd number:"))
print(str1 + str2)
Output:
enter your 1st number: 25
enter your 2nd number: 75
100
Result:
Thus the program has been executed successfully .
EX NO: S3
BASIC ARITHMETIC OPERATIONS
DATE:
Aim:
To create a Python program that takes two integer inputs from the user and performs basic
arithmetic operations: addition, subtraction, multiplication, and division.
Algorithm:
Step1: Start
Step2: Prompt the user to enter the first number and store it in the variable num.
Step3: Prompt the user to enter the second number and store it in the variable num1.
Step 4: Calculate the sum of num and num1, and store the result in variable a.
Step5: Calculate the difference of num and num1, and store the result in variable b
Step 6: Calculate the product of num and num1, and store the result in variable c.
Step7: Calculate the division of num by num1, and store the result in variable d.
Step 8: Display the values of a, b, c, and d.
Step 9: Stop
Department of Computer Science with Artificial Intelligence
Flowchart:
Program :
num = int(input("enter your 1st number:"))
num1 = int(input("enter your 2nd number:"))
a = (num + num1)
b = (num - num1)
c = (num * num1)
d = (num / num1)
print(a, b, c, d)
Output:
Enter your 1 st number :4
Enter your 2 nd number :2
62820
Result:
Thus the program has been executed successfully .
Department of Computer Science with Artificial Intelligence
EX NO: 1
TEMPERATURE CONVERSION
DATE:
Aim:
To develop a Python program tha
that converts a given temperature from Fahrenheit to Celsius
or from Celsius to Fahrenheit based on the user's choice.
Algorithm:
Step 1 : Start
Step 2: Get the choice (C / F) and the temperature value from user
Step 3: If choice is F then Calculate F = (C* 9 / 5) + 32
Step 4 : If choice is C then calculate C= (F-
(F 32)*5/9
Step 5 : Print the result F / C
Step 6 : Stop
Flowchart:
Result:
Thus the program has been executed successfully.
EX NO: 2
PATTERN USING NESTED LOOP
DATE:
Aim :
To write a python program to print a pattern with the given character.
Algorithm :
Step 1 : Start
Step 2: Get the no. of rows ‘n’ from user
Step 3: Print the character * to get the desired pattern starting from 1 up to ‘n’ times
in each line
Step 4 : Now Print the character * to starting from ‘n-1’
‘n 1’ and up to 1 time
in each line
Step 5 : Stop
Flowchart:
Result :
The given program has been executed successfully.
EX NO: 3
STUDENT GRADE CALCULATION
DATE:
Aim :
To write a python program to calculate total marks, percentage and grade
of student.
Algorithm :
Step 1 : Start
Step 2: Get the marks obtained in 5 different subjects from the user
Step 3: Calculate total = m1 + m2+m3+m4+m5
Step 4 : Calculate avg = total / 5.
Step 5 : Check if all marks are greater than 30:
If any mark is less than or equal to 30, set grade = "Fail" and stop
further calculations.
Step 6 : Determine the grade based on the average:
If avg >= 80 then grade = 'A'
Else if avg >= 70 and avg < 80 then grade = 'B'
Else if avg >= 60 and avg < 70 then grade = 'C'
Else if avg >= 40 and avg < 60 then grade = 'D'
Else if avg < 40 then grade = 'E'
Step 7: Stop
Department of Computer Science with Artificial Intelligence
Flowchart:
Program:
sub1 = float(input("Enter marks of the first subject: "))
sub2 = float(input("Enter marks of the second subject: "))
sub3 = float(input("Enter marks of the third subject: "))
sub4 = float(input("Enter marks of the fourth subject: "))
sub5 = float(input("Enter marks of the fifth subject: "))
tot = sub1 + sub2 + sub3 + sub4 + sub5
avg = tot / 5
print("Total Marks =", tot)
print("Marks Percentage =", avg)
if avg >= 80:
print("Grade: A")
elif avg >= 70:
print("Grade: B")
elif avg >= 60:
print("Grade: C")
elif avg >= 40:
print("Grade: D")
else:
print("Grade: E")
Result :
The given program has been executed successfully.
EX NO: 4
AREA OF A SHAPE
DATE:
Aim:
To write a python program To Find The Area Of Rectangle, Square, Circle And triangle by
accepting suitable input parameters from user
Algorithm :
Step 1 : Start
Step 2: Get the choice(1 – square 2-rectangle 3-triangle 4-circle) from the user
Step 3 : Determine the area of shape based on user choice:
If choice = 1 then get the square side value
Calculate area = side * side
If choice = 2 then get the length l and breadth b value of rectangle
Calculate area of = l * b
If choice = 3 then get the base b and height h value of triangle
Calculate area = 1/2 * b * h
If choice = 4 then get the radius r value of circle
Calculate area = 3.14 * r * r
Else print invalid choice
Step 4: Print area
Step 5: Stop
Department of Computer Science with Artificial Intelligence
Flowchart:
Program
i="Find area\nchoose your ptions\n1.square\n2.rectangle\n3.triangle\n4.circle"
print(i)
choice=int(input("Enter your option:"))
if choice==1:
z=int(input("Enter your value:"))
print("Square area is :",z**2)
elif choice==2:
a=int(input("Enter your Width value "))
b=int(input("Enter your length value :"))
print("Rectangle area is :",a*b)
elif choice==3:
c=int(input("Enter your base height value:"))
d=int(input("Enter your base value :"))
print("Triangle area is :",c*d/2)
elif choice==4:
e=int(input("Enter your radius value:"))
print("Circle area is:",int((e*e)*22/7))
else:
print("Your number is wrong")
Department of Computer Science with Artificial Intelligence
Result :
The given program has been executed successfully.
EX NO: 5
PRIME NUMBERS
DATE:
Aim:
To write a python program to print prime numbers less than 20.
Flowchart:
Program
starting_value = 1
n = int(input("Enter your number: "))
print("Prime numbers between", starting_value, "and", n, "are:")
for num in range(starting_value, n + 1):
if num > 1:
for i in range(2, num):
if (num % i) == 0:
break
else:
print(num)
Result
Thus the program has been executed successfully .
EX NO: 6
FACTORIAL USING RECURSIVE FUNCTION
DATE:
Aim:
To write a python program to find the factorial using recursive function.
Algorithm :
Step 1 : Start
Step 2:Input the number to find factorial
Step 3 :Define a function to calculate factorial recursively
Step 4 :Create a base case: if n is 0 or 1 return 1
Step 5 :Else return n multiplied by the factorial of (n-1)
Step 6 :print factorial
Step 7 :Stop
Department of Computer Science with Artificial Intelligence
Flowchart:
def recur_factorial(n):
if n == 1:
return n
else:
return n * recur_factorial(n - 1)
num = int(input("Enter a number: "))
if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
print("The factorial of", num, "is", recur_factorial(num))
Output:
Enter a number: 5
The factorial of 5 is 120
Result:
Thus the program has been executed successfully .
Department of Computer Science with Artificial Intelligence
EX NO: 7
COUNTING THE NUMBER OF EVEN AND
ODD NUMBERS FROM ARRAY OF N
DATE:
NUMBERS
Aim :
To write a python program to count the number of even and odd
numbers from array of n numbers
Algorithm :
Step 1 : Start
Step 2 :Initialy 2 counters are for odd count and another for even count
Step 3 :Input the arrey of n elements
Step 4 :Loop through each elements in the arrey using a’ for’ loop
Step 5 :For each no in the arrey check if it is odd/even using % operator
Step 6 :if the no is odd/even increment the corresponding counter
Step 7 :After the loop finishes, print the counter values for odd count and
Even count
Step 8 :Stop
Department of Computer Science with Artificial Intelligence
Flowchart:
Program:
def evenodd(arr,arr_size):
even_count =0
odd_count=0
for i in range(arr_size):
if(arr[i] &1==1):
odd_count+=1
else:
even_count+=1
print("Number of even element=", even_count)
print("Number of odd element =", odd_count)
a=[2,3,4,5,6]
n=len(a)
evenodd(a,n)
Output:
Number of even element =3
Number of odd element=2
Result:
Thus the program has been executed successfully .
Department of Computer Science with Artificial Intelligence
EX NO: 8
REVERSING A STRING WORD BY WORD.
DATE:
Aim :
To write a python program to reverse a string word by word
Algorithm :
Step 1 : Start
Step 2 :input a string with 2 or more words
Step 3 :split the string into words of list using split() method
Step 4 :reverse the list of words using the reversed function
Step 5 :join the reversed list into a string using the join() method
Step 6 :print the reversed string
Step 7 :stop
Department of Computer Science with Artificial Intelligence
Flowchart:
Program:
Class py_reverse:
defrevr (self, strs):
Sp=strs.split()
Sp.reverse()
res=” “.join(sp)
return res
Str1=input(“Enter a string with two or more words: “)
Print(“Reverse of string word by word: \n”,py_reverse().revr(str1 ));
Output:
Result:
Thus the program has been executed successfully .
EX NO: 9
COUNT THE OCCURRENCES OF ALL ITEMS
OF THE LIST IN THE TUPLE
DATE:
Aim :
To write a python program to count the occurrences of all items of the list in
the tuple
Algorithm :
Step 1 : Start
Step 2 :create a list and tuple
Step 3 :x= List of tuple
Step 4 :Initialize c=0
Step 5 :For each item in x iterate in loop
Step 6 :Find the intersection of element using count() method and print c
Step 7 :Stop
Department of Computer Science with Artificial Intelligence
Flowchart:
Program:
# Input
my_tuple = ('a', 'a', 'c', 'b', 'd')
my_list = ['a', 'b']
# Initialize counter
count = 0
# Count occurrences of each list item in the tuple
for item in my_list:
count += my_tuple.count(item)
# Output the result
print("Output:", count)
Output: 3
Result:
Thus the program has been executed successfully .
Department of Computer Science with Artificial Intelligence
EX NO: 10
SAVINGS ACCOUNT
DATE:
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
Step 2 : Define a base class BankAccount:
Step 3 : Initialize balance.
Step 4 : Define methods: deposit(), withdraw(), get_balance().
Step 5 : Define subclass SavingsAccount inheriting BankAccount:
Step 6 : Initialize with interest rate.
Step 7 : Define method apply_interest() that calculates interest and adds it to balance.
Step 8 : Create an object of SavingsAccount.
Step 9 : Perform deposit/withdraw operations.
Step 10 : Apply interest.
Step 11 : Display final balance.
Step 12 : Stop
Department of Computer Science with Artificial Intelligence
Flowchart:
Program:
class BankAccount:
def init (self, initial_balance=0):
self.balance = initial_balance
def deposit(self, amount):
if amount > 0:
self.balance += amount
else:
print("Deposit amount must be positive.")
def withdraw(self, amount):
if 0 < amount <= self.balance:
self.balance -= amount
else:
print("Insufficient balance or invalid withdrawal
amount.")
def get_balance(self):
return self.balance
Department of Computer Science with Artificial Intelligence
class SavingsAccount(BankAccount):
def init (self, initial_balance=0, interest_rate=0.03):
super(). init (initial_balance)
self.interest_rate = interest_rate
def apply_interest(self):
interest = self.balance * self.interest_rate
self.balance += interest
print(f"Interest of {interest:.2f} applied.")
# Example usage
if name == " main ":
account = SavingsAccount(1000, 0.05) # ₹1000 with 5%
interest
print("Initial Balance:", account.get_balance())
account.deposit(500) # Deposit ₹500
print("After Deposit:", account.get_balance())
account.withdraw(200) # Withdraw ₹200
print("After Withdrawal:", account.get_balance())
Department of Computer Science with Artificial Intelligence
account.apply_interest() # Apply interest
print("Final Balance:", account.get_balance())
Output:
Initial Balance: 1000
After Deposit: 1500
After Withdrawal: 1300
Interest of 65.00 applied.
Final Balance: 1365.0
Result:
Thus the program has been executed successfully .
Department of Computer Science with Artificial Intelligence
EX NO: 11
COPY ODD LINES TO A FILE CONTENT
DATE:
Aim:
To write a Python program to Read a file content and copy only the contents
at odd lines into a new file.
Algorithm:
Step 1 : Start
Step 2 : Open the source file in read mode
Step 3: Open the destination file in write mode
Step 4 : Initialize a line counter starting from 1
Step 5 : For each line in the source file:
If the line number is odd (i.e., line_number % 2 != 0):
o Write the line to the destination file
Increment the line counter
Step 6 : Close both the files
Step 7 : End
Department of Computer Science with Artificial Intelligence
Flowchart:
Program :
txt1, txt2=open('python.txt', 'r',), open('python1.txt','w')
count = txt1.readlines()
for i in range(len(count)):
if(i % 2 == 0):
txt2.write(count[i])
txt2=open('python1.txt','r')
cont1=txt2.read()
print(cont1)
1. Introduction
3. Control Structures
5. Functions
7. Modular Design
9. Dictionaries and Sets
11. Recursion
Result:
Thus the program has been executed successfully .
EX NO: 12
TURTLE GRAPHICS
DATE:
Aim:
To write a Python program to create a Turtle graphics window with specific size
Algorithm:
Step 1 : Start
Step 2 : Import the turtle module for using turtle graphics.
Step 3: Initialize the drawing screen using turtle’s default screen setup.
Step 4 : Set the screen size of the turtle canvas using
turtle.screensize(canvwidth=400, canvheight=400):
canvwidth sets the width of the scrollable canvas.
canvheight sets the height of the scrollable canvas.
Step 5 : Stop
Department of Computer Science with Artificial Intelligence
Flowchart:
Program :
import turtle
turtle. screensize (canvwidth=400, canvheight=400)
Result:
Thus the program has been executed successfully .
EX NO: 13
TOWERS OF HANOI
DATE:
Aim:
To write a Python program for Towers of Hanoi using recursion
Algorithm:
Step 1 : Start
Step 2 : Accept number of disks n from the user
Step 3 : Call the recursive function Tower(disks, A, B, C):
Step 4 : If disks == 1:
→ Print instruction to move the disk from rod A to rod B
→ Return
Step 5 :Else:
Call Tower(disks-1, A, C, B) → move top n-1 disks to auxiliary rod
Print instruction to move the nth disk from rod A to rod B
Call Tower(disks-1, C, B, A) → move n-1 disks to destination rod
Step 6 :Repeat until all disks are moved
Step 7 : Stop
Department of Computer Science with Artificial Intelligence
Flowchart:
Program :
def Tower(disks,A,B,C):
if disks==1:
print ("Move disk 1 from source",A,"to destination",B)
return
Tower(disks-1,A,C,B)
1,A,C,B)
print ("Move diskS",disks,"from source",A,"to destination",B)
Tower(disks-1,C,B,A)
1,C,B,A)
disks =int(input('Enter number of disks:'))
Tower(disks,'A','B','C')
Enter 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
ource A to destination B
Result:
Thus the program has been executed successfully .
EX NO: 14
MENUS USING DICTIONARY
DATE:
Aim:
To write a Python program to create a menu driven Python program with a
dictionary for words and their meanings
Algorithm:
Step 1 : Start
Step 2 : Create an empty dictionary
Step 3 : Repeat until user chooses to exit:
1. Display menu:
1. Add word
2. Search word
3. Update meaning
4. Delete word
5. Display all
6. Exit
Step 4 : Accept user choice
Step 5 : If choice is::
1: Ask for word and meaning, add to dictionary
2: Ask for word, search and display meaning if found
3: Ask for word, if exists, update meaning
4: Ask for word, if exists, delete from dictionary
5: Display all dictionary items
6: Exit loop
Invalid: Show error message
Step 6 : Stop
Department of Computer Science with Artificial Intelligence
Flowchart:
Program :
def dictionary_program():
word_dict = {}
while True:
print("\n--- Dictionary Menu ---")
print("1. Add Word")
print("2. Search Word")
print("3. Update Word")
print("4. Delete Word")
print("5. Display All Words")
print("6. Exit")
choice = input("Enter your choice (1-6): ")
if choice == '1':
word = input("Enter word: ")
meaning = input("Enter meaning: ")
word_dict[word] = meaning
print("Word added successfully.")
elif choice == '2':
word = input("Enter word to search: ")
if word in word_dict:
print(f"{word} means: {word_dict[word]}")
else:
print("Word not found.")
elif choice == '3':
word = input("Enter word to update: ")
if word in word_dict:
meaning = input("Enter new meaning: ")
word_dict[word] = meaning
print("Meaning updated.")
else:
print("Word not found.")
elif choice == '4':
word = input("Enter word to delete: ")
if word in word_dict:
del word_dict[word]
print("Word deleted.")
else:
Department of Computer Science with Artificial Intelligence
print("Word not found.")
elif choice == '5':
if word_dict:
for word, meaning in word_dict.items():
print(f"{word} : {meaning}")
else:
print("Dictionary is empty.")
elif choice == '6':
print("Exiting program.")
break
else:
print("Invalid choice. Please try again.")
# Run the program
dictionary_program()
--- Dictionary Menu ---
1. Add Word
2. Search Word
3. Update Word
4. Delete Word
5. Display All Words
6. Exit
Enter your choice (1-6): 1
Enter word: Python
Enter meaning: A high-level programming language.
Word added successfully.
--- Dictionary Menu ---
1. Add Word
2. Search Word
3. Update Word
4. Delete Word
5. Display All Words
6. Exit
Enter your choice (1-6): 2
Enter word to search: Python
Python means: A high-level programming language.
--- Dictionary Menu ---
1. Add Word
2. Search Word
3. Update Word
4. Delete Word
5. Display All Words
6. Exit
Enter your choice (1-6): 5
Python : A high-level programming language.
--- Dictionary Menu ---
1. Add Word
2. Search Word
Department of Computer Science with Artificial Intelligence
3. Update Word
4. Delete Word
5. Display All Words
6. Exit
Enter your choice (1-6): 6
Exiting program.
Result:
Thus the program has been executed successfully .
Department of Computer Science with Artificial Intelligence
EX NO: 15
HANGMAN GAME
DATE:
Aim:
To write a Python program to implement the Hangman Game.
Algorithm:
Step 1 : Start
Step 2 : Define a list of words, and choose one randomly as the secret word.
Step 3 : Initialize:
attempts = 6
guessed_letters = []
display_word = underscores for each letter in the secret word.
Step 4 : While attempts > 0 and word not guessed:
Display current progress (display_word)
Accept a letter guess
If letter is already guessed: prompt again
If letter in word: update display_word
Else: decrement attempts
Step 5 : If word is completely guessed → display "You Win!"
Step 6 : If attempts = 0 → display "You Lose!" and show correct word.
Step 7 : Stop
Department of Computer Science with Artificial Intelligence
Flowchart:
Program :
import random
def hangman():
words = ["python", "hangman", "programming", "education", "challenge"]
word = random.choice(words)
guessed_letters = []
attempts = 6
display_word = ["_" for _ in word]
print("Welcome to Hangman!")
while attempts > 0 and "_" in display_word:
print("\nWord:", " ".join(display_word))
print("Attempts left:", attempts)
guess = input("Guess a letter: ").lower()
if not guess.isalpha() or len(guess) != 1:
print("Please enter a single alphabetic character.")
continue
if guess in guessed_letters:
print("You already guessed that letter.")
continue
guessed_letters.append(guess)
if guess in word:
for i in range(len(word)):
if word[i] == guess:
display_word[i] = guess
print("Correct!")
else:
attempts -= 1
print("Wrong guess!")
if "_" not in display_word:
print("\nCongratulations! You guessed the word:", word)
else:
print("\nGame Over! The word was:", word)
# Run the game
hangman()
Department of Computer Science with Artificial Intelligence
Welcome to Hangman!
Word: _ _ _ _ _ _ _
Attempts left: 6
Guess a letter: p
Correct!
Word: p _ _ _ _ _ _
Attempts left: 6
Guess a letter: z
Wrong guess!
...
Congratulations! You guessed the word: python
Result:
Thus the program has been executed successfully .