0% found this document useful (0 votes)
14 views32 pages

Exp 1-14

The document outlines multiple Python experiments aimed at teaching various programming concepts, including generating personalized greetings, calculating areas of geometric figures, computing gross salaries, performing arithmetic operations, managing task lists with lists and tuples, and demonstrating set operations. Each experiment includes the aim, requirements, program code, and expected output. The code snippets provided are designed to run in Python 3.13.2.

Uploaded by

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

Exp 1-14

The document outlines multiple Python experiments aimed at teaching various programming concepts, including generating personalized greetings, calculating areas of geometric figures, computing gross salaries, performing arithmetic operations, managing task lists with lists and tuples, and demonstrating set operations. Each experiment includes the aim, requirements, program code, and expected output. The code snippets provided are designed to run in Python 3.13.2.

Uploaded by

Shaikh Rafee
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 32

EXPERIMENT-1

Aim:-Write a python code to generate Personalized Greeting.

Requirement:-Python 3.13.2

Program Code:-
# Getting current date and time using now().

# importing datetime module for now()

import datetime

# using now() to get current time

current_time = datetime.datetime.now()

# Printing value of now.

print("Name of student:Shaikh Rafee")

print("Roll no:47 Batch: D3 Branch:AI&DS")

print("Current date and time is:", current_time)

cstr='*'

print(cstr.ljust(70,'*'))

#(Above program code should be included in each program at the start of program code)

# Python program that asks the user to enter their name, and then greet them.

print("Welcome to the name and greet program!")

name = input("Please enter your name: ")

message=input("Please enter greeting message: ")

print(f"{message}",name)

Program Output:-
EXPERIMENT-2
Aim:-Write a python program to calculate areas of any geometric figures like circle, rectangle and
triangle.

Requirement:-Python 3.13.2

Program Code:-
# Getting current date and time using now().
# importing datetime module for now()
import datetime
# using now() to get current time
current_time = datetime.datetime.now()
# Printing value of now.
print("Name of student:Shaikh Rafee")
print("Roll no:47 Batch: D3 Branch:AI&DS")
print("Current date and time is:", current_time)
cstr='*'
print(cstr.ljust(70,'*'))
#(Above program code should be included in each program at the start of program code)
import math

print("**********Choose an Option:********* ");

print("1: Area of the Circle");

print("2: Area of the Rectangle ");

print("3: Area of the Triangle ");

print("4: Area of the Square ");

print("5: Area of the Parallelogram ");

print("Enter a choice :");

# input the desired shape

choice = int(input(""))

print(f"Enter a choice :{choice}");

# area of a circle

if choice==1:

# input circle radius

radius = float(input("Enter the radius of the Circle: "))

area = math.pi*pow(radius,2)

print(f"The area of the circle with radius {radius} is : {round(area,2)}")

#area of a rectangle

elif choice==2:
width =float(input("Enter the width of the rectangle: "))

length = float(input("Enter the length of the rectangle: "))

area = width*length

print(f"The area of the rectangle is {round(area,2)}")

# area of a triangle using Heron's formula

elif choice==3: # Triangle

base = float(input("Enter the base of the triangle: "))

height = float(input("Enter the height of the triangle: "))

area = 0.5 * base * height

print(f"The area of the triangle is: {round(area,2)} square units.")

#area of a Square

elif choice ==4:

side =float(input("Enter the side of the square: "))

area = side*side

print(f"The area of the square is {round(area,2)}")

#area of a Parallelogram

elif choice ==5:

base =float(input("Enter the base of the parallelogram: "))

height = float(input("Enter the height of the parallelogram: "))

area = base*height

print(f"The area of the parallelogram is {round(area,2)}")

else:

print("Wrong Choice! Enter a number between 1 to 5 :")

Program Output:-
EXPERIMENT-3
Aim:-Write a Python program to calculate the gross salary of an employee. The program should prompt
the user for the basic salary (BS) and then compute the dearness allowance (DA) as 70% of BS, the travel
allowance (TA) as 30% of BS, and the house rent allowance (HRA) as 10% of BS also provident fund (PF)
as 10% of BS. Finally, it should calculate the gross salary as the algebraic sum of BS, DA, TA, HRA and PF
and display the result.

