Ankush 4541 CP Practical File
Ankush 4541 CP Practical File
Practical File
2a) Write a Python program to calculate the area of a circle given the radius.
4a) Write a Python program to print the Fibonacci series using a for loop.
8b) Use lambda functions, map, and filter to perform operations on a list.
9b) Import and use functions from external packages (e.g., math, random).
print("Hello World!")
2a. Write a Python program to calculate the area of a circle given the
radius.
from math import pi
r=float(input("Enter the radius of the
circle:”)) A= pi*r*r
Area=round(A,2)
2
print(f"Area of circle of radius {r} is {Area}”
if ch==1:
x = float(input("Enter first
number: ")) y = float(input("Enter
second number: ")) print(f"Sum of
{x} and {y} = {x+y}")
elif ch==2:
x = float(input("Enter first
number: ")) y = float(input("Enter
second number: "))
print(f"Difference of {x} and {y} =
{x-y}") elif ch==3:
x = float(input("Enter first
number: ")) y = float(input("Enter
second number: ")) print(f"Product
4
of {x} and {y} = {x*y}")
elif ch==4:
x = float(input("Enter first
number: ")) y = float(input("Enter
second number: ")) if y==0:
print("Division by 0 is not
possible") else:
print(f"Division of {x} by {y} = {x/
y}") elif ch==5:
brea
k else:
5
4a. Write a python program to print the fibonacci series using a for loop.
n=int(input("Enter the no. of terms: "))
l=[0,1]
s=0
for i in range(n-2):
s=l[-1]+l[-2]
l.append(s)
print("Fibonacci Series")
for i in l:
print(i, end=" “)
6
5a. Write a function to calculate the sum of two numbers.
def sum(a,b):
sum=a+b
return sum
x = float(input("Enter first number: "))
y = float(input("Enter second number: "))
print(f"Sum of {x} and {y} = {sum(x,y)}")
def palindrome(str):
str1=str.lower()
str2=str1[::-1]
if str1==str2:
print("Given string is a palindrome")
else:
print("Given string is not a palindrome")
9
10
6b. Use dictionaries to store and retrieve student grades.
a=int(input("Enter the no. of students for entering records: "))
student_rec={}
for i in range(1,a+1):
name=input(f"Enter the name of student {i}: ")
grade=input("Enter grade: ")
student_rec[name]=grade
print("")
print("Student Record")
for i in student_rec:
print(f"{i} : {student_rec[i]}")
print("")
while True:
c=input("Enter the name of student to retrieve grade (Any key to
exit)")
if c in student_rec:
print(f"Grade given to {c} is {student_rec[c]}")
else:
break
11
7a. Write a python program to implement a class
to represent a book with attributes and methods.
class Book:
def init (self, title, author, genre, price):
self._title = title
self._author = author
self._genre = genre
self._price = price
# Accessors (Getters)
@property
def title(self):
return self._title
@property
def author(self):
return self._author
@property
def genre(self):
return self._genre
12
@property
def price(self):
return self._price
# Mutators (Setters)
@title.setter
def title(self, new_title):
self._title = new_title
@author.setter
def author(self, new_author):
self._author = new_author
@genre.setter
def genre(self, new_genre):
self._genre = new_genre
@price.setter
def price(self, new_price):
if new_price >= 0:
self._price = new_price
else:
print("Price cannot be negative.")
# Facilitators
def display_info(self):
return f"Title: {self._title}\nAuthor: {self._author}\nGenre:
{self._genre}\nPrice: Rs. {self._price:.2f}\n"
# Demonstration
book1 = Book("Nineteen Eighty-Four", "George Orwell", "Dystopian Fiction",
200)
book2 = Book("Norwegian Wood", "Haruki Murakami","Fiction and
13
Romance",400)
print(book1.display_info())
print(book2.display_info())
14
7b. Write a python program to implement inheritance in the above
class.
class Book:
def init (self, title, author, genre, price):
self._title = title
self._author = author
self._genre = genre
self._price = price
# Accessors (Getters)
@property
def title(self):
return self._title
@property
def author(self):
return self._author
@property
def genre(self):
return self._genre
@property
def price(self):
return self._price
# Mutators (Setters)
@title.setter
def title(self, new_title):
self._title = new_title
@author.setter
def author(self, new_author):
self._author = new_author
@genre.setter
def genre(self, new_genre):
self._genre = new_genre
@price.setter
def price(self, new_price):
if new_price >= 0:
15
self._price = new_price
else:
print("Price cannot be negative.")
# Facilitators
def display_info(self):
return f"Title: {self._title}\nAuthor: {self._author}\nGenre:
{self._genre}\nPrice: Rs. {self._price:.2f}\n"
class EBook(Book):
def init (self, title, author, genre, price, file_size,
file_format):
super(). init (title, author, genre, price) # Initializing
attributes from parent class
self._file_size = file_size
self._file_format = file_format
@property
def file_format(self):
return self._file_format
# Facilitators
def display_file_info(self):
return f"File Size: {self._file_size}MB\nFile Format:
{self._file_format}"
16
class
return book_info + f"\n{self.display_file_info()}"
#Demonstration
if name == " main ":
ebook1 = EBook("1984", "George Orwell", "Dystopian Fiction", 100, 5,
"EPUB")
print(ebook1.display_info())
# Demonstration
if name == " main ":
n = int(input("How many Fibonacci numbers would you like to generate?
"))
for num in fibonacci_generator(n):
print(num, end= " ")
17
8b. Use lambda functions, map, and filter to perform operations on a
list.
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print("Original list: ",numbers)
18
def subtract(a, b):
"""Return the result of subtracting b from a."""
return a - b
# main.py
import mathopsmodule as mo
a = 10
b = 5
19
9b. Import and use functions from external packages (e.g., math,
random).
import math
import random
# Shuffle a list
random.shuffle(choices)
print("Shuffled list:", choices)
20
10a. Create and manipulate NumPy arrays.
import numpy as np
print("\nElement-wise Operations:")
21
print("arr1 + 1 =", add_result)
print("arr1 * 2 =", multiply_result)
print("\nMatrix Multiplication:")
print("Matrix Multiplication of arr2 with itself:")
print(mat_mult_result)
print("\nTransposed Matrix:")
print(transposed)
print("\nReshaped Array:")
print(reshaped)
print("\nStatistics:")
print("Max Value:", max_val)
print("Min Value:", min_val)
print("Mean:", mean)
print("Median:", median)
print("Standard Deviation:", std_dev)
22
10b. Perform basic operations and indexing on arrays.
import numpy as np
# Creating an array
arr = np.array([1, 2, 3, 4, 5])
# Displaying the array
print("Original Array:", arr)
23
sliced_arr = arr[1:4] # Elements at index 1, 2, and 3
print("Sliced Array:", sliced_arr)
# Array operations
# Addition
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
addition_result = arr1 + arr2
print("Addition Result:", addition_result)
# Subtraction
subtraction_result = arr2 - arr1
print("Subtraction Result:", subtraction_result)
# Multiplication
multiplication_result = arr1 * arr2
print("Multiplication Result:", multiplication_result)
# Division
division_result = arr2 / arr1
print("Division Result:", division_result)
# Element-wise operations
# Square of each element
squared_arr = arr ** 2
print("Squared Array:", squared_arr)
# Square root of each element
sqrt_arr = np.sqrt(arr)
print("Square Root Array:", sqrt_arr)
# Sum of all elements in the array
sum_of_elements = np.sum(arr)
print("Sum of Array Elements:", sum_of_elements)
24
11a. Implement string operations (e.g., concatenation, slicing).
import numpy as np
lowercase_str = np.char.lower(str_arr)
print("Lowercase Array:", lowercase_str)
25
11b. Use regular expressions to validate email addresses.
import re
def is_valid_email(email):
# Regular expression for a basic email address validation
pattern = r'^[\w\.-]+@[\w\.-]+\.\w+'
# Example usage:
email1 = "[email protected]"
email2 = "invalid-email"
email3 = "missing@dotcom."
26
# Perform operations on the data
sum_of_numbers = sum(numbers)
average = sum_of_numbers / len(numbers)
max_value = max(numbers)
min_value = min(numbers)
27
# Display the read data
print("Data read from the file:", numbers)
except FileNotFoundError:
print("File not found. Please check the file path or existence.")
except ValueError:
print("Invalid data in the file. Make sure all lines contain valid
integers.")
except ZeroDivisionError:
print("Cannot calculate the average with no data.")
except Exception as e:
print("An unexpected error occurred:", str(e))
28