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

Ankush 4541 CP Practical File

Uploaded by

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

Ankush 4541 CP Practical File

Uploaded by

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

COMPUTER PROGRAMMING

Practical File

Netaji Subhas University of Technology


Session - 2023-2024

Name - ANKUSH VISHWAKARMA

Roll No. - 2023UEE4541


INDEX
1a) Install Python and set up the development environment.

1b) Write a Python program to print "Hello, World!"

2a) Write a Python program to calculate the area of a circle given the radius.

2b) Perform basic arithmetic operations on variables

3a) Write a Python program to check if a number is even or odd

3b) Implement a simple calculator using conditional statements

4a) Write a Python program to print the Fibonacci series using a for loop.

5a) Write a function to calculate the sum of two numbers.

5b) Implement a function to check if a given string is a palindrome

6a) Perform various operations on lists (e.g., sorting, slicing).

6b) Use dictionaries to store and retrieve student grades.

7a) Create a class to represent a book with attributes and methods

7b) Implement inheritance by creating subclasses for different types of books

8a) Write a generator function to generate the Fibonacci series.

8b) Use lambda functions, map, and filter to perform operations on a list.

9a) Create a module that contains functions for mathematical operations.

9b) Import and use functions from external packages (e.g., math, random).

10a) Create and manipulate NumPy arrays

10b) Perform basic operations and indexing on arrays

11a) Implement string operations (e.g., concatenation, slicing).

11b) Use regular expressions to validate email addresses

12a) Read data from a text file and perform operations

12b) Handle exceptions for file operations and input validation.


1a. Install python and set up the development environment.

1b. Write a Python program to print "Hello, World!”

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}”

2b. Perform basic arithmetic operations on variables


a=int(input("Enter first
number: ")) b=int(input("Enter
second number: ")) print(f"""
The sum of {a} and {b} is {a+b}
The difference of {a} and {b}
is {a-b} The product of {a} and
{b} is {a*b}
The division of {a} by {b} gives {round(a/b,2)}""")

3a. Write a Python program to check if a number is even or odd


a=int(input("Enter a number
to check:"))
if a%2==0:
3
print("The number
is even”)
else:
print("The number is odd”)

3b. Implement a simple calculator using conditional statements


while True:
print("
"" Menu:
1.Addition
2.Subtraction
3.Multiplication
4.Division
5.Quit
""")
ch=int(input("Enter the no. corresponding to your choice: "))

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:

print("Enter valid choice")

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)}")

5b. Implement a function to check if a given string is a palindrome.

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")

str1=input("Enter the string to check if its a palindrome: ")


palindrome(str1)

6a. Perform various operations on a list (e.g., sorting, slicing).


