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

Computer Programming Project

Cp project

Uploaded by

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

Computer Programming Project

Cp project

Uploaded by

deepakguptaab321
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 17
Computer Programming Lab (FCCS0102) Department of Information Technology Netaji Subhas University of Technology Submitted by- Name Roll Number Kartik Grover | 2024UIT2342 Khushi Bhandari_| 2024UIT2358 Kanishk Singaria_| 2024UIT2556 Jatin Sahu 2024UIT2855 Krati Gupta 2024UIT3041 Deepak Gupta 2024UIT3042 INDEX S.No. Program Remarks Install python and set up the development environment. 1b | Write a python program to print Hello World. Ic | Write a program to calculate area of a circle. 2a __| Write a python program to check if a number is even or odd. 2b | Write a python program to implement a simple calculator using conditional statement. 2c | Write a python program to print the Fibonacci series using for loop. 3a__| Implement a function to check if a given string is Palindrome. 3b__| Perform various operation on list. 3c | Write a python program use dictionaries to store and retrieve student grades. 4a__| Create a class to represent a book with attributes and methods. 4b | Write a python program to implement inheritance in the above class. 4c | Write a python program to implement a generator function to generate the fibonacci sequence. 5a__| Use lambda functions, map, and filter to perform operations on a list. Sb | Create a module that contains functions for mathematical operations. 6a __| Create and manipulate NumPy arrays. 6b __| Perform basic operations and indexing on arrays. 7a | Implement string operations. 7b | Use regular expressions to validate email addresses. 8a __| Read data from a text file and perform operations. 8b | Handle exceptions for file operations and input validations. Program 1 1a.Install python and set up the development environment. python After installing the setup adding it to path IDLE Shel 3.126 - a x File Edit Shell Debug Options Window Help Python 3.12.6 (tags/v3.12.é:adazdab, Sep € 2024, 20:11:23) [MSC v.i940 €4 bit ( aNDE4)] on win32 ‘Type "help", "copyright", "credits" or "license()" for more information. 1b. Write a python program to print Hello World. Code print("Hello World") Output: a) Clem) 1c. Write a program to calculate area of a circle. Code from math import pi r=float(input("Enter radius of the circle:”)) print(“Area of the circle i Output: Program 2 2a, Write a python program to check if a number is even or odd. Code a=int(input("Enter the number : ")) if a%2==0: print(f" {a} is a even number”) else print(P" {a} is a odd number”) Output : Semel a) OPERA E emus (Program finished) 2b. Write a python program to implement a simple calculator using conditional statement. Code while True: print("What do you want to perform?\n1.Addition\n2,Subtraction\n3.Multiplication\n4. Division\n5.Exit") x=int(input("Enter Choice: ")) n1=float(input("Enter first number: ")) n2=float(input("Enter second number: ")) if(x==1); print(f" {nl }+{n2}=",nl-+n2) elif(x==2): print(f" {nl }-{n2)=",nl-n2) elif(x==3): print(f" {nl }x{n nl*n2) elif(x==4): print(f" {nl }/{n2}=",n1/n2) elifix==5): break else: print("Enter a valid choice!!") Output : ye nter first. numb peer eee end ra aera] me tee Pere nen arti eer opbsinar) ior re series using for loop. n=int(input("Enter number of elements: ")) print(f"Fibonacci series with (n} elements:",a,b,end=" fori in range(0,n-2) c=atb print(c,end="") azb bee Output: EMMI eae cee Program 3 3a. Implement a function to check if a given string is Palindrome. Code: def pallindrome(s): slss(:-1] sl) print(f"{s} is pallindrome.”") else: print(f"{s} is not pallindrome.") input("Enter string: ") pallindrome(s) Output: Se eae eS) 3b. Perform various operation on list. Code: ] int(input("Enter the no. of elements required in the list: ")) hn for i in range(1.n+1): a=int(input(f"Enter element (i): ")) Lappend(a) while True: print("") print(f"Original List: (1)") print("Menu for list operations:\n1 Sorting in ascending ordes order\n3.Reversing a list\n4.Appending an element\n5.Slicing of ch=int(input("Enter choice:” if ch== Lsort() n2.Sorting in descending n6.Exit print(f" elif ch: Lsort() Lreverse() print(f"List sorted in descending order: {1}") elif ch: Lreverse() print(f"List reversed: {1}") elif ch==4: a=int(input("Enter an element to append in the list: ")) Lappend(a) print(f"List after appending {a}: (1}") elif ch==5: a=int(input("Enter starting index: ")) b=int(input("Enter stopping index: ")) c=int(input("Enter step: ")) print({"Sliced list: (Ifa:b:e])") elif ch==6: break else: print("Enter a valid choice") Output: st sorted in ascending order: {1}") Cs ay Cen Priya meee scr SUEUR age SO eon an ister ts nding an el ost Cireamegt SE (Bryaraer One ett Original List: [12, 23, 34, 54, 76] CeCe Seas ie Te Pegs Ue UR ang Page OR Ceca ar egg PaO Gaeta CaN Uae Cog 5.Slicing of list oats Clea Cabo List sorted in ascending order: [76, 54, 34, Original List: [76, 54, 34, 23, 12] Dn Cap staat Carts Ce eee eS ae Pes eR ec ae ERS aera Ce eeu ERS b at ease nis 6.Exit Lee Cate) Pee , 34, 54, 76] Cage ec eg igs URC gs OES bes Daa es Site res Soest uetcc rain! 3c. Wi ea python program use dictionaries to store and retrieve student grades. input("Enter no. of students : ")) student_rec={} for i in range(1,a+1): pput(“Enter student name:") rollno=int(input(““Enter student roll no. :”)) ‘grade=input("Enter grade: ") student_recfrolino}={name,grade] name 1(input(”Enter rollno to search: print(student_rec[c]) Output: Teaco Ces ao See oa ime Ar a ete] Oe) Program 4 4a. Create a class to represent a book with attributes and methods. Code: class Book: def __init__ (self, title, author, genre, publication_year): self.title = title self.author = author self. genre = genre self. publication def title(self) return self.title def author(self): return self.author def genre(selt): return self.genre def publication_year(self) return self.publication_year def display_info(selt): return f"Title: {self.title}\nAuthor: {self.author} \nGenre: {self.genre}\nPublication Year {self-publication_year}\n" book! = Book("Verity", "Colleen Hoover", "Thriller", 2018) book2 = Book(""The Immortals of Meluha’,” Amish Tripathi”," Fantasy Fic print(book | display_info() print(book2.display_info() ‘ar= publication_year on",2010) Output: Test Taye ere ms tas tL) 4b. Write a python program to implement inheritance in the above class. Code: class Book: def __init__ (self, title, author, genre, publication_year): self.title = title self.author = author self.genre = genre self publication_year= publication_year def title(self) return self.title def author(self): return self.author def genre(selt) return self. genre def publication_year(self): return self.publication_year def display_info(self): return f"Title: {self.title}\nAuthor: {self.author}\nGenre: {self.genre }\nPublication Year: {self.publication_year}\n" class EBook(Book): def __init__(self, title, author, genre, price, file_size,file_format): super().__init__(title, author, genre, price) self.file_size = file_size self.file_format = file_format def file_size(selt): return self.file_size def file_format(self) return self.file_format def display_file_infoyselt): return f"File Size: {self.file_size)MB\nFile Format:{ self-file_format}" def display_info(self): book_info = super(.display_info() return book_info + {"\n{self.display_file_info()}" ebook! = EBook("Verity", "Colleen Hoover", "Thriller’,2018, 15, "PDF") print(ebook | display_infoO) Decent pee eg Sree Cia 4c. Write a python program to implement a generator function to generate the fibonacci sequence. Code: def fibonacci_generator(n): ab=0,1 print(a,b,end=" ") for i in range(n-2): carb print(c,end=' ab bee n=int(input("How many fibonacci numbers you want to print?")) fibonacci_generator(n) Output Term macy crs) eS ret SCT a Program 5 5a. Use lambda functions, map, and filter to perform operations on a list. Code: nume [1, 2, 3, 4, 5, 6, 7, 8,9, 10] print("Original list: ",num) square_num = list(map(lambda x: x**2, num) print(’Squared Numbers:", square_num) even_num = list(filter(lambda x: x % 2 print("Even Numbers:", even_num) 0, num) Output: red Numbers: [1, i b FSET) Pac Cee 5a. Create a module that contains functions for mathematical operations. Code: def add(a, b): return a+b def subtract(a, b): return ab def multiply(a, b): return a*b def divide(a, b): ifb print("Cannot divide by zero!") return a/b import mathopsmodule as mo a=10 b=5 print(mo.add(a, b)) #output: 15 print(mo.subtract(a, b)) #output: 5 print(mo.muhtiply(a, b)) #output: 50 print(mo.divideta, b)) #output:2.0 Program 6 6a, Create and manipulate NumPy arrays. Code: import numpy as np arrl=np.array({11,12,13]) arr2=np.array({{11,12,13],[14,15,16])) row=arr2[0,:]_#Accessing and Manipulating Arrays col=arr2[:,1] add=arrl+5 _#Element-wise operations multiply=arrl*2 sum_arr=arrl-+arrl product=arrl*arrl reshape=arrl reshape(3,1)_ #Reshape max_val=arrlmax() #Statistics min_val=arr].minQ) ‘mean=arrlmean() median=np.median(arrl) print("Original Array:") print(arrl) print("\nOriginal Matrix:") print(arr2) ng and Slicing:") row) print("Second Column:",col) print("\nElementwise Operatior print("arrl+5 ="Jadd) print("arrl*2 =",multiply) print("\nElement wise operation between arrays:") print(“arrl-+arrl =",sum_arr) prin(("arrl*arrl =",product) print("\nReshaped Array:\n" reshape) print("\nStatisties") print("Max Value:”,max_val) print("Min Value:" min_val) print(”Mean:" mean) print(”Median:" median) print("'Standard Deviat Output: Carty wea (oR ran es original Matrix creas! [14 15 16]] oes cue eCt First Row: [11 12 13] Second Column: [12 15] Beene eet Jarrt+5 = [16 17 18] Jarr1*2 = [22 24 26] eRe crs Cu ecu RE larrt+arrt = [22 24 26] jarri*arrt = [121 144 169] Coe Ue conB) rary aE B Statistics Max Value: 13 Min Value: 1 TP) CCE) ee mage SC MM RSTO tere er) Cems oneness 6b. Perform basic operations and indexing on arrays. Code: import numpy as np arr=np.array((1,2,3,4,5,6.7,8,9)) print("Original Array:",arr) print("Element at index 0:",arr(0]) print(‘Element at index 3:'arr[3}) sliced_arr=arr{ 1:5] print("Sliced Array:",sliced_arr) print(” Addition Result:" add) print("Subraction Result:" subtract) print("Multiplication Resul print("Divi Output: Carrara aoe alae Ue oa) Element at index she Wy peace al Ree Clete ta) ik Subraction Result: [3 3 3] Multiplication Result: [ 4 10 18] Division Result: [4 ] Program 7 7a. Implement string operations. Code: import numpy as np str_arr=np.array((["Delh concatenated_str=np.char.add(str_arr, print("Concatenated Array:",concatenated_str) split_arr=np.char.split(str_arr,'e’) print("Split Array:",split_arr) upper=np.char.upper(str_arr) print("Uppercase Array:”,upper) Jower=np.char.lower(str_arr) print("Lowercase Array:",lower) count=np.char.count(str_att,’) print("count of e in each string" count) Concatenated Array: ['Delhiis a city’ ‘Mumbaiis a city COR ae Loe sto) “Bangaloreis a city’] Chennaiis a city Conta ae ee REIS aD Tes DP ETICG aL TL yeep IB ELICG mre) rend tat Le Deas @ cu Cae ean 7 Nemo ae eS 9 7b. Use regular expressions to validate email addresses. Code: import re def valid_email(email): pattern=r'*f\w\-}+@[\w\-]+\.\w#" if re.match(patternemail): return True else: return False email1="name@ gmail.com" email2="yahoo-mail" email3="unknown@comdot.” print("Email | is valid:",valid_email(email1)) print("Email 2 is valid:" valid_email(email2)) print("Email 3 is valid:" valid_email(email3)) Output: alid: True Rees EIR ETE Program 8 8a, Read data from a text file and perform operations. Code: ob= open(‘poem.txt','r') ob.read() vow=con=upper=lower=0 for iin s: lpha() and i in 'aeiouAEIOU'): vow=vow+ isalpha() and i not in ‘aeiouAEIOU): con=con+1 for i ins: print("No. of vowels: if(iisupper() upper=upper+l elif(i.islower)): lower=lower+1 vow) print("No. of consonants:",con) print("No. of uppercase characters:" upper) print("No. of lowercase characters:” lower) Output: sare) eee) Cees pee ee 8b. Handle exceptions for file operations and input validations. Code: try: ob=open(file.txt" 1’) num=ob.read() print("Data read from file” num) sum_of_num=sum(num) average=sum_of_numv/len(num) ‘max_val=max(num) min_val=mim(num) print(”Sum of Numbers:",sum_of_num) print("Average:" average) print(”Maximum value: print(’Minimum value:",min_val) except FileNotFoundError print("!!File not found. Please check the file path!!") except ValueError: except ZeroDivisionError print(" Invalid data in the file!!") print("Cannot calculate the average with no data!! except Exception as e: print("An unexpected error occured" str(e)) Output: An unexpected error occured unsupported operand type(s) for ae (ia ie ete f

You might also like