Requirement:-Python 3.13.2

Program Code:-
# Getting current date and time using now().
# importing datetime module for now()
import datetime
# using now() to get current time
current_time = datetime.datetime.now()
# Printing value of now.
print("Name of student:Shaikh Rafee")
print("Roll no:47 Batch: D3 Branch:AI&DS")
print("Current date and time is:", current_time)
cstr='*'
print(cstr.ljust(70,'*'))
#(Above program code should be included in each program at the start of program code)
# Python3 program to calculate the salary

import math

# Input the employee name and basic salary


name = input("Enter the name of Employee Mr/Mrs: ")

basic = float(input("Enter basic Salary in Rs.: "))

# Calculate allowances and deductions

hra = 0.10 * basic # House Rent Allowance (HRA)

da = 0.70 * basic # Dearness Allowance (DA)

ta = 0.30 * basic # Travel Allowance (TA)

pf = 0.10 * basic # Provident Fund (PF)

# Calculate gross salary

gross = round(basic + hra + da + ta - pf, 2)

# Output the salary details

print(f"\nSalary details of Employee {name}:")

print(f"Basic Salary: Rs. {basic}")

print(f"HRA: Rs. {hra}")

print(f"DA: Rs. {da}")

print(f"TA: Rs. {ta}")

print(f"PF Deduction: Rs. {pf}")

print(f"Gross Salary: Rs. {gross}")

Program Output:-

EXPERIMENT-4
Aim:-Write a Python program to explore basic arithmetic operations. The program should prompt the
user to enter two numbers and then perform addition, subtraction, multiplication, division, and modulus
operations on those numbers. The results of each operation should be displayed to the user.

Requirement:-Python 3.13.2
Program code:-
# Getting current date and time using now().
# importing datetime module for now()
import datetime
# using now() to get current time
current_time = datetime.datetime.now()
# Printing value of now.
print("Name of student:Shaikh Rafee")
print("Roll no:47 Batch: D3 Branch:AI&DS")
print("Current date and time is:", current_time)
cstr='*'
print(cstr.ljust(70,'*'))
#(Above program code should be included in each program at the start of program code)
#Python program to explore basic arithmetic operations.
num1 = int(input(“Enter First number: “))
num2 = int(input(“Enter Second number “))
#basic arithmetic operations
add = num1 + num2
dif = num1 - num2
mul = num1 * num2
div = num1 / num2
floor_div = num1 // num2
power = num1 ** num2
modulus = num1 % num2
print("1.Addition: ")
print('Sum of ', num1, 'and', num2, 'is :', add)
print("2.Substration: ")
print('Difference of ', num1, 'and', num2, 'is :', dif)
print("3.Multiplaction: ")
print('Product of ', num1, 'and', num2, 'is :', mul)
print("4.Division: ")
print('Division of ', num1, 'and', num2, 'is :', div)
print("5.Floor Division: ")
print('Floor Division of ', num1, 'and', num2, 'is :', floor_div)
print("6.Exponent: ")
print('Exponent of ', num1, 'and', num2, 'is :', power)
print("7.Modulus: ")
print('Modulus of ', num1, 'and', num2, 'is :', modulus)

Program Output:-
EXPERIMENT-5
Aim:- Develop a Python program to manage a task list using lists and tuples, including adding, removing,
updating, and sorting tasks.

Requirement:-Python 3.13.2

Program Code:-
# Getting current date and time using now().
# importing datetime module for now()
import datetime
# using now() to get current time
current_time = datetime.datetime.now()
# Printing value of now.
print("Name of student:Shaikh Rafee")
print("Roll no:47 Batch: D3 Branch:AI&DS")
print("Current date and time is:", current_time)
cstr='*'
print(cstr.ljust(70,'*'))
#(Above program code should be included in each program at the start of program code)
#Create a Python List

# a list of three elements

ages = [19, 26, 29]


print("List of three elements:",ages)

#List Items of Different Types

# a list containing strings, numbers and another list

student = ['Jack', 32, 'Computer Science', [2, 4]]

print(student)

# an empty list

empty_list = []

print("The final list:",empty_list)

#Access List Elements

languages = ['Python', 'Swift', 'C++']

# access the first element

print('languages[0] =', languages[0])

