Python Lab File
Python Lab File
University
Plot No. 2, Sector – 17 A,
Yamuna Expressway Greater
Noida,
Gautam Buddha Nagar
Uttar Pradesh,India
LAB FILE
Submitted By: Submitted To:
17 10/01/24 (i) Write a python program to open and write “hello world” 17
into
a file?
21 11/01/24 Write Python program using panda library for adding new 21
column admission no. to data frame. Initially, there are 3
column respectively name, marks and have some dummy
data for each columns.
Ques1: Write a Python Program for
factorial of a number?
factorial = 1
Radius = float (input ("Please enter the radius of the given circle:
"))
print (" The area of the given circle is: ", area_of_the_circle
(Radius))
Ques3: Write a Python program to print the calendar
of a given month and year.
import calendar
calculate_simple_interest(principal, rate,
time):
# Calcualtion
simple_interest = (principal*time*rate)/100
compound_interest = principal * ( (1+rate/100)**time - 1)
# Displaying result
print('Simple interest is: %f' % (simple_interest))
print('Compound interest is: %f' %(compound_interest))
Ques5. Write a Python program to calculate the
length of a string.
def multiply_all_items(input_list):
# Initialize the result to 1
result = 1
return result
# Example usage
if __name__ == "__main__":
# Get input from the user
input_list = [float(x) for x in input("Enter a list of
numbers separated by spaces: ").split()]
def find_largest_number(input_list):
# Check if the list is empty
if not input_list:
return "The list is empty."
# Example usage
if __name__ == "__main__":
# Get input from the user
input_list = [float(x) for x in input("Enter a list of
numbers separated by spaces: ").split()]
a)Update
b)Delete Set
# a) Update Dictionary
print("Original Dictionary:")
print(sample_dict)
# Example usage
if __name__ == "__main__":
# Sample dictionary
sample_dict = {'apple': 5, 'banana': 2, 'orange': 8,
'grape': 3}
# Create a dictionary
my_dict = {'apple': 5, 'banana': 2, 'orange': 8, 'grape': 3}
# 2) Access items
key_to_access = 'orange'
if key_to_access in my_dict:
value = my_dict[key_to_access]
print(f"2) Accessing item with key '{key_to_access}':
{value}")
else:
print(f"2) Key '{key_to_access}' not found in the
dictionary.")
# 3) Use get()
key_to_get = 'banana'
value_using_get = my_dict.get(key_to_get, "Key not found")
print(f"3) Using get() to access item with key
'{key_to_get}': {value_using_get}")
# 4) Change values
key_to_change = 'apple'
new_value = 10
if key_to_change in my_dict:
my_dict[key_to_change] = new_value
print(f"4) Changing value for key '{key_to_change}':
{new_value}")
else:
print(f"4) Key '{key_to_change}' not found in the
dictionary.")
# 5) Use len()
dictionary_length = len(my_dict)
print(f"5) Length of the dictionary: {dictionary_length}")
Ques13. Write a Python program to create a
tuple with different data types.: 1) Add items
2) len()
# Create an empty tuple
my_tuple = ()
# Create a tuple
my_tuple = (1, "Hello", 3.14, True, [1, 2, 3])
# fibonacci_module.py
def generate_fibonacci(n):
fib_sequence = [0, 1]
while len(fib_sequence) < n:
fib_sequence.append(fib_sequence[-1] +
fib_sequence[-2])
return fib_sequence
try:
with open(file_path, 'r', encoding='utf-8') as file:
for line in file:
words = line.split()
for word in words:
# Remove punctuation and convert to lowercase for better
comparison
cleaned_word = word.strip('.,!?()[]{}"\'').lower()
unique_words.add(cleaned_word)
except FileNotFoundError:
print(f"Error: File '{file_path}' not found.")
return set()
return unique_words
def main():
file_path = input("Enter the path to the text file: ")
unique_words = get_unique_words(file_path)
if unique_words:
sorted_unique_words = sorted(unique_words)
print("\nUnique Words (Alphabetical Order):")
for word in sorted_unique_words:
print(word)
else:
print("No unique words found.")
if __name__ == "__main__":
main()
Ques17. (i)Write a python program to open and
write “hello world” into a file?
# Program 2
class WelcomeMessage:
def display_message(self):
print("Welcome to BCA")
# Program (ii)
class MyClass:
# Data member
variable = "Hello from MyClass"
def display_message(self):
print("Message from the class:", self.variable)
# Create an object of the class and call the data member and function
my_obj = MyClass()
print("Data member value:", my_obj.variable)
my_obj.display_message()
# Program (iii)
class Calculator:
def add(self, num1, num2):
return num1 + num2
class StudentResult:
def __init__(self, marks1, marks2, marks3):
self.subject1 = marks1
self.subject2 = marks2
self.subject3 = marks3
def display_result(self):
total_marks = self.subject1 + self.subject2 + self.subject3
pass_mark = 40
def transpose_matrix(matrix):
try:
transposed_matrix = np.transpose(matrix)
return transposed_matrix
except ValueError:
print("Matrix transpose is not possible.")
return None
Ques20. Using a numpy module create an array
Axes of array
import numpy as np
import pandas as pd
df = pd.DataFrame(data)