0% found this document useful (0 votes)
15 views

Python Lab File

Uploaded by

alamnashra96
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Python Lab File

Uploaded by

alamnashra96
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 32

Galgotias

University
Plot No. 2, Sector – 17 A,
Yamuna Expressway Greater
Noida,
Gautam Buddha Nagar
Uttar Pradesh,India

School Of Computing Science & Engineering

LAB FILE
Submitted By: Submitted To:

Name: ALAM NASHRA ANSARI Mr. Pravin Kumar (sir)

Admission No.: 22SCSE1530001

Course Name: Programming inPython


Course Code: E1UA304C
School: CSE
Year: 2023-24
Semester: 3rd
Program: B.Sc. (Hons)CS
Session: 2nd year
INDEX
S. Date Name of the Experiment Page Remarks
No.
No

1 09/01/24 Write a Python Program for factorial of a 1


number?

2 09/01/24 Write a Python program which accepts the radius of a circle 2


from the user and computer the area?

3 09/01/24 Write a Python program to print the calendar of a given 3


month and year.

4 09/01/24 Write a Python Program for simple interest, and 4


compound interest

5 09/01/24 Write a Python program to calculate the length of a string. 5

6 09/01/24 Write a Python program to split and join a string 6

7 09/01/24 Write a Python program to demonstrate various ways of 7


accessing the string- By using Indexing (Both Positive and
Negative)

8 09/01/24 Write a Python program to multiply all the items in a list 8

9 09/01/24 Write a Python program to find smallest number in a 9


list, and to find largest number in a list.

10 09/01/24 Write Python program to perform following operations on 10


Dictionaries: a)Update Dictionary b)Delete Set c)Looping
through Dictionary

11 09/01/24 Write a Python script to sort (ascending and descending) 11


a dictionary by value.

12 10/01/24 Create a dictionary and apply the following Methods: 1) 12


Print the dictionary items 2) access items 3) use get()
4)change values 5) use len()

13 10/01/24 Write a Python program to create a tuple with different data 13


types. 1) Add items 2) len()

14 10/01/24 Write a Python program to create a tuple and perform the 14


following methods 1) check for item in tuple 2)Access
items
15 10/01/24 Write a python program to define a module to find 15
Fibonacci Numbers and import the module to another
program.
16 10/01/24 Write a program that inputs a text file. The program should 16
print all of the unique words in the file in alphabetical order.

17 10/01/24 (i) Write a python program to open and write “hello world” 17
into
a file?

(ii) Write a python program to write the content “hi


python programming” for the existing file.
18 10/01/24 (i) Write a python Program to display welcome to BCA by 18
using classes and objects.

(ii) Write a python Program to call data member and


function using classes and objects.

(iii) Write a program to find sum of two numbers using


class and methods.

(iv) Write a program to read 3 subject marks and display


pass or failed using class and object.

19 11/01/24 Write Python program for addition of two matrix using 19


numpy library and find transpose of matrix.

20 11/01/24 Using a numpy module create an array and check the 20


following:

1. Type of array 2. Axes of array

3. Shape of array 4. Type of elements in array

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?

# To take input from the user


num = int(input("Enter a number: "))

factorial = 1

# check if the number is negative, positive or zero


if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print("The factorial of",num,"is",factorial)
Ques2: Write a Python program which accepts the
radius of a circle from #the user and computer
the area?
import math

def area_of_the_circle (Radius):


area = Radius** 2 * math.pi
return area

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

# Prompt the user to input the year and month


y = int(input("Input the year : "))
m = int(input("Input the month : "))

# Print the calendar for the specified year and month


print(calendar.month(y, m))
Ques4. Write a Python Program for simple

interest, and compound interest def

calculate_simple_interest(principal, rate,

time):

# Simple and Compound Interest

# Reading principal amount, rate and time


principal = float(input('Enter amount: '))
time = float(input('Enter time: '))
rate = float(input('Enter rate: '))

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

# User inputs the string and it gets stored in variable str


str = input("Enter a string: ")

# counter variable to count the character in a string


counter = 0
for s in str:
counter = counter+1
print("Length of the input string is:", counter)
Ques6: Write a Python program to split and
join a string def
split_and_join_string(string, delimiter)

def split_and_join_string(string, delimiter):


return delimiter.join(string.split())

# Get input from the user


user_string = input("Enter a string: ")
user_delimiter = input("Enter a delimiter: ")

# Call the function and print the result