# access the third element

print('languages[2] =', languages[2])

#Add Elements to a Python List

fruits = ['apple', 'banana', 'orange']

print('Original List:', fruits)

fruits.append('cherry')

print('Updated List:', fruits)

#Add Elements at the Specified Index

fruits = ['apple', 'banana', 'orange']

print("Original List:", fruits)

fruits.insert(2, 'cherry')

print("Updated List:", fruits)

#Change List Items (Update List)

colors = ['Red', 'Black', 'Green']

print('Original List:', colors)

# change the first item to 'Purple'

colors[2] = 'Purple'
# change the third item to 'Blue'

colors[2] = 'Blue'

print('Updated List:', colors)

#Remove an Item From a List

numbers = [2,4,7,9]

# remove 4 from the list

numbers.remove(4)

print(numbers)

#Remove One or More Elements of a List

names = ['John', 'Eva', 'Laura', 'Nick', 'Jack']

# delete the item at index 1

del names[1]

print(names)

# delete items from index 1 to index 2

del names[1: 3]

print(names)

# delete the entire list

names = ['John', 'Eva', 'Laura', 'Nick', 'Jack']

del names

#Slicing of a List in Python

my_list = ['p', 'r', 'o', 'g', 'r', 'a', 'm']

print("my_list =", my_list)

# get a list with items from index 2 to index 4 (index 5 is not included)

print("my_list[2: 5] =", my_list[2: 5])

# get a list with items from index 2 to index -3 (index -2 is not included)

print("my_list[2: -2] =", my_list[2: -2])

# get a list with items from index 0 to index 2 (index 3 is not included)

print("my_list[0: 3] =", my_list[0: 3])

#Omitting Start and End Indices in Slicing


my_list = ['p', 'r', 'o', 'g', 'r', 'a', 'm']

print("my_list =", my_list)

# get a list with items from index 5 to last

print("my_list[5: ] =", my_list[5: ])

# get a list from the first item to index -5

print("my_list[: -4] =", my_list[: -4])

# omitting both start and end index

# get a list from start to end items

print("my_list[:] =", my_list[:])

#Create a Python Tuple

numbers = (1, 2, -5)

print(numbers)

tuple_constructor = tuple(('Jack', 'Maria', 'David'))

print(tuple_constructor)

#Tuple of different data types

# tuple of string types

names = ('James', 'Jack', 'Eva')

print (names)

# tuple of float types

float_values = (1.2, 3.4, 2.1)

print(float_values)

#Tuple of mixed data types

# tuple including string and integer

mixed_tuple = (2, 'Hello', 'Python')

print(mixed_tuple)

#Access Tuple Items

#Access Items Using Index

languages = ('Python', 'Swift', 'C++')

# access the first item


print(languages[0]) # Python

# access the third item

print(languages[2]) # C++

#Tuple Cannot be Modified

cars = ['BMW', 'Tesla', 'Ford', 'Toyota']

# trying to modify a tuple

cars[0] = 'Nissan'

print(cars)

animals = ('dog', 'cat', 'rat')

print(animals)

# deleting the tuple

animals = ('dog', 'cat', 'rat')

del animals

#Concatenation of Tuples

x = (1, 2, 3, 4)

y = (5, 6, 7, 8)

z = x + y #tuple concatenation

print(z)

#Slicing of Tuple

#tuple[start : stop : step]

tu = ("W", "S", "C", "U", "B", "E")

print(tu[::]) #('W', 'S', 'C', 'U', 'B', 'E')

print(tu[0::]) #('W', 'S', 'C', 'U', 'B', 'E')

print(tu[0::1]) #('W', 'S', 'C', 'U', 'B', 'E')

print(tu[2::]) #('C', 'U', 'B', 'E')

print(tu[2:6:]) #('C', 'U', 'B', 'E')

print(tu[2:6:1]) #('C', 'U', 'B', 'E')

print(tu[3:7:2]) #('U', 'E')

print(tu[::-1]) #('E', 'B', 'U', 'C', 'S', 'W')


print(tu[-2:-6:-1]) #('B', 'U', 'C', 'S')

#Updating Tuples in Python

tu=['a', 'b', 'c']

tu[0]=='p' #will generate error