l=[]
n=int(input("Enter the no. of elements required in the list: "))
7
for i in range(1,n+1):
a=int(input(f"Enter element {i}: "))
l.append(a)
while True:
print("")
print(f"Original List: {l}")
print("""
Menu for list operations:
1.Sorting in ascending order
2.Sorting in descending order
3.Reversing a list
4.Appending an element
5.Slicing of list
6.Returning the index of an element
7.Removing an element
8.Removing an element by its index
9.Extending the list to another list
10.Exit”"")

ch=int(input("Enter the number corresponding to your choice:"))


if ch==1:
l.sort()
print(f"List sorted in ascending order: {l}")
elif ch==2:
l.sort()
l.reverse()
print(f"List sorted in ascending order: {l}")
elif ch==3:
l.reverse()
print(f"List reversed: {l}")
elif ch==4:
a=int(input("Enter an element to append in the list: "))
l.append(a)
print(f"List after appending {a}: {l}")
elif ch==5:
a=int(input("Enter starting index: "))
b=int(input("Enter stopping index: "))
c=int(input("Enter step: "))
print(f"Sliced list: {l[a:b:c]}")
elif ch==6:
a=int(input("Enter the element to find its index: "))
b=l.index(a)
if b==-1:
print(f"{a} not present in the list: {l}")
8
else:
print(f"Index of first occurence of {a}: {b}")
elif ch==7:
a=int(input("Enter the element to be removed: "))
print(f"List after removing {a}: {l.remove(a)}")
elif ch==8:
a=int(input("Enter the index of element to be removed: "))
del l[a]
print("List after removing {a}:",l)
elif ch==9:
n1=int(input("Enter the no. of elements required in the second
list: "))
for i in range (n1):
a=int(input("Enter element",i,": "))
l1.append(a)
print(f"Second List: {l1}")
print(f"Extended list: {l1.extend(l2)}")
elif ch==10:
break
else:
print("Enter a valid choice")

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"

def apply_discount(self, percentage):


if 0 <= percentage <= 100:
discount = (percentage / 100) * self._price
self._price -= discount
return self._price
else:
print("Invalid discount percentage. Must be between 0 and
100.")

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

# Use mutators to update


book1.title = "1984"
print("\nAfter updating title of",book1._author,"'s book:")
print(book1.display_info())

# Use facilitator to apply discount


discounted_price = book2.apply_discount(10) # 10% discount
print(f"\nPrice after 10% discount on {book2._title}: Rs.
{discounted_price:.2f}")

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"

def apply_discount(self, percentage):


if 0 <= percentage <= 100:
discount = (percentage / 100) * self._price
self._price -= discount
return self._price
else:
print("Invalid discount percentage. Must be between 0 and
100.")

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

# Accessors for the new attributes


@property
def file_size(self):
return self._file_size

@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}"

# Overriding display_info to include EBook specific details


def display_info(self):
book_info = super().display_info() # Fetching info from parent

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

8a. Write a python program to implement a generator function


to generate the fibonacci sequence.
def fibonacci_generator(n):
"""n= no. of terms"""
a, b = 0, 1
for _ in range(n):
yield a
a, b = b, a + b

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

# 1. Square all numbers in the list


squared_numbers = list(map(lambda x: x**2, numbers))
print("Squared Numbers:", squared_numbers)

# 2. Extract only the even numbers


even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print("Even Numbers:", even_numbers)

# 3. Double the even numbers


doubled_even_numbers = list(map(lambda x: x*2, even_numbers))
print("Doubled Even Numbers:", doubled_even_numbers)

9a. Create a module that contains functions for mathematical


operations.
#mathopsmodule.py
def add(a, b):
"""Return the sum of a and b."""
return a + b

18
def subtract(a, b):
"""Return the result of subtracting b from a."""
return a - b

def multiply(a, b):


"""Return the product of a and b."""
return a * b

def divide(a, b):


"""Return the result of dividing a by b."""
if b == 0:
raise ValueError("Cannot divide by zero!")
return a / b

# main.py

import mathopsmodule as mo

a = 10
b = 5

print(mo.add(a, b)) # Outputs: 15


print(mo.subtract(a, b)) # Outputs: 5
print(mo.multiply(a, b)) # Outputs: 50
print(mo.divide(a, b)) # Outputs: 2.0

19
9b. Import and use functions from external packages (e.g., math,
random).
import math

# Use the constant pi


print("Value of Pi:", math.pi)

# Compute the square root


print("Square root of 16:", math.sqrt(16))

# Compute the factorial


print("Factorial of 5:", math.factorial(5))

# Compute the cosine of an angle (angle is in radians)


print("Cosine of pi/4:", math.cos(math.pi / 4))

import random

# Generate a random number between 0 and 1


print("Random float between 0 and 1:", random.random())

# Generate a random integer between two numbers (inclusive)


print("Random integer between 10 and 20:", random.randint(10, 20))

# Choose a random element from a list


choices = ["apple", "banana", "cherry", "date"]
print("Random fruit:", random.choice(choices))

# Shuffle a list
random.shuffle(choices)
print("Shuffled list:", choices)

20
10a. Create and manipulate NumPy arrays.
import numpy as np

# Creating NumPy arrays


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

# Accessing and manipulating NumPy arrays


element = arr2[1, 2] # Access an element
row = arr2[1, :] # Get the second row
col = arr2[:, 2] # Get the third column
submatrix = arr2[:2, 1:3] # Get a 2x2 sub-matrix

add_result = arr1 + 1 # Element-wise addition


multiply_result = arr1 * 2 # Element-wise multiplication

sum_result = arr1 + arr1 # Element-wise addition between arrays


product_result = arr1 * arr1 # Element-wise multiplication between arrays

mat_mult_result = np.dot(arr2, arr2.T) # Matrix multiplication

transposed = arr2.T # Transpose the matrix


reshaped = arr1.reshape(3, 1) # Reshape the array

max_val = arr1.max() # Find the maximum value


min_val = arr1.min() # Find the minimum value

mean = arr1.mean() # Compute the mean


median = np.median(arr1) # Compute the median
std_dev = arr1.std() # Compute the standard deviation

# Display the results


print("Original Array:")
print(arr1)
print("\nOriginal Matrix:")
print(arr2)

print("\nAccessing and Slicing:")


print("Element at (1, 2):", element)
print("Second Row:", row)
print("Third Column:", col)
print("Sub-matrix (first 2 rows and columns 1 to 2):\n", submatrix)

print("\nElement-wise Operations:")

21
print("arr1 + 1 =", add_result)
print("arr1 * 2 =", multiply_result)

print("\nElement-wise Operations Between Arrays:")


print("arr1 + arr1 =", sum_result)
print("arr1 * arr1 =", product_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)

# Indexing: Accessing elements in the array


print("Element at index 0:", arr[0]) # Accessing the first element
print("Element at index 3:", arr[3]) # Accessing the fourth element
# Slicing: Creating a new array from a slice of the original array

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

# Create an array of strings


str_arr = np.array(["apple", "banana", "cherry", "date", "elderberry"])

# Concatenation of string arrays


concatenated_str = np.char.add(str_arr, " is a fruit")
print("Concatenated Array:", concatenated_str)

# Split a string into an array of substrings


split_arr = np.char.split(str_arr, 'e')
print("Split Array:", split_arr)

# Join an array of strings into a single string


joined_str = np.char.join(',', str_arr)
print("Joined String:", joined_str)

# Uppercase and lowercase conversion


uppercase_str = np.char.upper(str_arr)
print("Uppercase Array:", uppercase_str)

lowercase_str = np.char.lower(str_arr)
print("Lowercase Array:", lowercase_str)

# Count the occurrences of a substring in each string


count = np.char.count(str_arr, 'e')
print("Count of 'e' in each string:", count)

# Replace a substring with another in each string


replaced_str = np.char.replace(str_arr, 'e', 'i')
print("Replaced Array:", replaced_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+'

# Use the re.match() function to search for a match at the beginning


of the string
if re.match(pattern, email):
return True
else:
return False

# Example usage:
email1 = "[email protected]"
email2 = "invalid-email"
email3 = "missing@dotcom."

print("Email 1 is valid:", is_valid_email(email1))


print("Email 2 is valid:", is_valid_email(email2))
print("Email 3 is valid:", is_valid_email(email3))

12a. Read data from a text file and perform operations.


# Open the file in read mode
with open("data.txt", "r") as file:
# Read the file line by line and convert each line to an integer
numbers = [int(line.strip()) for line in file]

# Display the read data


print("Data read from the file:", numbers)

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)

# Display the results


print("Sum of numbers:", sum_of_numbers)
print("Average:", average)
print("Maximum value:", max_value)
print("Minimum value:", min_value)

12b. Handle exceptions for file operations and input validation.


try:
# Open the file in read mode
with open("data.txt", "r") as file:
# Read the file line by line and convert each line to an integer
numbers = [int(line.strip()) for line in file]

27
# Display the read data
print("Data read from the file:", numbers)

# Perform operations on the data


sum_of_numbers = sum(numbers)
average = sum_of_numbers / len(numbers)
max_value = max(numbers)
min_value = min(numbers)

# Display the results


print("Sum of numbers:", sum_of_numbers)
print("Average:", average)
print("Maximum value:", max_value)
print("Minimum value:", min_value)

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

You might also like