result_string = split_and_join_string(user_string,
user_delimiter)
print("Result after split and join:", result_string)
Ques7. Write a Python program to demonstrate
various ways of #accessing the string- By using
Indexing (Both Positive and #Negative)
def access_string(string):
# Accessing string using positive indexing
print("Using positive indexing:")
for i in range(len(string)):
print(f"Character at index {i}: {string[i]}")

# Accessing string using negative indexing


print("\nUsing negative indexing:")
for i in range(-1, -len(string) - 1, -1):
print(f"Character at index {i}: {string[i]}")

# Get input from the user


user_string = input("Enter a string: ")

# Call the function to demonstrate string access


access_string(user_string)
Ques8. Write a Python program to multiply all
the items in a list. def
multiply_all_items(list)

def multiply_all_items(input_list):
# Initialize the result to 1
result = 1

# Multiply each element in the list


for item in input_list:
result *= item

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

# Call the function and print the result


result = multiply_all_items(input_list)
print(f"The product of all items in the list: {result}"
Ques9. Write a Python program to find smallest
number in a list, and to find largest number in
a list
def find_smallest_number(input_list):
# Check if the list is empty
if not input_list:
return "The list is empty."

# Initialize the smallest number with the first element


smallest = input_list[0]

# Find the smallest number in the list


for num in input_list:
if num < smallest:
smallest = num

return f"The smallest number in the list is: {smallest}"

def find_largest_number(input_list):
# Check if the list is empty
if not input_list:
return "The list is empty."

# Initialize the largest number with the first element


largest = input_list[0]

# Find the largest number in the list


for num in input_list:
if num > largest:
largest = num

return f"The largest number in the list is: {largest}"

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

# Call the functions and print the results


print(find_smallest_number(input_list))
print(find_largest_number(input_list))
Ques10 Write Python program to perform
following operations on Dictionaries:

a)Update

b)Delete Set

c)Looping through Dictionary


def perform_operations_on_dictionary():
# Initialize a sample dictionary
sample_dict = {'a': 1, 'b': 2, 'c': 3, 'd': 4}

# a) Update Dictionary
print("Original Dictionary:")
print(sample_dict)

# Update the value of key 'b'


sample_dict['b'] = 10
print("\nDictionary after updating 'b':")
print(sample_dict)

# Add a new key-value pair 'e': 5


sample_dict['e'] = 5
print("\nDictionary after adding 'e':")
print(sample_dict)

# b) Delete Set (Delete key 'c')


del sample_dict['c']
print("\nDictionary after deleting 'c':")
print(sample_dict)

# c) Looping through Dictionary


print("\nLooping through Dictionary:")
for key, value in sample_dict.items():
print(f"Key: {key}, Value: {value}")

# Call the function to perform operations on the dictionary


perform_operations_on_dictionary()
Ques11. Write a Python script to sort
(ascending and descending) a dictionary by
value.

def sort_dictionary_by_value(input_dict, ascending=True):


# Use the sorted() function with a lambda function as
the key parameter
sorted_dict = dict(sorted(input_dict.items(), key=lambda
item: item[1], reverse=not ascending))
return sorted_dict

# Example usage
if __name__ == "__main__":
# Sample dictionary
sample_dict = {'apple': 5, 'banana': 2, 'orange': 8,
'grape': 3}

# Sorting in ascending order


ascending_sorted_dict =
sort_dictionary_by_value(sample_dict, ascending=True)
print("Dictionary sorted in ascending order by value:")
print(ascending_sorted_dict)

# Sorting in descending order


descending_sorted_dict =
sort_dictionary_by_value(sample_dict, ascending=False)
print("\nDictionary sorted in descending order by
value:")
print(descending_sorted_dict)
Ques12. Create a dictionary and apply the
following Methods: 1) Print the dictionary
items 2) access items 3) use get() 4)change
values 5) use len() my_dict

# Create a dictionary
my_dict = {'apple': 5, 'banana': 2, 'orange': 8, 'grape': 3}

# 1) Print the dictionary items


print("1) Dictionary items:")
print(my_dict)

# 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 = ()

# Add items to the tuple


my_tuple += (1, "Hello", 3.14, True, [1, 2, 3])

# Display the tuple


print("Tuple after adding items:", my_tuple)

# Calculate and display the length of the tuple


tuple_length = len(my_tuple)
print("Length of the tuple:", tuple_length)
Ques14 Write a Python program to create a
tuple and perform the following methods: 1)
check for item in tuple 2)Access items

# Create a tuple
my_tuple = (1, "Hello", 3.14, True, [1, 2, 3])