print(tu)

Program Output:-

EXPERIMENT-6
Aim:-Create a Python code to demonstrate the use of sets and perform set operations (union,
intersection, difference) to manage student enrollments in multiple courses / appearing for multiple
entrance exams like CET, JEE, NEET etc.

Requirement:- Python 3.13.2

Program Code:-
# Getting current date and time using now().

# importing datetime module for now()


import datetime

# using now() to get current time

current_time = datetime.datetime.now()

# Printing value of now.

print("Name of student:Shaikh Rafee")

print("Roll no:47 Batch: D3 Branch:AI&DS")

print("Current date and time is:", current_time)

cstr='*'

print(cstr.ljust(70,'*'))

#(Above program code should be included in each program at the start of program code)

# Program to perform different set operations as we do in mathematics

# sets are define

CET = {0, 2, 4, 6, 8};

JEE = {1, 2, 3, 4, 11};

NEET ={2,4,3,7,9,8};

#Students Enrolled for CET examination only.

print("Students Enrolled for CET examination :",CET)

#Students Enrolled for JEE examination only.

print("Students Enrolled for JEE examination :",JEE)

#Students Enrolled for NEET examination only.

print("Students Enrolled for NEET examination :",NEET)

# Total Number Of Students Registered For CET,JEE & NEET Examination.

# union

Union=CET | JEE |NEET

print("Total Number Of Students Registered For CET,JEE & NEET Examination All Together :",Union)

#Common Number Of Students Registered For CET,JEE & NEET Examination

# intersection

Intersection = CET & JEE & NEET

print("Common Number Of Students Registered For CET,JEE & NEET Examination :",Intersection)
Intersection1 = CET & JEE

print("Common Number Of Students Registered For CET & JEE Examination :",Intersection1)

Intersection2 = CET & NEET

print("Common Number Of Students Registered For CET & NEET Examination :",Intersection2)

Intersection3 = JEE & NEET

print("Common Number Of Students Registered For JEE & NEET Examination :",Intersection3)

#Number Of Students Registered For for CET Examination only

# difference

Difference = CET - JEE - NEET

print(" Number Of Students Registered For CET Examination only :",Difference)

#Number Of Students Registered For for JEE Examination only

# difference

Difference = JEE- NEET-CET

print(" Number Of Students Registered For JEE Examination only :",Difference)

#Number Of Students Registered For for NEET Examination only

# difference

Difference = NEET-CET-JEE

print(" Number Of Students Registered For NEET Examination only :",Difference)

Program Output:-
EXPERIMENT-7
Aim:-Write a Python program to create, update, and manipulate a dictionary of student
records, including their grades and attendance.

Requirement:-Python 3.13.2

