Lab Record
Lab Record
SERKADU,
VELLORE-632115
PG DEPARMENT OF
COMPUTER SCIENCE LAB MANUAL
PREPARED BY
DEPARMENT OF COMPUTER SCIENCE
1ST SEMESTER PRATICAL
20 -20
NAME : _________________________
REG.NO : _________________________
SUB.CODE : _________________________
THIRUVALLUVAR UNIVERSITY
SERKKADU
VELLORE – 632 115
I SEMESTER – PRACTICAL ~I
__________________________________
Submitted for the University Practical Examination held on
......................... at Thiruvalluvar University, Serkkadu, Vellore –
632 115.
13.09.2023 Functions
6
20.09.2023 Recursion
7
27.09.2023 Arrays
8
04.10.2023 Strings
9
06.10.2023 Modules
10
11.10.2023 Lists
11
18.10.2023 Tuples
12
25.10.2023 Dictionaries
13
Aim:
To create a program using python in variable, constant and I/O statements.
Procedure:
• Start the program using python IDLE prompt window.
• To create a program above mentioning aim.
• The program using a variable as radius, area _circle, volume _sphere as the part of
variable declaration.
• Assigning a constant value of PI=3.14
• •We find the value of area of circle and volume of sphere.
• Save the program using Ctrl + S.
• Locate the file space where to save the program and the file name of extension using
.py .
• Execute the program and run the program using f5.
• Exit the program (or) close the window.
Source Code:
PI = 22/7
radius = float (input ("Enter the radius: "))
area_circle = PI * radius ** 2
volume_sphere = (4 / 3) * PI * radius ** 3
print ("-------- Circle and Sphere Calculations --------")
print (f"Radius: {radius}")
print (f"Area of the circle: {area_circle:.2f}")
print (f"Volume of the sphere: {volume_sphere:.2f}")
Output:
Enter the radius: 6
-------- Circle and Sphere Calculations --------
Radius: 6.0
Area of the circle: 113.14
Volume of the sphere: 905.14
Result:
Thus, the program has been executed successfully, and the output has been verified.
Ex. No: 02
Date: 02.08.2023 Operators in Python
Aim:
To create a program using operators in python.
Procedure:
• Start the program using python IDLE _prompt window.
• To create a program entitled above mentioning aim.
• The program using a operators like Arithmetic operator, Comparison operators,
Logical operator, Assignment operator, Membership Operator.
• Declare a variable using
i. Arithmetic operator & Comparison operator (num1and num2 to be value assign
num1=10, num2=5).
ii. Logical operator (p and q to be assign p=true, q=false).
iii. Assignment operator directly to be assigned the variable and their value should be
constant (num3 = 10, num3 += 5, num3 -= 3, num3 *= 2, num3 /= 4).
iv. Membership operator (in operator) such as the variable declare a part of tuple.
• Save the program using Ctrl +S.
• Locate the file space the program and the file name of extension using .py .
• Execute the program and run the program using f5.
• Exit the program (or) close the window.
Source code:
# Arithmetic operators
num1 = 3
num2 = 6
addition = num1 + num2
subtraction = num1 - num2
multiplication = num1 * num2
division = num1 / num2
modulus = num1 % num2
exponentiation = num1 ** num2
print ("\nArithmetic Operators:")
print (f"Addition: {num1} + {num2} = {addition}")
print (f"Subtraction: {num1} - {num2} = {subtraction}")
print (f"Multiplication: {num1} * {num2} = {multiplication}")
print (f"Division: {num1} / {num2} = {division}")
print (f"Modulus: {num1} % {num2} = {modulus}")
print (f"Exponentiation: {num1} ** {num2} = {exponentiation}")
# Comparison operators
greater_than = num1 > num2
less_than = num1 < num2
equal_to = num1 == num2
not_equal_to = num1! = num2
greater_than_equal_to = num1 >= num2
less_than_equal_to = num1 <= num2
print ("\nComparison Operators:")
print (f"Greater than: {num1} > {num2} is {greater_than}")
print (f"Less than: {num1} < {num2} is {less_than}")
print (f"Equal to: {num1} == {num2} is {equal_to}")
print (f"Not equal to: {num1}! = {num2} is {not_equal_to}")
print (f"Greater than or equal to: {num1} >= {num2} is {greater_than_equal_to}")
print (f"Less than or equal to: {num1} <= {num2} is {less_than_equal_to}")
# Logical operators
p = True
q = False
logical_and = p and q
logical_or = p or q
logical_not_p = not p
logical_not_q = not q
print ("\nLogical Operators:")
print(f"{p} and {q}: {logical_and}")
print(f"{p} or {q}: {logical_or}")
print (f"not {p}: {logical_not_p}")
print (f"not {q}: {logical_not_q}")
# Assignment operators
num3 = 10
num3 += 5
num3 -= 3
num3 *= 2
num3 /= 4
print ("\nAssignment Operators:")
print (f"num3 = 10 -> num3 += 5 -> num3 = {num3}")
#Membership Operator:
fruits = ["apple", "banana", "orange"]
is_apple_present = "apple" in fruits
is_grape_present = "grape" in fruits
print ("\nMembership Operators:")
print (f"'apple' in {fruits}: {is_apple_present}")
print (f"'grape' in {fruits}: {is_grape_present}")
Output:
Addition: 3 + 6 = 9
Subtraction: 3 - 6 = -3
Multiplication: 3 * 6 = 18
Division: 3 / 6 = 0.5
Modulus: 3 % 6 = 3
Exponentiation: 3 ** 6 = 729
Comparison Operators:
Greater than: 3 > 6 is False
Less than: 3 < 6 is True
Equal to: 3 == 6 is False
Not equal to: 3! = 6 is True
Greater than or equal to: 3 >= 6 is False
Less than or equal to: 3 <= 6 is True
Logical Operators:
True and False: False
True or False: True
not True: False
not False: True
Assignment Operators:
num3 = 10 -> num3 += 5 -> num3 = 6.0
Membership Operators:
'apple' in ['apple', 'banana', 'orange']: True
'grape' in ['apple', 'banana', 'orange']: False
Result:
Thus, the program has been executed successfully, and the output has been verified.
Ex. No: 03
Date: 17.08.2023 Conditional Statements
Aim:
To create a program using conditional statements in python.
Procedure:
• Start the program using python IDLE _prompt window.
• To create a program entitled above mentioning aim.
• Declare the variables are English, Math, Computer, Physics, Chemistry such as floats
data types.
• Declare the variables are Total, Percentage such as integers data types.
• The program using a Conditional Statements are if, elif, else.
• Save the program using Ctrl +S.
• Locate the file space the program and the file name of extension using .py.
• Execute the program and run the program using f5.
• Exit the program (or) close the window.
Source code:
English=float (input ("Enter the mark in English:"))
Math=float (input ("Enter the mark in Math:"))
Biology=float (input ("Enter the mark in Biology:"))
Physics=float (input ("Enter the mark in Physics:"))
Chemistry=float (input ("Enter the mark in Chemistry:"))
Total=English+ Math+ Biology+ Physics+ Chemistry
Percentage=(Total/500) *100
print ("Total Marks= “, Total)
print (f"Percentage = {Percentage:.2f}")
if (Percentage >=90):
print ("A Grade")
elif(Percentage >=80):
print ("B Grade")
elif(Percentage >=70):
print ("C Grade")
elif(Percentage >=60):
print ("D Grade")
elif(Percentage >=50):
print ("E Grade")
elif(Percentage >=40):
print ("F Grade")
else:
print("Fail")
Output:
Enter the mark in English :88
Enter the mark in Math :67
Enter the mark in Biology :88
Enter the mark in Physics :76
Enter the mark in Chemistry :83
Total Marks= 402.0
Percentage = 80.40
B Grade
Result:
Thus, the program has been executed successfully, and the output has been verified.
Ex. No: 04
Date: 28.08.2023 Loops
1. Fibonacci Series:
Aim:
To create a program using Fibonacci series in python.
Procedure:
• Start the program using python IDLE _prompt window.
• To create a program entitled above mentioning aim.
• Get the input from the user and assign it to ‘n’ variable.
• Assign f1 and f2 value to 0 and 1 respectively.
• Initialize i value to 0. o Display f1, f2.
• Start a while loop ranging from 0 to n-2.
• Calculate f3=f1+f2. o Display f3.
• Assign f2 value to f1 and f2 value to f2 respectively.
• Increment i value.
• Save the program using Ctrl +S.
• Locate the file space the program and the file name of extension using .py .
• Execute the program and run the program using f5.
• Exit the program (or) close the window.
Source code:
Print ("Fibonacci Series")
n=int (input ("Enter no. of terms:"))
f1, f2=0,1
i=0
print(f1)
print(f2)
while(i<n-2):
f3=f1+f2
print(f3)
f1=f2
f2=f3
i=i+1
Output:
Fibonacci Series
Enter no. of terms:9
0
1
1
2
3
5
8
13
21
Result:
Thus, the program has been executed successfully, and the output has been verified.
2. First N Prime Number:
Aim:
To write a python program to generate first n prime numbers.
Procedure:
• Start the program using python IDLE _prompt window.
• To create a program entitled above mentioning aim.
• Get the Input from the user and assign it to ‘n’ variable.
• Start a ’i’ for loop ranging from 1 to n+1.
• Start a ‘j’ for loop ranging from 2 to i.
• If i % j==0, break the loop else display ‘i’ value.
• Save the program using Ctrl +S.
• Locate the file space the program and the file name of extension using .py.
• Execute the program and run the program using f5.
• Exit the program (or) close the window.
Source code:
print ("First N Prime Numbers")
n=int (input ("Enter Upper limit: "))
for i in range (2, n+1):
for j in range (2, i):
if(i%j) ==0:
break
else:
print(i)
Output:
First N Prime Numbers
Enter Upper limit: 12
2
3
5
7
11
Result:
Thus, the program has been executed successfully, and the output has been verified.
Ex. No: 05
Date: 05.09.2023 Jump Statements
Aim:
To create a program using jump statements in python.
Procedure:
• Start the program using python IDLE _prompt window.
• To create a program entitled above mentioning aim.
• We are providing in jump statement such as break continue and pass like look as
display of the execute programs.
• If the condition is true the break statement is executed at the point.
• Another condition is followed by the break conditions is executed its feather the
conditions true the continue statement is executed.
• Above condition all are execute by the pass conditions to be execute.
• Save the program using Ctrl +S.
• Locate the file space the program and the file name of extension using .py.
• Execute the program and run the program using f5.
• Exit the program (or) close the window.
Source code:
import random
def combat_game():
player_health = 100
enemies_defeated = 0
max_enemies = 1
print ("Welcome to the Combat Game!")
print ("Defeat enemies to win the game.")
while player_health > 0 and enemies_defeated < max_enemies:
print (f"Player health: {player_health}")
print (f"Enemies defeated: {enemies_defeated}")
action = input ("Do you want to 'attack' or 'rest'? ")
if action == 'attack':
enemy_health = random.randint(20, 40)
print (f"You encounter an enemy with {enemy_health} health.")
while enemy_health > 0:
attack_damage = random.randint(5, 15)
print (f"You attack the enemy and deal {attack_damage} damage.")
enemy_health -= attack_damage
if enemy_health <= 0:
print ("You defeated the enemy!")
enemies_defeated += 1
break
else:
player_damage = random.randint(8, 18)
print (f"The enemy attacks you and deals {player_damage} damage.")
player_health -= player_damage
if player_health <= 0:
print ("You were defeated. Game over.")
break
else:
continue
elif action == 'rest':
print ("You rest and recover some health.")
player_health += random.randint(20, 30)
pass
else:
print ("Invalid action. Choose 'attack' or 'rest'.")
if player_health > 0:
print ("Congratulations! You've defeated all enemies and won the game!")
else:
print ("Thanks for playing. Better luck next time!")
combat_game()
Output:
Welcome to the Combat Game!
Defeat enemies to win the game.
Player health: 100
Enemies defeated: 0
Do you want to 'attack' or 'rest'? attack
You encounter an enemy with 31 health.
You attack the enemy and deal 11 damage.
The enemy attacks you and deals 8 damage.
You attack the enemy and deal 9 damage.
The enemy attacks you and deals 8 damage.
You attack the enemy and deal 11 damage.
You defeated the enemy!
Congratulations! You've defeated all enemies and won the game!
Result:
Thus, the program has been executed successfully, and the output has been verified.
Ex. No: 06
Date: 13.09.2023 Functions
Aim:
To create a program using functions in python.
Procedure:
• Start the program using python IDLE _prompt window.
• To create a program entitled above mentioning aim.
• def- keyword used to declare a function.
• We declared a function named def guessing_game().
• We can call the guessing_game() function python.
• Return (Optional) - returns value from a function.
• Save the program using Ctrl +S.
• Locate the file space the program and the file name of extension using .py.
• Execute the program and run the program using f5.
• Exit the program (or) close the window.
Source code:
import random
def guessing_game():
secret_number = random.randint(1, 100)
attempts = 0
while True:
guess = int (input ("Guess a number between 1 and 100: "))
attempts += 1
if guess < secret_number:
print ("Too low! Try again.")
elif guess > secret_number:
print ("Too high! Try again.")
else:
print (f"Congratulations! You guessed the number {secret_number} in{attempts}
attempts.")
break
guessing_game()
Output:
Guess a number between 1 and 100: 66
Too low! Try again.
Guess a number between 1 and 100: 70
Too low! Try again.
Guess a number between 1 and 100: 80
Too low! Try again.
Guess a number between 1 and 100: 83
Congratulations! You guessed the number 83 in4 attempts.
Result:
Thus, the program has been executed successfully, and the output has been verified.
Ex. No: 07
Date: 20.09.2023 Recursion
Aim:
To create a program using recursion in python.
Procedure:
• Start the program using python IDLE _prompt window.
• To create a program entitled above mentioning aim.
• def- keyword used to declare a function.
• Define a recursive function called factorial that takes an integer n as an input.
• Set up a base case: If n is 0 or 1, return 1 since the factorial of 0 or 1 is 1.
• In the recursive case, call the factorial function with n-1 as the argument and multiply
the result by n.
• Return the result obtained from the recursive call.
• To find the factorial of a specific number, invoke the factorial function with the
desired number as an argument.
• Save the program using Ctrl +S.
• Locate the file space the program and the file name of extension using .py.
• Execute the program and run the program using f5.
• Exit the program (or) close the window.
Source code:
def recursive_factorial(n):
if n == 1:
return n
else:
return n * recursive_factorial(n-1)
num=int (input ("Enter the number:"))
if num < 0:
print ("Invalid input! Please enter a positive number.")
elif num == 0:
print ("Factorial of number 0 is 1")
else:
print ("Factorial of number", num, "=", recursive_factorial(num))
Output:
Enter the number:7
Factorial of number 7 = 5040
Result:
Thus, the program has been executed successfully, and the output has been verified.
Ex. No: 08
Date: 27.09.2023 Arrays
Aim:
To create a program using recursion in python.
Procedure:
• Start the program using python IDLE _prompt window.
• Array in Python can be created by importing an array module.
• array (data_type, value_list) is used to create an array with data type and value list
specified in its arguments.
• append () is also used to add the value mentioned in its arguments at the end of the
array.
• The extend () function is simply used to attach an item from iterable to the end of the
array.
• Elements can be removed from the array by using built-in remove ().
• pop () function can also be used to remove and return an element from the array, to
remove element from a specific position of the array.
• In order to reverse elements of an array we need to simply use reverse method.
• Save the program using Ctrl +S.
• Locate the file space the program and the file name of extension using .py.
• Execute the program and run the program using a f5.
• Exit the program (or) close the window.
Source code:
import array as arr
m1 = arr. array ('i', [1,3,5,7])
m2 = arr. array ('i', [6,4,2,0])
m2. append (-2)
print (m2)
m1. extend(m2)
print (m1)
m2. remove (6)
print (m2)
m2.pop (0)
print (m2)
m1. reverse ()
print (m1)
Output:
array ('i', [6, 4, 2, 0, -2])
array ('i', [1, 3, 5, 7, 6, 4, 2, 0, -2])
array ('i', [4, 2, 8, -2])
array ('i', [2, 0, -2])
array ('i', [-2, 8, 2, 4, 6, 7, 5, 3, 1])
Result:
Thus, the program has been executed successfully, and the output has been verified.
Ex. No: 09
Date: 04.10.2023 Strings
Aim:
To create a program using strings in python.
Procedure:
• Start the program using python IDLE _prompt window.
• Concatenating two strings.
• Accessing characters in a string using indexing.
• Slicing a string to extract a substring.
• Finding the length of a string.
• Searching for a substring within a string.
• Counting the occurrences of a character or substring.
• Replacing a substring in a string.
• Save the program using Ctrl +S.
• Locate the file space the program and the file name of extension using .py.
• Execute the program and run the program using a f5.
• Exit the program (or) close the window.
Source code:
string1 = "Hello, "
string2 = "Python!"
concatenated_string = string1 + string2
print ("Concatenated String:", concatenated_string)
first_char = concatenated_string[0]
second_char = concatenated_string[1]
print ("First Character:", first_char)
print ("Second Character:", second_char)
substring = concatenated_string[7:12]
print ("Substring:", substring)
string_length = len(concatenated_string)
print ("Length of String:", string_length)
search_substring = "Python"
if search_substring in concatenated_string:
print(f"'{search_substring}' found in the string.")
else:
print(f"'{search_substring}' not found in the string.")
char_count = concatenated_string.count("l")
print ("Count of 'l':", char_count)
replaced_string = concatenated_string.replace("Python", "World")
print ("Replaced String:", replaced_string)
Output:
Concatenated String: Hello, Python!
First Character: H
Second Character: e
Substring: Pytho
Length of String: 14
'Python' found in the string.
Count of 'l': 2
Replaced String: Hello, World!
Result:
Thus, the program has been executed successfully, and the output has been verified.
Ex. No: 10
Date: 06.10.2023 Modules
Aim:
To create a program using modules in python.
Procedure:
• Start the program using python IDLE _prompt window.
• Create a Python module named math_operations.py.
• Create a Python script that imports and uses the math_operations module. Create a file
named File_name.py.
• This script imports the math_operations module and uses its functions to perform
basic mathematical operations based on user input: o Addition o Subtraction o
Multiplication o Division
• Save the program using Ctrl +S.
• Locate the file space the program and the file name of extension using .py.
• Execute the program and run the program using a f5.
• Exit the program (or) close the window.
Source code:
# math_operations.py
def add (a, b):
return a + b
def subtract (a, b):
return a - b
def multiply (a, b):
return a * b
def divide (a, b):
if b == 0:
return "Cannot divide by zero"
return a / b
# main_program.py
import math_operations
def main ():
num1 = float (input ("Enter the first number: "))
num2 = float (input ("Enter the second number: "))
print ("Select operation:")
print ("1. Addition")
print ("2. Subtraction")
print ("3. Multiplication")
print ("4. Division")
choice = input ("Enter choice (1/2/3/4): ")
if choice == '1':
result = math_operations.add(num1, num2)
operation = "addition"
elif choice == '2':
result = math_operations.subtract(num1, num2)
operation = "subtraction"
elif choice == '3':
result = math_operations.multiply(num1, num2)
operation = "multiplication"
elif choice == '4':
result = math_operations.divide(num1, num2)
operation = "division"
else:
print ("Invalid choice")
return
print (f"Result of {operation}: {result}")
main ()
Output:
Enter the first number: 4
Enter the second number: 2
Select operation:
1. Addition
2. Subtraction
3. Multiplication
4. Division
Enter choice (1/2/3/4): 4
Result of division: 2.0
Result:
Thus, the program has been executed successfully, and the output has been verified.
Ex. No: 11
Date: 11.10.2023 Lists
Aim:
To create a program using lists in python.
Procedure:
• Start the program using python IDLE _prompt window.
• We can create lists, access elements, modify them, add and remove elements, find the
length, check for the existence of elements, and perform sorting and concatenation.
• We can modify and expand on this program to suit your specific needs.
• Save the program using Ctrl +S.
• Locate the file space the program and the file name of extension using .py.
• Execute the program and run the program using a f5.
• Exit the program (or) close the window.
Source code:
my_list = [1, 2, 3, 4, 5]
print ("First element:", my_list[0])
print ("Last element:", my_list[-1])
print ("Sliced list:", my_list[1:4])
my_list[2] = 10
print ("Modified list:", my_list)
my_list.append(6)
print ("Appended list:", my_list)
my_list.remove(4)
print ("List after removing 4:", my_list)
removed_element = my_list.pop(1)
print ("List after removing element at index 1:", my_list)
print ("Removed element:", removed_element)
list_length = len(my_list)
print ("List length:", list_length)
if 4 in my_list:
print ("4 is in the list")
else:
print ("4 is not in the list")
my_list.sort()
print ("Sorted list:", my_list)
my_list.reverse()
print ("Reversed list:", my_list)
new_list = my_list + [7, 8, 9]
print ("Concatenated list:", new_list)
Output:
First element: 1
Last element: 5
Sliced list: [2, 3, 4]
Modified list: [1, 2, 10, 4, 5]
Appended list: [1, 2, 10, 4, 5, 6]
List after removing 4: [1, 2, 10, 5, 6]
List after removing element at index 1: [1, 10, 5, 6]
Removed element: 2
List length: 4
4 is not in the list
Sorted list: [1, 5, 6, 10]
Reversed list: [10, 6, 5, 1]
Concatenated list: [10, 6, 5, 1, 7, 8, 9]
Result:
Thus, the program has been executed successfully, and the output has been verified.
Ex. No: 12
Date: 18.10.2023 Tuples
Aim:
To create a program using tuples in python.
Procedure:
• Start the program using python IDLE _prompt window.
• We can choose to add a new contact with their name, phone number, and email,
display all contacts in the list, or quit the program.
• The contacts are stored as tuples in the contacts list.
• Save the program using Ctrl +S.
• Locate the file space the program and the file name of extension using .py.
• Execute the program and run the program using a f5.
• Exit the program (or) close the window.
Source code:
contacts = []
def add_contact(name, phone, email):
contact = (name, phone, email)
contacts.append(contact)
print ("Contact added successfully!")
def display_contacts():
if not contacts:
print ("No contacts in the list.")
else:
print ("Contact List:")
for i, contact in enumerate (contacts, start=1):
name, phone, email = contact
print(f"{i}. Name: {name}, Phone: {phone}, Email: {email}")
while True:
print("\nOptions:")
print ("1. Add a new contact")
print ("2. Display all contacts")
print ("3. Quit")
choice = input ("Enter your choice (1/2/3): ")
if choice == "1":
name = input ("Enter the contact's name: ")
phone = input ("Enter the contact's phone number: ")
email = input ("Enter the contact's email: ")
add_contact(name, phone, email)
elif choice == "2":
display_contacts()
elif choice == "3":
print("Goodbye!")
break
else:
print ("Invalid choice. Please enter 1, 2, or 3.")
Output:
Options:
1. Add a new contact
2. Display all contacts
3. Quit
Enter your choice (1/2/3): 1
Enter the contact's name: Maliha
Enter the contact's phone number: 9876543210
Enter the contact's email: malihamryam12@gmail.com
Contact added successfully!
Options:
1. Add a new contact
2. Display all contacts
3. Quit
Enter your choice (1/2/3): 2
Contact List:
1. Name: Maliha, Phone: 9876543210,
Email: malihamryam12@gmail.com
Options:
1. Add a new contact
2. Display all contacts
3. Quit
Enter your choice (1/2/3): 3
Goodbye!
Result:
Thus, the program has been executed successfully, and the output has been verified.
Ex. No: 13
Date: 25.10.2023 Dictionaries
Aim:
To create a program using dictionaries in python.
Procedure:
• Start the program using python IDLE _prompt window.
• We can choose to add a new student's name, age, and grade, display all students in the
dictionary, or quit the program.
• Student data is stored as dictionary values with the student's name as the key.
• We can expand this program to include more features, such as searching for specific
students or calculating statistics based on the data.
• Save the program using Ctrl +S.
• Locate the file space the program and the file name of extension using .py.
• Execute the program and run the program using a f5.
• Exit the program (or) close the window.
Source code:
students = {}
def add_student():
name = input ("Enter the student's name: ")
age = int (input ("Enter the student's age: "))
grade = float (input ("Enter the student's grade: "))
students[name] = {'age': age, 'grade': grade}
print ("Student added successfully!")
def display_students():
if not students:
print ("No students in the list.")
else:
print ("Student List:")
for name, data in students.items():
age = data['age']
grade = data['grade']
print (f"Name: {name}, Age: {age}, Grade: {grade}")
while True:
print("\nOptions:")
print ("1. Add a new student")
print ("2. Display all students")
print ("3. Quit")
choice = input ("Enter your choice (1/2/3): ")
if choice == "1":
add_student()
elif choice == "2":
display_students()
elif choice == "3":
print("Goodbye!")
break
else:
print ("Invalid choice. Please enter 1, 2, or 3.")
Output:
Options:
1. Add a new student
2. Display all students
3. Quit
Enter your choice (1/2/3): 1
Enter the student's name: S Maliha Maryam
Enter the student's age: 17
Enter the student's grade: 1
Student added successfully!
Options:
1. Add a new student
2. Display all students
3. Quit
Enter your choice (1/2/3): 2
Student List:
Name: S Maliha Maryam, Age: 17, Grade: 1.0
Options:
1. Add a new student
2. Display all students
3. Quit
Enter your choice (1/2/3): 3
Goodbye!
Result:
Thus, the program has been executed successfully, and the output has been verified.
Ex. No: 14
Date: 30.10.2023 File Handling
1. Read:
Aim:
To create a program using file handling read in python.
Procedure:
• Start the program using python IDLE _prompt window.
• The file should exist in the same directory as the python program file else, full address
of the file should be written on place of filename.
• After we open a file, we use the read () method to read its contents.
• Save the program using Ctrl +S.
• Locate the file space the program and the file name of extension using .py.
• Execute the program and run the program using a f5.
• Exit the program (or) close the window.
Source code:
L = ["This is Delhi \n", "This is Paris \n", "This is London \n"]
with open ("myfile.txt", "w") as file1:
file1.write("Hello \n")
file1.writelines(L)
file1.close()
with open ("myfile.txt", "r+") as file1:
print (file1.read())
Output:
Hello
This is Delhi
This is Paris
This is London
Result:
Thus, the program has been executed successfully, and the output has been verified.
2. Write:
Aim:
To create a program using file handling write in python.
Procedure:
• Start the program using python IDLE _prompt window.
• The user to enter the file name where they want to write data and the data they want to
write to the file. o It then opens the specified file in write mode ("w") using the open
function.
• The write method to write the user's input to the file. o Finally, it prints a message to
confirm that the data has been written to the specified file.
• Save the program using Ctrl +S.
• Locate the file space the program and the file name of extension using .py.
• Execute the program and run the program using a f5.
• Exit the program (or) close the window.
Source code:
file_name = input ("Enter the file name: ")
data_to_write = input ("Enter the data to write to the file: ")
with open (file_name, "w") as file:
file.write(data_to_write)
print (f"Data has been written to {file_name}")
Output:
Enter the file name: Python
Enter the data to write to the file: File handling
Data has been written to Python
Result:
Thus, the program has been executed successfully, and the output has been verified.