# Check for an item in the tuple


item_to_check = "Hello"
if item_to_check in my_tuple:
print(f"{item_to_check} is present in the tuple.")
else:
print(f"{item_to_check} is not present in the tuple.")

# Access items in the tuple by index


index_to_access = 2
if 0 <= index_to_access < len(my_tuple):
accessed_item = my_tuple[index_to_access]
print(f"Item at index {index_to_access}:
{accessed_item}")
else:
print(f"Index {index_to_access} is out of range for the
tuple.")
Ques15. Write a python program to define a
module to find Fibonacci Numbers and import the
module to another program.

# 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

# Test the module if needed


if __name__ == "__main__":
n_terms = int(input("Enter the number of Fibonacci terms
to generate: "))
result = generate_fibonacci(n_terms)
print(f"Fibonacci Sequence ({n_terms} terms): {result}")
Ques16. Write a program that inputs a text

file. The program should print all of the

unique words in the file in alphabetical order.


def get_unique_words(file_path):
unique_words = set()

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?

(ii)Write a python program to write the


content “hi python programming” for the
existing file.
# Program 1

file_path = "hello_world.txt" # File path

# Open the file in write mode


with open(file_path, 'w', encoding='utf-8') as file:
# Write "hello world" into the file
file.write("hello world")

print("Content written to the file:", file_path)

# Program 2

file_path = "hello_world.txt" # Same file path used in


Program 1

# Open the file in append mode


with open(file_path, 'a', encoding='utf-8') as file:
# Write "hi python programming" into the file
file.write("\nhi python programming")

print("Content appended to the file:", file_path)


Ques18:(i) Write a python Program to display
welcome to BCA by using classes and objects.

(ii)Write a python Program to call data


member and function using classes and
objects.

(iii)Write a program to find sum of two


numbers using class and methods.

(iv)Write a program to read 3 subject marks and


display pass or failed using class and object.
# Program (i)

class WelcomeMessage:
def display_message(self):
print("Welcome to BCA")

# Create an object of the class and call the method


welcome_obj = WelcomeMessage()
welcome_obj.display_message()

# 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

# Create an object of the class and call the method


calculator_obj = Calculator()
result = calculator_obj.add(5, 7)
print("Sum of two numbers:", result)
# Program (iv)

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

if total_marks >= (3 * pass_mark):


print("Congratulations! Passed")
else:
print("Sorry! Failed")

# Read marks from the user


marks_subject1 = int(input("Enter marks for Subject 1: "))
marks_subject2 = int(input("Enter marks for Subject 2: "))
marks_subject3 = int(input("Enter marks for Subject 3: "))

# Create an object of the class and call the method


result_obj = StudentResult(marks_subject1, marks_subject2, marks_subject3)
result_obj.display_result()
Ques19. Write Python program for addition of two
matrix using numpy library and find transpose of
matrix.
import numpy as np

def add_matrices(matrix1, matrix2):


try:
result_matrix = np.add(matrix1, matrix2)
return result_matrix
except ValueError:
print("Matrix addition is not possible. Make sure
both matrices have the same shape.")
return None

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

and check the following: # 1. Type of array 2.

Axes of array

import numpy as np

# Create a NumPy array


my_array = np.array([[1, 2, 3], [4, 5, 6]])

# Check the type of array


array_type = type(my_array)
print("1. Type of array:", array_type)

# Check the axes of array


array_axes = my_array.ndim
print("2. Axes of array:", array_axes)

# 3. Shape of array 4. Type of elements in array


import numpy as np

# Create a NumPy array


my_array = np.array([[1, 2, 3], [4, 5, 6]])

# Check the shape of array


array_shape = my_array.shape
print("3. Shape of array:", array_shape)

# Check the type of elements in array


array_element_type = my_array.dtype
print("4. Type of elements in array:", array_element_type)
Ques21. Write Python program using panda
library for adding new column admission no. to
data frame. Initially, there are 3 column
respectively name, marks and have some dummy
data for each columns.

import pandas as pd

# Create a DataFrame with dummy data


data = {'name': ['John', 'Alice', 'Bob'],
'marks': [85, 92, 78]}

df = pd.DataFrame(data)

# Display the original DataFrame


print("Original DataFrame:")
print(df)

# Add a new column "admission_no" with dummy data


df['admission_no'] = ['A001', 'A002', 'A003']

# Display the DataFrame after adding the new column


print("\nDataFrame with New Column (admission_no):")
print(df)

You might also like