Pythonans 3 Ia
Pythonans 3 Ia
Program:
def divide(a, b):
assert b != 0, "Division by zero is not allowed"
return a / b
numerator = 10
denominator = 0
try:
result = divide(numerator, denominator)
except AssertionError as e:
print(f"Assertion Error: {e}")
else:
print(f"Result: {result}")
Raising Exceptions:
Exceptions are used to handle errors and exceptional conditions during
the execution of your program. Unlike assertions, exceptions are not
limited to debugging purposes and are essential for robust error handling
in your code.
Program:
def divide(a, b):
if b == 0:
raise ValueError("Division by zero is not allowed")
return a / b
numerator = 10
denominator = 0
try:
result = divide(numerator, denominator)
except ValueError as e:
print(f"Value Error: {e}")
else:
print(f"Result: {result}")
Prototype Phase:
Initial Prototype: Create a basic mobile app that allows users to add, view,
and delete tasks. The interface is minimal, focusing on core functionality.
Demonstration: Share the prototype with potential users, team members,
and stakeholders.
Feedback: Users and stakeholders provide feedback, suggesting
additional features such as task prioritization, due dates, and task
categories.
Patch Phase:
Patch 1: Add task prioritization (e.g., high, medium, low) to the app.
Patch 2: Implement due dates for tasks, allowing users to set deadlines.
Patch 3: Introduce task categories and the ability to organize tasks by
category.
Patch 4: Improve the user interface, incorporating feedback on usability
and aesthetics.
Continue this iterative process, adding features and addressing issues
based on feedback and evolving requirements.
def Print_time(input_time):
if isinstance(input_time, time):
formatted_time = input_time.strftime("%H:%M:%S")
print(formatted_time)
else:
print("Invalid input. Please provide a valid time object.")
# Example usage:
if __name__ == "__main__":
# Create a time object (hour=10, minute=30, second=45)
input_time = time(10, 30, 45)
# Create a logger for your module (usually one logger per module)
logger = logging.getLogger(__name__)
if __name__ == "__main__":
# Perform a division operation
divide(10, 2)
divide(10, 0) # This will log an error message
def __str__(self):
if self.imag >= 0:
return f"{self.real} + {self.imag}i"
else:
return f"{self.real} - {-self.imag}i"
def __str__(self):
return f"{self.hour:02d}:{self.minute:02d}:{self.second:02d}"
def speak(self):
pass # This method will be overridden in the subclasses
class Dog(Animal):
def speak(self):
return f"{self.name} says Woof!"
class Cat(Animal):
def speak(self):
return f"{self.name} says Meow!"
class Duck(Animal):
def speak(self):
return f"{self.name} says Quack!"
Example:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
__str__ method:
The __str__ method is used to define a human-readable string
representation of an object. It is called when the str() function is applied
to an object or when the print() function is used with the object.
It should return a string that represents the object in a clear and
informative way.
This method is helpful for debugging and providing a meaningful string
representation of an object.
Example:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"Name: {self.name}, Age: {self.age}"
person_str = str(person2)
print(person_str) # Output: Name: Bob, Age: 25
Exaclass Shape:
def area(self):
pass
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius * self.radius
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
def calculate_area(shape):
if isinstance(shape, Shape):
return shape.area()
else:
raise ValueError("Unsupported shape")
def add_to_total(value):
global total
total += value
add_to_total(5)
add_to_total(3)
shallow_copied_list = copy.copy(original_list)
shallow_copied_list[1][0] = 99
print(original_list) # Output: [1, [99, 3], [4, 5]]
print(shallow_copied_list) # Output: [1, [99, 3], [4, 5]]
Deep Copy:
• A deep copy of an object creates a new object that is a fully
independent copy of the original object and all its nested objects.
• It recursively copies all objects referenced by the original object,
creating a new instance for each one.
• Changes made to nested objects inside the copied object do not
affect the original object, and vice versa.
• You can use the copy module's deepcopy() function to create a
deep copy.
Example:
import copy
deep_copied_list = copy.deepcopy(original_list)
deep_copied_list[1][0] = 99
12. Define a class. Explain how classes & objects are created in
python
Ans.
A class is a blueprint or a template for creating objects. It defines the
structure and behavior of objects that will be created based on that class.
A class can have attributes (data members) and methods (functions) that
define the characteristics and actions of the objects it represents. Classes
provide a way to model real-world entities and their interactions in a
program, promoting code organization and reuse.
Example:
class MyClass:
# Constructor method (optional)
def __init__(self, attribute1, attribute2):
self.attribute1 = attribute1
self.attribute2 = attribute2
# Instance method
def display_attributes(self):
print(f"Attribute 1: {self.attribute1}")
print(f"Attribute 2: {self.attribute2}")
def __str__(self):
return f"({self.x}, {self.y})"
class Point:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def read_point(self):
self.x = float(input("Enter the x-coordinate: "))
self.y = float(input("Enter the y-coordinate: "))
def print_point(self):
print(f"({self.x}, {self.y})")
# Example usage
if __name__ == "__main__":
point1 = Point()
print("Enter coordinates for Point 1:")
point1.read_point()
point2 = Point()
print("Enter coordinates for Point 2:")
point2.read_point()
distance = point1.distance(point2)
print("Distance between Point 1 and Point 2:", distance)
class Dog(Animal):
def speak(self):
return "Woof!"
class Cat(Animal):
def speak(self):
return "Meow!"
def animal_sound(animal):
return animal.speak()
dog = Dog()
cat = Cat()
Inheritance in Python:
Inheritance is a mechanism in object-oriented programming that allows a
new class (subclass or derived class) to inherit properties and methods
from an existing class (superclass or base class). It promotes code reuse
and the creation of a hierarchy of classes, where the subclass can extend
or override the behavior of the superclass.
Example:
class Vehicle:
def __init__(self, brand, model):
self.brand = brand
self.model = model
def display_info(self):
return f"{self.brand} {self.model}"
class Car(Vehicle):
def __init__(self, brand, model, num_doors):
super().__init__(brand, model)
self.num_doors = num_doors
def display_info(self):
return f"{super().display_info()}, {self.num_doors} doors"
class Motorcycle(Vehicle):
def __init__(self, brand, model, engine_capacity):
super().__init__(brand, model)
self.engine_capacity = engine_capacity
def display_info(self):
return f"{super().display_info()}, {self.engine_capacity} cc engine"