1]
#python program
def printPicnic(itemsDict, leftWidth, rightWidth):
print('PICNIC ITEMS'.center(leftWidth + rightWidth, '-'))
for k, v in itemsDict.items():
print(k.ljust(leftWidth, '.') + str(v).rjust(rightWidth))
# Defining the picnic items dictionary
picnicItems = {'sandwiches': 4,'apples': 12,'cups': 4,'cookies': 8000}
# Printing the picnic items with different widths
printPicnic(picnicItems, 12, 5)
printPicnic(picnicItems, 20, 6)
2]
#python program
import re
# Sample text for testing
text = """
From: alice@example.com
To: bob@example.com
"""
from_regex = re.compile(r'From: (\S+@\S+)')
to_regex = re.compile(r'To: (\S+@\S+)')
from_addresses = from_regex.findall(text)
print("From addresses:", from_addresses)
# Extract 'To' email addresses
to_addresses = to_regex.findall(text)
print("To addresses:", to_addresses)
3]
Class: A class in Python is a blueprint for creating objects. It defines a set of attributes
and methods that the created objects can use.
Object: An object is an instance of a class. When a class is defined, no memory is
allocated until an object of that class is instantiated.
Attribute: Attributes are variables that belong to a class or an
object. They are used to store data for objects created from the class
#python program
# Define a class named Person
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def display(self):
print(f"Name: {self.name}")
print(f"Age: {self.age}")
person1 = Person("Alice", 30)
print("Person 1 Details:")
person1.display()
person2 = Person("Bob", 25)
print("\nPerson 2 Details:")
person2.display()
4]
class Point:
def __init__(self, x=0.0, y=0.0):
self.x = x
self.y = y
class Rectangle:
def __init__(self, width=100.0, height=200.0, corner=None):
self.width = width
self.height = height
if corner is None:
self.corner = Point() # Default corner at (0.0, 0.0)
else:
self.corner = corner # Custom corner point
# Creating an instance of Rectangle
box = Rectangle()
# Displaying the attributes of the rectangle
print("Width:", box.width)
print("Height:", box.height)
print("Corner x:", box.corner.x)
print("Corner y:", box.corner.y)
OUTPUT:
Width: 100.0
Height: 200.0
Corner x: 0.0
Corner y: 0.0