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

rakesh assignment 3

Antivirus and rogue antivirus are quite different in purpose and functionality: 1. Antivirus: This is legitimate software designed to detect, prevent, and remove malware from computers and devices. It provides real-time protection, regularly updates its virus definitions, and scans for threats to keep systems secure. 2. Rogue Antivirus: This is a type of malicious software that pretends to be legitimate antivirus software. It often tricks users into downloading it by displaying fake alerts abo

Uploaded by

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

rakesh assignment 3

Antivirus and rogue antivirus are quite different in purpose and functionality: 1. Antivirus: This is legitimate software designed to detect, prevent, and remove malware from computers and devices. It provides real-time protection, regularly updates its virus definitions, and scans for threats to keep systems secure. 2. Rogue Antivirus: This is a type of malicious software that pretends to be legitimate antivirus software. It often tricks users into downloading it by displaying fake alerts abo

Uploaded by

520 Rakesh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 19
PYTHON ASSIGNMENT 3 M. Rakesh 1602-23-742-008 CSE 1LFiles: Write a program that reads a CSV file and prints each row as a dictionary. Prog: import pandas as pd dataset = pd.read_csv("annual-enterprise-survey-2019-financial-year-provisional-csv.csv") dataset-head() In [3]: 1 date = pen cov oma enterprise-suvey-2019-financal-yar-provisienl-es.c0) In [4]: 1 daasetsd0) otal 1 200 tt some sitvces Si at 2 ao oat som inane 22s 2 ame oat 0 inane «Br ae tot se mvontes p28 omg 2. Files: Create a program to merge the contents of two text files into a third file. Prog: data = data2 ="; with open(‘filel.txt’) as fp: data = fp.read() with open('file2.txt’) as fp: data2 = fp.read|) mn data += data2 data with open ('file3.tet', 'w') as fp: fp.write(data) [This 4s the content from file Hello There This 4s in filed Hello Geeks This ts in fle2 3. Files: Write a function that reads a binary file and returns its content as a list of integers. Prog: def read_binary_fie(filename): with opentfilename, 'rb') asf return list(fread()) 4, Exceptions: Write a program that demonstrates the use of the finally block by ensuring a file is closed after reading, Prog: def read_file(filename): try: with open(filename, 'r) as file: content =file.read{) print("File contents:") print(content) except FileNotFoundError: print(f"File “{filename}’ not found.") except |OError: print(f"Error reading file ‘{filenamey’.") finally # The finally’ block ensures that the file is closed regardless of exceptions try: file.close() except NameEtror: pass #fif the file was not opened successfully, 'file' won't be defined # Example usage: file_name = "sample.txt” read_file(file_name) ~~ Output err Cee aman cn nests tumors 5, Pickling: Write a program that pickles a list of objects (e.g., instances of a class) and then unpickles it Prog import pickle n= int(input("Enter the number of items")) (] # input list for din range(n): iter input("Enter data :" + str(d+1)+":") data.append((item)) file = open((list.pk’, ‘wb') pickle.dump(data, file) file.close() print("\n') Un-Pickling- pen ‘lst.pk', 'rb’) datao = pickle.load{fileo) fileo.close() print("showing data pickled") for {in datao: print(i) SE See SEey 6. Exceptions: Create a custom exception EmptyFileError and write a program that raises this exception if afile is empty. Prog: class EmptyFileError(Exception): pass def read_file(filename): try: with opentfilename, 'r') as f content = fread) if not content: raise EmptyFileError( "File is empty") return content except FileNotFoundError: Print("File not found") 7. Files and Pickling: Write a program to pickle a list of dictionaries (each representing a book with title, author, year) to a file and unpickle it back. Prog: import pickle books = [{"title": "Book1", "author": "Author1", "year": 2020}, {"title": "Book2", author": "Author2", "year": 2021}) with open('books.pickle’, 'wb') as f: pickle.dump(books, f) with open('books.pickle’, rb’) as f: loaded_books = pickle.load(f) for book in loaded_books: print(book{"title"], book{"author"], book{"year"|) 8, User-Defined Exceptions: Write a program that raises a PasswordTooShort€rror if a user-provided password is less than 8 characters. Prog: class PasswordTooShortError(Exception): "Custom exception for passwords that are too short.” def validate_password(password): “Validates the user-provided password." if len(password) < 8: raise PasswordTooShortError("Password must be at least 8 characters long") # Example usage: try: User_password = input("Enter your password: ") validate_password(user_password) print("Password is valid.") except PasswordTooShortError as e: print(f"Error: {e}") Output ieee en Ee psa Error: Password must be at least 8 characters long rsa SC uma eine 9. Files and Exceptions: Write a program that reads a configuration file and handles any missing key errors using try-except blocks. Prog: import json try: with open('configjson’,'"') asf: config = json.load(f) print(config{"key"l) except FileNotFoundError: print( "Config file not found") except KeyError: print("Key not found in contig file") 10.Exceptions: Write a function that demonstrates the use of nested try-except blocks by handling multiple levels of exceptions. Prog: try: try: #f code that may raise an exception x=1/0 except ZeroDivisionError: print("Inner exception caught") #f code that may raise another exception y=1/0 except ZeroDivisionEtror: print("Outer exception caught") Comers OL ess CuMe Tar Ciera tc SCM s Ser Rats umtccee ay 11.Classes and Objects: Write a class Student with attributes name, age, and grade. Include methods to display the student's information and to update the grade. Prog: class Student: def _ init__(self, name, age, grade} selfiname = name self.age = age self.grade = grade def display_info(selt) ‘Display student information print(f"Name: {self.name}") print(f"Age: {self.age) years") print(f"Grade: (self.grade}") def update_grade(self, new_grade): Update the student's grade. self grade = new_grade print(f"(self.name}'s grade has been updated to {self grade}") # Example usage: student = Student(name="Alice", age=18, grade="A") student1 display_info() # Display initial information student1.update_grade("B+") # Update the grade student display_infol) # Display updated information Output Tera vet’ Ceo cece Net CCE CURT i eos Treat ee cree fer ese st ume 0: self,_balance += amount print(f"Deposited ${amount). New balance: ${self,__balance}") else: print("Invalid deposit amount. Please provide a positive value." def withdraw(self, amount): ‘Withdraw money from the account. if 0 < amount <= self_balance: self._balance = amount print(f"Withdrew ${amount}. New balance: ${self,__balance}") else: print("Insufficient funds or invalid withdrawal amount.") def get_balance(selt} “'Get the current balance. return self, balance # Example usage: account = BankAccount(account_number="12345 ' initial_balance=1000) print(f" Account number: {account._BankAccount__account_number)") # Accessing private attribute account! .deposit(500) accountL.withdraw(200) print(f"Current balance: ${account!.get_balance()}") (oman Nectar ee EZ Es) Peposited $500. New balance: $1500 See RESO oS Cs EEL) urrent balance: $1300 er ets e accra me 17. Object Variables: Write a class Car with instance variables for make, model, and year. Include methods to display and update these variables, Prog: class Car: def _ init__(self, make, model, year): selfmake = make selfmodel = model def dispiay_info(selt} Display car information. print(f"Make: (self.make}") print(f"Model: (self.model)") print(f"Year: (selfyear}") def update_make(self, new_make): "Update the car's make." selfmake = new_make print(f"Make updated to: {selfmake}") def update_model(selt, new_model) "Update the car's model." selfmodel = new_mode! print(f*Model updated to: {self.model}") def update_year(self, new_year): "Update the car's year.""" selfyear = new_year print(f"Year updated to: {self year)") # Example usage: my_car = Car(make="Toyota", model="Camry", year=2020) my_cardisplay_info() my_car.update_make("Honda") my_car-update_model|"Accord") my_car.update_year(2022) my_cardisplay_info() Coan TCO nt Dees Reng SELL Make updated to: Honda Creo Ms ceo ace Smt et Prd CeCe) Tre ease] Seely er eesti mace 18.Inheritance: Create a base class Shape with a method to calculate area. Derive two classes Circle and ‘Square from Shape and override the area method. Prog: import math class Shape: def calculate_area(set) "Calculate the area (to be overridden by subclasses).""” pass class Circle(Shape}: def __init_(self, radius): self.radius = radius def calculate_area(selt) “Calculate the area of a circle.’ return math.pi* selfradius ** 2 class Square(Shape): def __init_{(self, side_length): self.side_length = side_length def calculate_area(selt) “Calculate the area of a square. return selfside_length ** 2 # Example usage: circled = Circle(radius=5) squarel = Square(side_length=4) print(f*Circle area: {circle1.calculate_area():.2f} square units") print(f'Square area: {square1.calculate_area()} square units") Corn ts + RSC ee eee Ta Ore a Ee Mn er SSC cc eine 19.Class and Object: Write a class Library with methods to add and remove books. Each book can be represented asa dictionary with title, author, and ISBN. Prog: class Library: def _ init__(self): 1 self.book: def add_book(self, title, author, ISBN]: book "title": title, "author": author, "ISBN": ISBN} self.books.append(book) def remove_book(self, ISBN): for book in self.books: if book{"ISBN") ISBN: self.books.remove(book) print("Book removed") return print("Book not found") def display_books(selt): for book in self.books: print(book) 20.0perator Overloading: Create a class Vector to represent a mathematical vector. Overload the * operator to perform the dot product of two vectors. Prog: class Vector: def __init__(self, components): self.components = components def _mul_(self, other): "Overload the * operator for dot product." if len(self.components) len(other.components): raise ValueError("Vectors must have the same dimension for dot product") return sum(a * b for a, b in zip(self.components, other.components)) i Example usage: vector = Vector(components=(1, 2, 3]) vector2 fector(components=[4, 5, 6]) vector * vector2 dot_product print(f"Dot product: {dot_product}") Ca Pirates ener Coma Stuer

You might also like