Program Code:-
# Getting current date and time using now().
# importing datetime module for now()
import datetime
# using now() to get current time
current_time = datetime.datetime.now()
# Printing value of now.
print("Name of student:Shaikh Rafee")
print("Roll no:47 Batch: D3 Branch:AI&DS")
print("Current date and time is:", current_time)
cstr='*'
print(cstr.ljust(70,'*'))
#(Above program code should be included in each program at the start of program code)
# Create an empty dictionary
student_dict = {}
# Function to determine grade based on marks
defcalculate_grade(marks):
if marks >= 85:
return 'A'
elif marks >= 70:
return 'B'
elif marks >= 50:
return 'C'
else:
return 'F'
# Get the number of students
n = int(input("Enter the number of students: "))
# Iterate over the range of students to collect information
for i in range(n):
roll_number = input("Enter roll number: ")
name = input("Enter name: ")
marks = float(input("Enter marks: "))
attendance = float(input("Enter attendance: "))
grade = calculate_grade(marks) # Calculate grade based on marks
# Add the student details to the dictionary
student_dict[roll_number] = {'name': name, 'marks': marks, 'attendance': attendance, 'grade':
grade}
# Display the names of students with marks above 75 and attendance above 75
print("\nStudents with marks above 75 and attendance above 75:")
print("-" * 60)
print(f"{'Name':<20} {'Marks':<10} {'Attendance':<10} {'Grade':<10}")
print("-" * 60)
for roll_number, student in student_dict.items():
if student['marks'] > 75 and student['attendance'] > 75:
print(f"{student['name']:<20} {student['marks']:<10} {student['attendance']:<10}
{student['grade']:<10}")
print("-" * 60)
# Updating student details
update_roll = input("\nEnter the roll number of the student to update: ")
if update_roll in student_dict:
# Update student's marks and attendance
new_marks = float(input(f"Enter new marks for {student_dict[update_roll]['name']}: "))
new_attendance = float(input(f"Enter new attendance for {student_dict[update_roll]['name']}:
"))
new_grade = calculate_grade(new_marks) # Recalculate grade based on new marks
# Update the dictionary
student_dict[update_roll]['marks'] = new_marks
student_dict[update_roll]['attendance'] = new_attendance
student_dict[update_roll]['grade'] = new_grade
print(f"\nUpdated details for {student_dict[update_roll]['name']}:")
print(f"Marks: {new_marks}, Attendance: {new_attendance}, Grade: {new_grade}")
else:
print("Student with this roll number does not exist.")
# Display all student records, including the updated ones in a table format
print("\nAll Student Records (Updated):")
print("-" * 70)
print(f"{'Roll Number':<15} {'Name':<20} {'Marks':<10} {'Attendance':<10} {'Grade':<10}")
print("-" * 70)
for roll_number, student in student_dict.items():
print(f"{roll_number:<15} {student['name']:<20} {student['marks']:<10}
{student['attendance']:<10} {student['grade']:<10}")
print("-" * 70)

Program Output:-
EXPERIMENT-8
Aim:-Develop a Python program that takes a numerical input and identifies whether it is even
or odd, utilizing conditional statements and loops.

Requirement:-Python 3.13.2

Program Code:-
# Getting current date and time using now().
# importing datetime module for now()
import datetime
# using now() to get current time
current_time = datetime.datetime.now()
# Printing value of now.
print("Name of student:Shaikh Rafee")
print("Roll no:47 Batch: D3 Branch:AI&DS")
print("Current date and time is:", current_time)
cstr='*'
print(cstr.ljust(70,'*'))
#(Above program code should be included in each program at the start of program code)
# Python program to check if the input number is odd or even.
# A number is even if division by 2 gives a remainder of 0.
# If the remainder is 1, it is an odd number.
for i in range(2): # Loop will run 5 times
# Taking input from the user
number = int(input("Enter a number: "))
# Checking if the number is even or odd
if number % 2 == 0:
print(f"{number} is even.")
else:
print(f"{number} is odd.")
# Ask if the user wants to check another number
cont = input("Do you want to check another number? (yes/no): ")
if cont != 'yes':
print("Goodbye!")
break # Exit the loop if the answer is not "yes"

Program Output:-
EXPERIMENT-9
Aim:-Design a Python program to compute the factorial of a given integer N.

Requirement:-Python 3.13.2

Program Code:-
# Getting current date and time using now().
# importing datetime module for now()
import datetime
# using now() to get current time
current_time = datetime.datetime.now()
# Printing value of now.
print("Name of student:Shaikh Rafee")
print("Roll no:47 Batch: D3 Branch:AI&DS")
print("Current date and time is:", current_time)
cstr='*'
print(cstr.ljust(70,'*'))
#(Above program code should be included in each program at the start of program code)
# Input: An integer number
num =int(input("Enter the number: "))
# Initialize the factorial variable to 1
factorial = 1
# Calculate the factorial using a for loop
for i in range(1, num + 1):
factorial *= i
# Output: The factorial of the number
print(f"The factorial of {num} is {factorial}")
Program Output:-
EXPERIMENT-10
Aim:-Using function, write a Python program to analyze the input number is prime or not.

Requirement:-Python 3.13.2

Program Code:-
# Getting current date and time using now().
# importing datetime module for now()
import datetime
# using now() to get current time
current_time = datetime.datetime.now()
# Printing value of now.
print("Name of student:Shaikh Rafee")
print("Roll no:47 Batch: D3 Branch:AI&DS")
print("Current date and time is:", current_time)
cstr='*'
print(cstr.ljust(70,'*'))
#(Above program code should be included in each program at the start of program code)
def is_prime(number):
# Handle edge case for numbers less than 2
if number < 2:
return False
# Check for factors from 2 to the square root of the number
for i in range(2, int(number ** 0.5) + 1):
if number % i == 0:
return False
return True
# Take input from the user
num = int(input("Enter a number to check if it is prime: "))
# Call the is_prime function and print the result
if is_prime(num):
print(f"{num} is a prime number.")
else:
print(f"{num} is not a prime number.")

Program Output:-
EXPERIMENT-11
Aim:-Implement a simple Python calculator that takes user input and performs basic arithmetic
operations (addition, subtraction, multiplication, division) using functions.

Requirement:- Python 3.13.2

Program Code:-
# Getting current date and time using now().
# importing datetime module for now()
import datetime
# using now() to get current time
current_time = datetime.datetime.now()
# Printing value of now.
print("Name of student:Shaikh Rafee")
print("Roll no:47 Batch: D3 Branch:AI&DS")
print("Current date and time is:", current_time)
cstr='*'
print(cstr.ljust(70,'*'))
#(Above program code should be included in each program at the start of program code)
# Python program for simple calculator
# Function to add two numbers
def add(num1, num2):
return num1 + num2
# Function to subtract two numbers
def subtract(num1, num2):
return num1 - num2
# Function to multiply two numbers
def multiply(num1, num2):
return num1 * num2
# Function to divide two numbers
def divide(num1, num2):
return num1 / num2
print("Please select operation -\n" \
"1. Add\n" \
"2. Subtract\n" \
"3. Multiply\n" \
"4. Divide\n")
n=5
for i in range(n):
# Take input from the user
select = int(input("Select operations form 1, 2, 3, 4 :"))
if select == 1:
number_1 = int(input("Enter first number: "))
number_2 = int(input("Enter second number: "))
print(number_1, "+", number_2, "=",
add(number_1, number_2))
elif select == 2:
number_1 = int(input("Enter first number: "))
number_2 = int(input("Enter second number: "))
print(number_1, "-", number_2, "=",
subtract(number_1, number_2))
elif select == 3:
number_1 = int(input("Enter first number: "))
number_2 = int(input("Enter second number: "))
print(number_1, "*", number_2, "=",
multiply(number_1, number_2))
elif select == 4:
number_1 = int(input("Enter first number: "))
number_2 = int(input("Enter second number: "))
print(number_1, "/", number_2, "=",
divide(number_1, number_2))
else:
print("Invalid input")
print("program Ended")

Program Output:-
EXPERIMENT-12
Aim:-Develop a Python program that reads a text file and prints words of specified lengths (e.g.,
three, four, five, etc.) found within the file.

Requirement:-Python 3.13.2

Program Code:-
# Getting current date and time using now().
# importing datetime module for now()
import datetime
# using now() to get current time
current_time = datetime.datetime.now()
# Printing value of now.
print("Name of student:Shaikh Rafee")
print("Roll no:47 Batch: D3 Branch:AI&DS")
print("Current date and time is:", current_time)
cstr='*'
print(cstr.ljust(70,'*'))
#(Above program code should be included in each program at the start of program code)
# Python program to read
# file word by word
# opening the text file
with open('abcd.txt','r') as file:
# reading each line
for line in file:
#count_word=4
# reading each word
for word in line.split():
#if len(word)==count_word:
# displaying the words
print(word)

Program Output:-
EXPERIMENT-14
Aim:-Write a Python program that takes two numbers as input and performs division.
Implement exception handling to manage division by zero and invalid input errors gracefully.

Requirement:-Python 3.13.2

Program Code:-
# Getting current date and time using now().
# importing datetime module for now()
import datetime
# using now() to get current time
current_time = datetime.datetime.now()
# Printing value of now.
print("Name of student:Shaikh Rafee")
print("Roll no:47 Batch: D3 Branch:AI&DS")
print("Current date and time is:", current_time)
cstr='*'
print(cstr.ljust(70,'*'))
#(Above program code should be included in each program at the start of program code)
# Example of an exception
for i in range(5):
try:
num1 = int(input("Enter First Number: "))
num2 = int(input("Enter Second Number: "))
result = num1 / num2
print(result)
except ValueError as e:
print("Invalid Input Please Input Integer...")
except ZeroDivisionError as e:
print(e)

Program Output:-

You might also like