PythonLab_4
PythonLab_4
1 Lab 4
1.1 Muhammad Haider
1.2 ITF-11126
##1. Create a Simple Class: ### Define a class Car with attributes brand, model, and year.
### Create an instance of the class and print the attributes.
[1]: class Car:
def __init__(self, brand, model, year):
self.brand = brand
self.model = model
self.year = year
print(f"Brand: {my_car.brand}")
print(f"Model: {my_car.model}")
print(f"Year: {my_car.year}")
Brand: Toyota
Model: Corolla
Year: 2022
def display_info(self):
print(f"Car Info: {self.year} {self.brand} {self.model}")
1
my_car = Car("Toyota", "Corolla", 2022)
my_car.display_info()
def get_year(self):
return self._year
def display_info(self):
print(f"Car Info: {self._year} {self.brand} {self.model}")
class ElectricCar(Car):
def __init__(self, brand, model, year, battery_capacity):
super().__init__(brand, model, year)
self.battery_capacity = battery_capacity
def battery_info(self):
print(f"Battery Capacity: {self.battery_capacity} kWh")
2
my_car = Car("Toyota", "Corolla", 2022)
my_car.display_info()
print(my_car.get_year())
my_car.set_year(2025)
print(my_car.get_year())
def get_year(self):
return self._year
def display_info(self):
print(f"Car Info: {self._year} {self.brand} {self.model}")
def __str__(self):
return f"{self._year} {self.brand} {self.model}"
3
2022 Toyota Corolla
##Basic Function: Write a function calculate_sum(a, b) that takes two numbers and returns their
sum.
##7. Function with Default Parameters: Create a function greet(name=“Guest”) that prints
“Hello, {name}!”. If no name is provided, it should greet “Guest” by default. ##8. Lambda
Function: Write a lambda function to find the square of a number and apply it to a list [2, 4, 6, 8]
using the map() function.
##9. Recursive Function: Implement a recursive function to calculate the factorial of a number.
[7]: def calculate_sum(a, b):
return a + b
def greet(name="Guest"):
print(f"Hello, {name}!")
square = lambda x: x ** 2
numbers = [2, 4, 6, 8]
squared_numbers = list(map(square, numbers))
def factorial(n):
return 1 if n == 0 else n * factorial(n - 1)
print(calculate_sum(5, 10))
greet()
greet("Alice")
print(squared_numbers)
print(factorial(5))
15
Hello, Guest!
Hello, Alice!
[4, 16, 36, 64]
120
Alice: 85
Bob: 78
Charlie: 92